
    jh             
          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+c m,c m-Z, d dl.m/Z/ erd 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e'      Z>	  G d de      Z? G d de?e>      Z@ G d de      ZA G d d e'ed          ZB G d! d"e'      ZC G d# d$e&      ZD G d% d&e      ZE G d' d(e      ZF G d) d*e      ZG G d+ d,e      ZH G d- d.e      ZI G d/ d0e      ZJ G d1 d2eEeFeGeHeIeJ      ZK G d3 d4e      ZL G d5 d6e      ZMe G d7 d8             ZN G d9 d:eMe=      ZO G d; d<e      ZP G d= d>e      ZQ G d? d@e      ZR G dA dBe      ZS G dC dDe      ZT G dE dFe      ZU G dG dHe      ZV G dI dJe      ZW G dK dLe      ZX G dM dNe      ZY G dO dPe      ZZ G dQ dRe      Z[ G dS dTedT   ee;j                           Z] G dU dVe      Z^ G dW dXe=      Z_ G dY dZe      Z`y)[    )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                   N    e Zd ZU dZeed<   edee   fd       Z	ede
fd       Zy)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                      y)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 selfs    -/Users/sumanjeet/code/py-libp2p/libp2p/abc.pyget_transport_addressesz&IRawConnection.get_transport_addressesZ   s     	    c                      yzD
        Get the type of connection (direct, relayed, etc.)
        Nr,   r-   s    r/   get_connection_typez"IRawConnection.get_connection_typed       
 	r1   N)__name__
__module____qualname____doc__bool__annotations__r   listr   r0   r   r4   r,   r1   r/   r(   r(   J   sG     i   ^  r1   r(   c                   h    e Zd ZdZedefd       Zedefd       Zedefd       Z	ede
fd       Zy)AbstractSecureConnz
    Abstract interface for secure connections.

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

    r*   c                      y)z\
        Retrieve the local peer's identifier.

        :return: The local peer ID.
        Nr,   r-   s    r/   get_local_peerz!AbstractSecureConn.get_local_peer}       r1   c                      y)zm
        Retrieve the local peer's private key.

        :return: The private key of the local peer.
        Nr,   r-   s    r/   get_local_private_keyz(AbstractSecureConn.get_local_private_key   rA   r1   c                      y)z^
        Retrieve the remote peer's identifier.

        :return: The remote peer ID.
        Nr,   r-   s    r/   get_remote_peerz"AbstractSecureConn.get_remote_peer   rA   r1   c                      y)zm
        Retrieve the remote peer's public key.

        :return: The public key of the remote peer.
        Nr,   r-   s    r/   get_remote_public_keyz(AbstractSecureConn.get_remote_public_key   rA   r1   N)r6   r7   r8   r9   r   r   r@   r   rC   rE   r   rG   r,   r1   r/   r>   r>   t   ss        z      y  r1   r>   c                       e Zd ZdZy)ISecureConnzv
    Interface for a secure connection.

    Combines secure connection functionalities with raw I/O operations.

    N)r6   r7   r8   r9   r,   r1   r/   rI   rI      s    r1   rI   c                   2   e Zd ZU dZeed<   ej                  ed<   ede	deddfd       Z
eedefd              Zedd	       Zedd
       Zeedefd              Zeedefd              Zedd       Zedd       Zedee   fd       Zedefd       Zy)
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                      y)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.   rN   rL   s      r/   __init__zIMuxedConn.__init__   rA   r1   c                      y)z
        Determine if this connection is the initiator.

        :return: True if this connection initiated the connection,
            otherwise False.
        Nr,   r-   s    r/   r)   zIMuxedConn.is_initiator   rA   r1   c                    K   yw)z)
        Start the multiplexer.

        Nr,   r-   s    r/   startzIMuxedConn.start           c                    K   yw)z4
        Close the multiplexed connection.

        Nr,   r-   s    r/   closezIMuxedConn.close   rU   rV   c                      y)z
        Check if the connection is fully established and ready for streams.

        :return: True if the connection is established, otherwise False.
        Nr,   r-   s    r/   is_establishedzIMuxedConn.is_established   rA   r1   c                      yz
        Check if the connection is fully closed.

        :return: True if the connection is closed, otherwise False.
        Nr,   r-   s    r/   	is_closedzIMuxedConn.is_closed   rA   r1   c                    K   yw)zm
        Create and open a new multiplexed stream.

        :return: A new instance of IMuxedStream.
        Nr,   r-   s    r/   open_streamzIMuxedConn.open_stream   rU   rV   c                    K   yw)z
        Accept a new multiplexed stream initiated by the remote peer.

        :return: A new instance of IMuxedStream.
        Nr,   r-   s    r/   accept_streamzIMuxedConn.accept_stream   rU   rV   c                      y)zH
        Get transport addresses by delegating to secured_conn.
        Nr,   r-   s    r/   r0   z"IMuxedConn.get_transport_addresses  r5   r1   c                      y)zD
        Get connection type by delegating to secured_conn.
        Nr,   r-   s    r/   r4   zIMuxedConn.get_connection_type  r5   r1   r*   Nr*   IMuxedStream)r6   r7   r8   r9   r   r;   trioEventr   rI   rQ   propertyr:   r)   rT   rX   rZ   r]   r_   ra   r<   r   r0   r   r4   r,   r1   r/   rK   rK      s9     K::  
	  d            4        i   ^  r1   rK   c                       e Zd ZU dZeed<   edd       Zededdfd       Z	edd       Z
d	ee   dz  d
edz  dedz  ddfdZy)rf   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                    K   yw)z
        Reset the stream.

        This method closes both ends of the stream, instructing the remote
        side to hang up.
        Nr,   r-   s    r/   resetzIMuxedStream.reset$  rU   rV   ttlc                      y)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.   rn   s     r/   set_deadlinezIMuxedStream.set_deadline-  rA   r1   c                    K   | S w)z Enter the async context manager.r,   r-   s    r/   
__aenter__zIMuxedStream.__aenter__6  s      s   exc_typeexc_valexc_tbc                 @   K   | j                          d{    y7 w)z4Exit the async context manager and close the stream.N)rX   )r.   rt   ru   rv   s       r/   	__aexit__zIMuxedStream.__aexit__;  s      jjls   rd   re   )r6   r7   r8   r9   rK   r;   r   rm   intrq   rs   typeBaseExceptionr   rx   r,   r1   r/   rf   rf     s    
        }%, % $	
 
r1   rf   c                       e Zd ZU dZeed<   ej                  e   dz  ed<   e	de
dz  fd       Ze	de
ddfd       Ze	d
d	       Zy)
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.

    rk   Nmetric_send_channelr*   c                      y)z
        Retrieve the protocol identifier for the stream.

        :return: The protocol ID associated with the stream.
        Nr,   r-   s    r/   get_protocolzINetStream.get_protocolX  rA   r1   protocol_idc                      y)z
        Set the protocol identifier for the stream.

        :param protocol_id: The protocol ID to assign to the stream.
        Nr,   r.   r   s     r/   set_protocolzINetStream.set_protocol`  rA   r1   c                    K   yw)z`
        Reset the network stream.

        This method closes both ends of the stream.
        Nr,   r-   s    r/   rm   zINetStream.reseth  rU   rV   rd   )r6   r7   r8   r9   rK   r;   rg   MemorySendChannelr   r   r   r   r   rm   r,   r1   r/   r}   r}   H  sy    
 //4t;;i$.   	 d    r1   r}   c                       e Zd ZU dZeed<   ej                  ed<   ee	de
fd              Ze	defd       Ze	deedf   fd       Ze	dee   fd	       Ze	defd
       Zy)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.

    rk   rM   r*   c                      yr\   r,   r-   s    r/   r]   zINetConn.is_closed  rA   r1   c                    K   yw)zr
        Create a new network stream over the connection.

        :return: A new instance of INetStream.
        Nr,   r-   s    r/   
new_streamzINetConn.new_stream  rU   rV   .c                      y)z
        Retrieve all active streams associated with this connection.

        :return: A tuple containing instances of INetStream.
        Nr,   r-   s    r/   get_streamszINetConn.get_streams  rA   r1   c                      y)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-   s    r/   r0   z INetConn.get_transport_addresses  rA   r1   c                      yr3   r,   r-   s    r/   r4   zINetConn.get_connection_type  r5   r1   N)r6   r7   r8   r9   rK   r;   rg   rh   ri   r   r:   r]   r}   r   tupler   r<   r   r0   r   r4   r,   r1   r/   r   r   t  s     ::4    *   U:s?3   i   ^  r1   r   c            	       j    e Zd ZdZedededefd       Zededededdfd       Z	ededdfd	       Z
y)
IPeerMetadataz
    Interface for managing peer metadata.

    Provides methods for storing and retrieving metadata associated with peers.
    rL   keyr*   c                      y)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.   rL   r   s      r/   getzIPeerMetadata.get  rA   r1   valNc                      y)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.   rL   r   r   s       r/   putzIPeerMetadata.put  rA   r1   c                      y)z
        Remove all stored metadata for the specified peer.

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

        Nr,   r.   rL   s     r/   clear_metadatazIPeerMetadata.clear_metadata  rA   r1   )r6   r7   r8   r9   r   r   strr   r   r   r   r,   r1   r/   r   r     s     2 C M   2 C m    	b 	T 	 	r1   r   c            	           e Zd ZdZededededdfd       Zedede	e   deddfd	       Z
ededee   fd
       Zededdfd       Zedee   fd       Zy)	IAddrBookz[
    Interface for an address book.

    Provides methods for managing peer addresses.
    rL   addrrn   r*   Nc                      y)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.   rL   r   rn   s       r/   add_addrzIAddrBook.add_addr  rA   r1   addrsc                      y)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.   rL   r   rn   s       r/   	add_addrszIAddrBook.add_addrs  rA   r1   c                      y)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,   r   s     r/   r   zIAddrBook.addrs  rA   r1   c                      y)z
        Remove all stored addresses for the specified peer.

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

        Nr,   r   s     r/   clear_addrszIAddrBook.clear_addrs   rA   r1   c                      y)z
        Retrieve all peer identifiers that have stored addresses.

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

        Nr,   r-   s    r/   peers_with_addrszIAddrBook.peers_with_addrs,  rA   r1   )r6   r7   r8   r9   r   r   r   ry   r   r	   r   r<   r   r   r   r,   r1   r/   r   r     s      ) # $  "  HY,? c d  & R DO    	2 	$ 	 	 	$r( 	 	r1   r   c                   h    e Zd ZdZedddedefd       Zedede	d   fd       Z
ededd	fd
       Zy	)ICertifiedAddrBookzh
    Interface for a certified address book.

    Provides methods for managing signed peer records
    enveloper!   rn   r*   c                      y)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   rn   s      r/   consume_peer_recordz&ICertifiedAddrBook.consume_peer_recordA  rA   r1   rL   c                      y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,   r   s     r/   get_peer_recordz"ICertifiedAddrBook.get_peer_recordW  rA   r1   Nc                      y)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,   r   s     r/   maybe_delete_peer_recordz+ICertifiedAddrBook.maybe_delete_peer_recordi  rA   r1   )r6   r7   r8   r9   r   ry   r:   r   r   r   r   r   r,   r1   r/   r   r   :  sy     J S T  * r hz.B  "  t  r1   r   c                       e Zd ZdZededefd       Zededefd       Z	edededdfd       Z
eded	eddfd
       Zedededdfd       Zedee   fd       Zededdfd       Zy)IKeyBookz[
    Interface for an key book.

    Provides methods for managing cryptographic keys.
    rL   r*   c                      y)z
        Returns the public key of the specified peer

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

        Nr,   r   s     r/   pubkeyzIKeyBook.pubkey  rA   r1   c                      y)z
        Returns the private key of the specified peer

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

        Nr,   r   s     r/   privkeyzIKeyBook.privkey  rA   r1   r   Nc                      y)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.   rL   r   s      r/   
add_pubkeyzIKeyBook.add_pubkey  rA   r1   r   c                      y)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.   rL   r   s      r/   add_privkeyzIKeyBook.add_privkey  rA   r1   key_pairc                      y)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.   rL   r   s      r/   add_key_pairzIKeyBook.add_key_pair  rA   r1   c                      yz/Returns all the peer IDs stored in the AddrBookNr,   r-   s    r/   peer_with_keyszIKeyBook.peer_with_keys  rA   r1   c                      yz
        Remove all stored keydata for the specified peer.

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

        Nr,   r   s     r/   clear_keydatazIKeyBook.clear_keydata  rA   r1   )r6   r7   r8   r9   r   r   r   r   r   r   r   r   r   r   r<   r   r   r,   r1   r/   r   r   }  s    	b 	Y 	 	 	r 	j 	 	 " i D   2 
 t   B ' d   >R > > 	R 	D 	 	r1   r   c                   b    e Zd ZdZedededdfd       Zededefd       Zededdfd       Z	y)	IMetricszd
    Interface for metrics of peer interaction.

    Provides methods for managing the metrics.
    rL   RTTr*   Nc                      y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.   rL   r   s      r/   record_latencyzIMetrics.record_latency  rA   r1   c                      y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,   r   s     r/   latency_EWMAzIMetrics.latency_EWMA  rA   r1   c                      y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,   r   s     r/   clear_metricszIMetrics.clear_metrics  rA   r1   )
r6   r7   r8   r9   r   r   floatr   r   r   r,   r1   r/   r   r     st     b u    
B 
5 
 
 	R 	D 	 	r1   r   c                      e Zd ZdZededee   fd       Zedede	e   ddfd       Z
edede	e   ddfd       Zedede	e   ddfd	       Zedede	e   dee   fd
       Zedede	e   defd       Zededdfd       Zy)
IProtoBookzl
    Interface for a protocol book.

    Provides methods for managing the list of supported protocols.
    rL   r*   c                      y)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,   r   s     r/   get_protocolszIProtoBook.get_protocols  rA   r1   	protocolsNc                      y)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.   rL   r   s      r/   add_protocolszIProtoBook.add_protocols!  rA   r1   c                      y)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   s      r/   set_protocolszIProtoBook.set_protocols0  rA   r1   c                      y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   s      r/   remove_protocolszIProtoBook.remove_protocols?  rA   r1   c                      y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   s      r/   supports_protocolszIProtoBook.supports_protocolsN  rA   r1   c                      y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   s      r/   first_supported_protocolz#IProtoBook.first_supported_protocol^  rA   r1   c                      y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,   r   s     r/   clear_protocol_datazIProtoBook.clear_protocol_datas  rA   r1   )r6   r7   r8   r9   r   r   r<   r   r   r	   r   r   r   r   r   r   r,   r1   r/   r   r     s6    	R 	DI 	 	 R HSM d   R HSM d    x}    " # 4PS9    x} QT  ( 	2 	$ 	 	r1   r   c            	           e Zd ZdZedededefd       Zededededdfd       Z	ededdfd	       Z
eded
ededdfd       Zededee   deddfd       Zededee   fd       Zededdfd       Zedee   fd       Zeded   fd       Zed5d       Zedddedefd       Zededed   fd       Zededdfd       Zededefd       Zededefd       Zedededdfd       Zedededdfd       Z edede!ddfd        Z"edee   fd!       Z#ededdfd"       Z$eded#e%ddfd$       Z&edede%fd%       Z'ededdfd&       Z(ededee   fd'       Z)eded(ee   ddfd)       Z*eded(ee   ddfd*       Z+eded(ee   ddfd+       Z,eded(ee   dee   fd,       Z-eded(ee   defd-       Z.ededdfd.       Z/edede0fd/       Z1edee   fd0       Z2ededefd1       Z3ededdfd2       Z4ed6d3eddfd4       Z5y)7
IPeerStorez
    Interface for a peer store.

    Provides methods for managing peer information including address
    management, protocol handling, and key storage.
    rL   r   r*   c                      y)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,   r   s      r/   r   zIPeerStore.get  rA   r1   r   Nc                      y)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,   r   s       r/   r   zIPeerStore.put  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.clear_metadata  rA   r1   r   rn   c                      y)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,   r   s       r/   r   zIPeerStore.add_addr  rA   r1   r   c                      y)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   s       r/   r   zIPeerStore.add_addrs  rA   r1   c                      y)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,   r   s     r/   r   zIPeerStore.addrs  rA   r1   c                      y)z
        Clear all addresses for the specified peer.

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

        Nr,   r   s     r/   r   zIPeerStore.clear_addrs  rA   r1   c                      y)z
        Retrieve all peer identifiers with stored addresses.

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

        Nr,   r-   s    r/   r   zIPeerStore.peers_with_addrs   rA   r1   r!   c                      y)z-Get the local-peer-record wrapped in EnvelopeNr,   r-   s    r/   get_local_recordzIPeerStore.get_local_record  rA   r1   r   c                      y)z-Set the local-peer-record wrapped in EnvelopeNr,   )r.   r   s     r/   set_local_recordzIPeerStore.set_local_record  rA   r1   c                      y)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   s      r/   r   zIPeerStore.consume_peer_record  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.get_peer_record+  rA   r1   c                      y)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,   r   s     r/   r   z#IPeerStore.maybe_delete_peer_record=  rA   r1   c                      y)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,   r   s     r/   r   zIPeerStore.pubkeyO  rA   r1   c                      y)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,   r   s     r/   r   zIPeerStore.privkeye  rA   r1   r   c                      y)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   s      r/   r   zIPeerStore.add_pubkey{  rA   r1   r   c                      y)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   s      r/   r   zIPeerStore.add_privkey  rA   r1   r   c                      y)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   s      r/   r   zIPeerStore.add_key_pair  rA   r1   c                      yr   r,   r-   s    r/   r   zIPeerStore.peer_with_keys  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.clear_keydata  rA   r1   r   c                      yr   r,   r   s      r/   r   zIPeerStore.record_latency  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.latency_EWMA  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.clear_metrics  rA   r1   c                      y)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,   r   s     r/   r   zIPeerStore.get_protocols  rA   r1   r   c                      y)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   s      r/   r   zIPeerStore.add_protocols  rA   r1   c                      y)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   s      r/   r   zIPeerStore.set_protocols  rA   r1   c                      yr   r,   r   s      r/   r   zIPeerStore.remove_protocols!  rA   r1   c                      yr   r,   r   s      r/   r   zIPeerStore.supports_protocols0  rA   r1   c                      yr   r,   r   s      r/   r   z#IPeerStore.first_supported_protocol@  rA   r1   c                      yr   r,   r   s     r/   r   zIPeerStore.clear_protocol_dataU  rA   r1   c                      y)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,   r   s     r/   	peer_infozIPeerStore.peer_infob  rA   r1   c                      y)z
        Retrieve all peer identifiers stored in the peer store.

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

        Nr,   r-   s    r/   peer_idszIPeerStore.peer_idss  rA   r1   c                      y)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,   r   s     r/   has_peerzIPeerStore.has_peer  rA   r1   c                      y)clear_peerdataNr,   r   s     r/   r  zIPeerStore.clear_peerdata  rA   r1   cleanup_intervalc                    K   yw)z=Start periodic cleanup of expired peer records and addresses.Nr,   )r.   r  s     r/   start_cleanup_taskzIPeerStore.start_cleanup_task  rU   rV   )r   r!   r*   N)i  )6r6   r7   r8   r9   r   r   r   r   r   r   r   r   ry   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   r   r  r  r  r  r  r,   r1   r/   r   r     s;    2 C M  . 2 C m    	b 	T 	 	  ) # $    HY,? c d   R DO    	2 	$ 	 	 	$r( 	 	 <(:"6 < < < < J S T  ( r hz.B  "  t  " b Y  * r j  * " i D  $ 2 
 t  $ B ' d  $ >R > > 	R 	D 	 	 b u    
B 
5 
 
 	R 	D 	 	 R DI  * R HSM d   R HSM d    x}    " # 4PS9    x} QT  ( 	2 	$ 	 	      	$r( 	 	  t  * b T   L L L Lr1   r   c                   \    e Zd ZdZededdfd       Zedeedf   fd       Zed	d       Z	y)
	IListenerz
    Interface for a network listener.

    Provides methods for starting a listener, retrieving its addresses,
    and closing it.
    maddrr*   Nc                    K   yw)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"  s     r/   listenzIListener.listen  rU   rV   .c                      y)z
        Retrieve the list of addresses on which the listener is active.

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

        Nr,   r-   s    r/   	get_addrszIListener.get_addrs  rA   r1   c                    K   yw)z&
        Close the listener.

        Nr,   r-   s    r/   rX   zIListener.close        	rV   rd   )
r6   r7   r8   r9   r   r   r%  r   r'  rX   r,   r1   r/   r!  r!    sa     )   , 	5C0 	 	  r1   r!  c                      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       Zeddedz  dee	   fd	       Zedeeee	   f   fd
       Zedede	dz  fd       Zededee	   fd       Zededefd       Zededede	fd       Zedededefd       Zededdfd       Zededefd       Zedd       Zedd       Zedd       Zededdfd       Z y)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.

    	peerstoreconnections	listenersr*   c                      y)z
        Retrieve the peer identifier for this network.

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

        Nr,   r-   s    r/   get_peer_idzINetwork.get_peer_id  rA   r1   NrL   c                      y)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,   r   s     r/   get_connectionszINetwork.get_connections  rA   r1   c                      y)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-   s    r/   get_connections_mapzINetwork.get_connections_map  rA   r1   c                      y)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,   r   s     r/   get_connectionzINetwork.get_connection  rA   r1   c                    K   yw)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,   r   s     r/   	dial_peerzINetwork.dial_peer)  rU   rV   c                    K   yw)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,   r   s     r/   r   zINetwork.new_stream?  rU   rV   raw_connc                    K   yw)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:  rL   s      r/   upgrade_outbound_raw_connz"INetwork.upgrade_outbound_raw_connP  rU   rV   r"  c                    K   yw)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"  s      r/   upgrade_inbound_raw_connz!INetwork.upgrade_inbound_raw_connj  rU   rV   stream_handlerc                      y)z
        Set the stream handler for incoming streams.

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

        Nr,   )r.   rA  s     r/   set_stream_handlerzINetwork.set_stream_handler  rA   r1   
multiaddrsc                    K   yw)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.   rD  s     r/   r%  zINetwork.listen  rU   rV   c                      y)z
        Register a notifee instance to receive network events.

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

        Nr,   r.   notifees     r/   register_notifeezINetwork.register_notifee  rA   r1   c                      y)z
        Unregister a notifee instance so it stops receiving network events.

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

        Nr,   rG  s     r/   remove_notifeezINetwork.remove_notifee  rA   r1   c                    K   yw)zQ
        Close the network and all associated connections and listeners.
        Nr,   r-   s    r/   rX   zINetwork.close  rU   rV   c                    K   yw)z
        Close the connection to the specified peer.

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

        Nr,   r   s     r/   
close_peerzINetwork.close_peer  rU   rV   N)rH  INotifeer*   Nrd   )!r6   r7   r8   r9   r   r;   dictr   r<   r   r   r!  r   r0  r2  r4  r6  r8  r}   r   r(   r=  r   rK   r@  r   rC  r:   r%  rI  rK  rX   rN  r,   r1   r/   r+  r+    s   " b$x.())CN##	R 	 	 rDy DN  " 	T"d8n*<%= 	 	 b X_    r d8n  *  z    &13	 2 &/8	 2 	 	T 	 	 	 d    	 	 	 	  
 	 	t 	 	r1   r+  c                   J    e Zd ZU dZeed<   eed<   eed<   eed<   edz  ed<   y)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.

    low_watermarkhigh_watermarkconnected_countgrace_periodN	last_trim)r6   r7   r8   r9   ry   r;   r   r,   r1   r/   rS  rS    s+    0 t|r1   rS  c            	          e Zd ZU dZeed<   edefd       Zede	e
ef   fd       Zedede
dedd	fd
       Zedede
dd	fd       Zededefd       Zedede
dd	fd       Zedede
defd       Zeddede
defd       Zedefd       Zy	)INetworkServicez
    Interface for a network service with connection management capabilities.

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

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

        Nr,   r-   s    r/   get_total_connectionsz%INetworkService.get_total_connections  rA   r1   c                      y)z
        Get connection metrics (go-libp2p style).

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

        Nr,   r-   s    r/   get_metricszINetworkService.get_metrics  rA   r1   rL   tagvalueNc                      y)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.   rL   r`  ra  s       r/   tag_peerzINetworkService.tag_peer  rA   r1   c                      y)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.   rL   r`  s      r/   
untag_peerzINetworkService.untag_peer  rA   r1   c                      y)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,   r   s     r/   get_tag_infozINetworkService.get_tag_info,  rA   r1   c                      y)z
        Protect a peer from having its connection(s) pruned.

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

        Nr,   re  s      r/   protectzINetworkService.protect=  rA   r1   c                      y)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,   re  s      r/   	unprotectzINetworkService.unprotectK  rA   r1   c                      y)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,   re  s      r/   is_protectedzINetworkService.is_protected^  rA   r1   c                      y)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-   s    r/   get_conn_mgr_infoz!INetworkService.get_conn_mgr_infoq  rA   r1   ) )r6   r7   r8   r9   r   r;   r   ry   r]  rQ  r   r_  r   rc  rf  rh  rj  r:   rl  rn  rS  rp  r,   r1   r/   rZ  rZ    s\    	s 	 	 	T#s(^ 	 	   S T   " 3 4   B 3    r      # $  $ B S $  $ 6  r1   rZ  c                       e Zd ZdZedddeddfd       Zedddeddfd       Zeddd	eddfd
       Z	eddd	eddfd       Z
edddeddfd       Zedddeddfd       Zy)rP  z
    Interface for a network service.

    Extends the INetwork interface with additional service management
    capabilities.

    networkr+  streamr*   Nc                    K   yw)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.   rs  rt  s      r/   opened_streamzINotifee.opened_stream  rU   rV   c                    K   yw)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,   rv  s      r/   closed_streamzINotifee.closed_stream  rU   rV   rN   c                    K   yw)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.   rs  rN   s      r/   	connectedzINotifee.connected  rU   rV   c                    K   yw)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{  s      r/   disconnectedzINotifee.disconnected  rU   rV   	multiaddrc                    K   yw)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.   rs  r  s      r/   r%  zINotifee.listen  rU   rV   c                    K   yw)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  s      r/   listen_closezINotifee.listen_close  rU   rV   )r6   r7   r8   r9   r   r}   rw  ry  r   r|  r~  r   r%  r  r,   r1   r/   rP  rP    s     : z d   : z d   z  d   * H    J 9    *  t  r1   rP  c            	          e Zd ZdZedefd       Zedefd       Zede	fd       Z
edefd       Zed&d       Zedee   fd       Zedee   fd	       Zedefd
       Zeed'd              Zedee   fd       Zedee   fd       Zeej2                  ddee   deded   fd       Zedededdfd       Z ededdfd       Z!edejD                  e   dz  fd       Z#ed(d       Z$ed)de%dz  ddfd       Z&ededee   de'fd       Z(ede)ddfd       Z*ededdfd        Z+ed*d!       Z,ed"e-dede.fd#       Z/ed"e-d$ede0fd%       Z1y)+IHostz
    Interface for the host.

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

    r*   c                      y)z
        Retrieve the host's peer identifier.

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

        Nr,   r-   s    r/   get_idzIHost.get_id  rA   r1   c                      y)z
        Retrieve the public key of the host.

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

        Nr,   r-   s    r/   get_public_keyzIHost.get_public_key  rA   r1   c                      y)z
        Retrieve the private key of the host.

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

        Nr,   r-   s    r/   get_private_keyzIHost.get_private_key  rA   r1   c                      y)z
        Retrieve the network service instance associated with the host.

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

        Nr,   r-   s    r/   get_networkzIHost.get_network  rA   r1   c                      y)z
        Retrieve the muxer instance for the host.

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

        Nr,   r-   s    r/   get_muxzIHost.get_mux  rA   r1   c                      y)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-   s    r/   r'  zIHost.get_addrs+  rA   r1   c                      y)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-   s    r/   get_transport_addrszIHost.get_transport_addrs;  rA   r1   c                      y)z4
        :return: the peerstore of the host
        Nr,   r-   s    r/   get_peerstorezIHost.get_peerstoreH  rA   r1   c                      y)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-   s    r/   conn_managerzIHost.conn_managerN  rA   r1   c                      y)z
        Retrieve the identifiers of peers currently connected to the host.

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

        Nr,   r-   s    r/   get_connected_peerszIHost.get_connected_peers_  rA   r1   c                      y)zH
        :return: List of peer IDs that have active connections
        Nr,   r-   s    r/   get_live_peerszIHost.get_live_peersk  rA   r1   )task_statuslisten_addrsr  Nc                     y)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  s      r/   runz	IHost.runq  rA   r1   r   rA  c                      y)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.   r   rA  s      r/   rC  zIHost.set_stream_handler  rA   r1   c                      y)z
        Remove the stream handler for the specified protocol.

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

        Nr,   r   s     r/   remove_stream_handlerzIHost.remove_stream_handler  rA   r1   c                      y)zP
        Returns the recving end of the channel, used for metric events
        Nr,   r-   s    r/   get_metrics_recv_channelzIHost.get_metrics_recv_channel  rA   r1   c                      y)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-   s    r/   get_event_buszIHost.get_event_bus  rA   r1   	public_ipc                    K   yw)zS
        Initiate the ACME-AUTO-TLS-BROKER negotiation for TLS certificate
        Nr,   )r.   r  s     r/   initiate_autotls_procedurez IHost.initiate_autotls_procedure  rU   rV   rL   protocol_idsc                    K   yw)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.   rL   r  s      r/   r   zIHost.new_stream  rU   rV   r  c                    K   yw)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  s     r/   connectzIHost.connect  rU   rV   c                    K   yw)z
        Disconnect from the specified peer.

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

        Nr,   r   s     r/   
disconnectzIHost.disconnect  rU   rV   c                    K   yw)zN
        Close the host and all underlying connections and services.

        Nr,   r-   s    r/   rX   zIHost.close  rU   rV   r:  c                    K   yw)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<  s      r/   upgrade_outbound_connectionz!IHost.upgrade_outbound_connection  rU   rV   r"  c                    K   yw)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?  s      r/   upgrade_inbound_connectionz IHost.upgrade_inbound_connection	  rU   rV   )r*   r#   )r*   r    )r*   r   rO  rd   )2r6   r7   r8   r9   r   r   r  r   r  r   r  rZ  r  r  r<   r   r'  r  r   r  ri   r  r  r  rg   TASK_STATUS_IGNOREDr	   r   r
   r  r   r   rC  r  MemoryReceiveChannelr  r  r   r  r}   r   r   r  r  rX   r(   r   r  rK   r  r,   r1   r/   r  r    s    	 	 	 		 	 	 	 	 	 	_ 	 	 	 	 4	?   
T)_ 
 
 z  
    	T"X 	 	 R  
 
  33	y) 	
 
%T	* $ $6E	  	 	t 	 	 $*C*CC*H4*O  
   #* PT   )1))<	 ( x D  " 	 	t 	 	   &13	 6 &/8	 r1   r  c                       e Zd ZdZedefd       Zedefd       Zede	j                  fd       Zedefd       Zededefd       Zy	)
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                      y)z
        Return the domain string for this record type.

        Used in envelope validation to distinguish different record types.
        Nr,   r-   s    r/   domainzIPeerRecord.domain;	  rA   r1   c                      y)z
        Return a binary codec prefix that identifies the PeerRecord type.

        This is prepended in signed envelopes to allow type-safe decoding.
        Nr,   r-   s    r/   codeczIPeerRecord.codecC	  rA   r1   c                      y)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-   s    r/   to_protobufzIPeerRecord.to_protobufK	  rA   r1   c                      y)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-   s    r/   marshal_recordzIPeerRecord.marshal_recordT	  rA   r1   otherc                      y)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  s     r/   equalzIPeerRecord.equal_	  rA   r1   N)r6   r7   r8   r9   r   r   r  bytesr  pbr"   r  r  objectr:   r  r,   r1   r/   r  r  1	  s        u   R]]      6 d  r1   r  c                   h    e Zd Zedefd       Zededdfd       Zed	d       Zede	de
fd       Zy)
	IEnveloper*   c                      y)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-   s    r/   marshal_envelopezIEnvelope.marshal_envelopep	  rA   r1   r  Nc                      y)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  s     r/   validatezIEnvelope.validate{	  rA   r1   c                      y)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-   s    r/   recordzIEnvelope.record	  rA   r1   r  c                      y)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  s     r/   r  zIEnvelope.equal	  rA   r1   )r*   r"   )r6   r7   r8   r   r  r  r   r  r  r   r:   r  r,   r1   r/   r  r  o	  ss    %   	s 	t 	 	 
 
 3 4  r1   r  c                      e Zd ZdZedee   fd       Zedee   ddfd       Z	edee   ddfd       Z
edee   ddfd       Zedee   dee   fd	       Zedee   defd
       Zed&d       Zedee   ddfd       Zedee   fd       Zed&d       Zedededdfd       Zededefd       Zed&d       Zededdfd       Zedefd       Zededdfd       Zedefd       Zed&d       Zededdfd       Zedefd       Z ed&d       Z!ed&d        Z"ede#fd!       Z$ede#fd"       Z%ed#e#ddfd$       Z&ede'fd%       Z(y)'	IPeerDataz
    Interface for managing peer data.

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

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

        Nr,   r-   s    r/   r   zIPeerData.get_protocols	  rA   r1   r   Nc                      y)z
        Add one or more protocols to the peer's data.

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

        Nr,   r.   r   s     r/   r   zIPeerData.add_protocols	  rA   r1   c                      y)z
        Set the protocols for the peer.

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

        Nr,   r  s     r/   r   zIPeerData.set_protocols	  rA   r1   c                      y)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  s     r/   r   zIPeerData.remove_protocols	  rA   r1   c                      y)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  s     r/   r   zIPeerData.supports_protocols	  rA   r1   c                      y)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  s     r/   r   z"IPeerData.first_supported_protocol	  rA   r1   c                      y)zE
        Clears all protocol data associated with this peer.
        Nr,   r-   s    r/   r   zIPeerData.clear_protocol_data
  rA   r1   r   c                      y)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   s     r/   r   zIPeerData.add_addrs
  rA   r1   c                      y)z
        Retrieve all multiaddresses associated with the peer.

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

        Nr,   r-   s    r/   r'  zIPeerData.get_addrs
  rA   r1   c                      y)z@
        Clear all addresses associated with the peer.

        Nr,   r-   s    r/   r   zIPeerData.clear_addrs"
  rA   r1   r   r   c                      y)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.   r   r   s      r/   put_metadatazIPeerData.put_metadata)
  rA   r1   c                      y)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.   r   s     r/   get_metadatazIPeerData.get_metadata7
  rA   r1   c                      y)zH
        Clears all metadata entries associated with this peer.
        Nr,   r-   s    r/   r   zIPeerData.clear_metadataM
  rA   r1   r   c                      y)z
        Add a public key to the peer's data.

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

        Nr,   )r.   r   s     r/   r   zIPeerData.add_pubkeyS
  rA   r1   c                      y)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-   s    r/   
get_pubkeyzIPeerData.get_pubkey_
  rA   r1   r   c                      y)z
        Add a private key to the peer's data.

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

        Nr,   )r.   r   s     r/   r   zIPeerData.add_privkeyp
  rA   r1   c                      y)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-   s    r/   get_privkeyzIPeerData.get_privkey|
  rA   r1   c                      y)z~
        Clears all cryptographic key data associated with this peer,
        including both public and private keys.
        Nr,   r-   s    r/   r   zIPeerData.clear_keydata
  rA   r1   new_latencyc                      y)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  s     r/   r   zIPeerData.record_latency
  rA   r1   c                      y)z
        Returns the current EWMA value of the recorded latency.

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

        Nr,   r-   s    r/   r   zIPeerData.latency_EWMA
  rA   r1   c                      y)zS
        Clears all latency-related metrics and resets the internal state.
        Nr,   r-   s    r/   r   zIPeerData.clear_metrics
  rA   r1   c                      y)z4
        Updates timestamp to current time.
        Nr,   r-   s    r/   update_last_identifiedz IPeerData.update_last_identified
  rA   r1   c                      y)z
        Fetch the last identified timestamp

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

        Nr,   r-   s    r/   get_last_identifiedzIPeerData.get_last_identified
  rA   r1   c                      y)z
        Get ttl value for the peer for validity check

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

        Nr,   r-   s    r/   get_ttlzIPeerData.get_ttl
  rA   r1   rn   c                      y)z
        Set ttl value for the peer for validity check

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

        Nr,   rp   s     r/   set_ttlzIPeerData.set_ttl
  rA   r1   c                      y)z
        Check if the peer is expired based on last_identified and ttl

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

        Nr,   r-   s    r/   
is_expiredzIPeerData.is_expired
  rA   r1   rd   ))r6   r7   r8   r9   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  ry   r  r  r  r:   r  r,   r1   r/   r  r  	  s    	tCy 	 	 	x} 	 	 	 	x} 	 	 	 	(3- 	D 	 	 HSM d3i  $ (3- C     
 x	2 t   	4	? 	 	    - D      *  
 	 	t 	 	 I    	: 	$ 	 	 Z      % D   	e 	 	  
  
 	S 	 	 	 	 	 	3 	4 	 	 	D 	 	r1   r  c                   @    e Zd ZdZededdfd       Zedefd       Zy)IMultiselectCommunicatorz
    Communicator helper for multiselect.

    Ensures that both the client and multistream module follow the same
    multistream protocol.
    msg_strr*   Nc                    K   yw)z
        Write a message to the stream.

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

        Nr,   )r.   r  s     r/   writezIMultiselectCommunicator.write
  rU   rV   c                    K   yw)z
        Read a message from the stream until EOF.

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

        Nr,   r-   s    r/   readzIMultiselectCommunicator.read  rU   rV   )r6   r7   r8   r9   r   r   r  r  r,   r1   r/   r  r  
  sD     	3 	4 	 	 	C 	 	r1   r  c                   l    e Zd ZdZededdfd       Zedee   dedefd       Z	edededefd	       Z
y)
IMultiselectClientz
    Client for multiselect negotiation.

    Communicates with the receiver's multiselect module to select a protocol
    for communication.
    communicatorr*   Nc                    K   yw)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   s     r/   	handshakezIMultiselectClient.handshake  rU   rV   r   c                    K   yw)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   s      r/   select_one_ofz IMultiselectClient.select_one_of,  rU   rV   protocolc                    K   yw)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  s      r/   
try_selectzIMultiselectClient.try_selectF  rU   rV   )r6   r7   r8   r9   r   r  r  r	   r   r  r  r,   r1   r/   r  r    s     ,D   " !),<T	 2 4@I	 r1   r  c                       e Zd ZU dZeedz  edz  f   ed<   edededdfd       Z	ededdfd       Z
edeedz  d	f   fd
       Zededeedz  edz  f   fd       Zy)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                      y)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  r  s      r/   add_handlerzIMultiselectMuxer.add_handlern  rA   r1   c                      y)z
        Remove the handler for the specified protocol.

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

        Nr,   )r.   r  s     r/   remove_handlerz IMultiselectMuxer.remove_handler|  rA   r1   .c                      y)z
        Retrieve the protocols for which handlers have been registered.

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

        Nr,   r-   s    r/   r   zIMultiselectMuxer.get_protocols  rA   r1   r   c                    K   yw)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  s     r/   	negotiatezIMultiselectMuxer.negotiate  rU   rV   )r6   r7   r8   r9   rQ  r   r   r;   r   r  r  r   r   r  r  r,   r1   r/   r
  r
  d  s     9t#_t%;;<<I  D   	y 	T 	 	 	uY%5s%:; 	 	 4	y44!77	8 r1   r
  c                   T    e Zd ZdZed	dededdfd       Zededede	e
   fd       Zy)
IContentRoutingzm
    Interface for content routing.

    Provides methods to advertise and search for content providers.
    cidannouncer*   Nc                      y)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.   r  r  s      r/   providezIContentRouting.provide  rA   r1   countc                      y)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.   r  r  s      r/   find_provider_iterz"IContentRouting.find_provider_iter  rA   r1   )T)r6   r7   r8   r9   r   r  r:   r  ry   r   r   r  r,   r1   r/   r  r    s^     5 D D    e C HX<N  r1   r  c                   0    e Zd ZdZedededz  fd       Zy)IPeerRoutingzZ
    Interface for peer routing.

    Provides methods to search for a specific peer.
    rL   r*   Nc                    K   yw)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,   r   s     r/   	find_peerzIPeerRouting.find_peer  rU   rV   )r6   r7   r8   r9   r   r   r   r   r,   r1   r/   r  r    s-     r ho  r1   r  c                   H    e Zd ZdZededefd       Zedededefd       Z	y)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

    rN   r*   c                    K   yw)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.   rN   s     r/   secure_inboundzISecureTransport.secure_inbound  rU   rV   rL   c                    K   yw)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,   rP   s      r/   secure_outboundz ISecureTransport.secure_outbound  rU   rV   N)
r6   r7   r8   r9   r   r(   rI   r$  r   r&  r,   r1   r/   r"  r"    sR    
  K  & . 2 +  r1   r"  c                       e Zd ZU dZdZeed<   edede	fd       Z
ededefd       Zededefd	       Zededefd
       Zedee   fd       Zy)
ITransportzt
    Interface for a transport.

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

    Fprovides_native_muxingr"  r*   c                    K   yw)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$  s     r/   dialzITransport.dial@  rU   rV   handler_functionc                      y)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.   r,  s     r/   create_listenerzITransport.create_listenerQ  rA   r1   c                      y)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$  s     r/   can_dialzITransport.can_diald  rA   r1   c                      y)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$  s     r/   
can_listenzITransport.can_listen~  rA   r1   c                      y)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-   s    r/   r   zITransport.protocols  rA   r1   N)r6   r7   r8   r9   r)  r:   r;   r   r   r(   r+  r   r!  r.  r0  r2  r<   r   r   r,   r1   r/   r(  r(  3  s     $)D(	 n     Y  $ i D  2 	 d  ( 49  r1   r(  c                   L    e Zd ZdZedd       Zedej                  fd       Zy)ISubscriptionAPIz}
    Interface for a subscription in pubsub.

    Combines asynchronous context management and iteration over messages.

    r*   Nc                    K   yw)z6
        Unsubscribe from the current topic.

        Nr,   r-   s    r/   unsubscribezISubscriptionAPI.unsubscribe  r)  rV   c                    K   yw)z
        Retrieve the next message from the subscription.

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

        Nr,   r-   s    r/   r   zISubscriptionAPI.get        	rV   rd   )	r6   r7   r8   r9   r   r7  r%   Messager   r,   r1   r/   r5  r5    s:       
7?? 
 
r1   r5  c                      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       Zedd	       Zed
ede	dz  ddfd       Zed
eddfd       Zedej$                  deddfd       Zededej(                  ddfd       Zededdfd       Zededdfd       Zd
eddfdZd
ededdfdZy)IPubsubRouterz
    Interface for a pubsub router.

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

    meshfanoutpeer_protocoldegreer*   c                      y)z
        Retrieve the list of protocols supported by the router.

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

        Nr,   r-   s    r/   r   zIPubsubRouter.get_protocols  rA   r1   Nc                      y)z
        Attach the router to a newly initialized PubSub instance.

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

        Nr,   )r.   pubsubs     r/   attachzIPubsubRouter.attach  rA   r1   rL   r   c                      y)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.   rL   r   s      r/   add_peerzIPubsubRouter.add_peer  rA   r1   c                      y)z
        Notify the router that a peer has disconnected.

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

        Nr,   r   s     r/   remove_peerzIPubsubRouter.remove_peer  rA   r1   rpcsender_peer_idc                    K   yw)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.   rI  rJ  s      r/   
handle_rpczIPubsubRouter.handle_rpc  rU   rV   msg_forwarder
pubsub_msgc                    K   yw)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.   rM  rN  s      r/   publishzIPubsubRouter.publish  rU   rV   topicc                    K   yw)z
        Join a topic to receive and forward messages.

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

        Nr,   r.   rQ  s     r/   joinzIPubsubRouter.join$  rU   rV   c                    K   yw)z
        Leave a topic, stopping message forwarding for that topic.

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

        Nr,   rS  s     r/   leavezIPubsubRouter.leave0  rU   rV   c                    K   yw)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,   r   s     r/   flush_pending_messagesz$IPubsubRouter.flush_pending_messages<  rU   rV   c                    K   yw)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.   rL   rQ  s      r/   send_recent_messagesz"IPubsubRouter.send_recent_messagesK  rU   rV   )rC  r$   r*   N)r6   r7   r8   r9   rQ  r   setr   r;   r   ry   r   r<   r   rD  rF  rH  r%   RPCrL  r:  rP  rT  rV  rX  rZ  r,   r1   r/   r<  r<    s    sCG|
c"gI&&K	tI 	 	 	 	  T1A d   	2 	$ 	 	 GKK     2 7?? t   	 	 	 	 	 	 	 	B 4 " S T r1   r<  c            
       r   e Zd ZdZeedefd              Zeedee	df   fd              Z
eedee   fd              Zededed	edd
fd       Zededd
fd       Zedd       Zededefd       Zededd
fd       Zedeee   z  dedd
fd       Zeddededd
fd       Ze	 ddedededd
fd       Zy
)IPubsubz
    Interface for the pubsub system.

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

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

        Nr,   r-   s    r/   my_idzIPubsub.my_idd       	r1   .c                      y)z
        Retrieve the protocols used by the pubsub system.

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

        Nr,   r-   s    r/   r   zIPubsub.protocolsr  ra  r1   c                      y)z
        Retrieve the set of topic identifiers.

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

        Nr,   r-   s    r/   	topic_idszIPubsub.topic_ids  ra  r1   rQ  	validatoris_async_validatorNc                      y)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.   rQ  re  rf  s       r/   set_topic_validatorzIPubsub.set_topic_validator  s    " 	r1   c                      y)z
        Remove the validator for a specific topic.

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

        Nr,   rS  s     r/   remove_topic_validatorzIPubsub.remove_topic_validator  s     	r1   c                    K   yw)zO
        Wait until the pubsub system is fully initialized and ready.

        Nr,   r-   s    r/   wait_until_readyzIPubsub.wait_until_ready  r)  rV   topic_idc                    K   yw)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.   rm  s     r/   	subscribezIPubsub.subscribe  s       	rV   c                    K   yw)z
        Unsubscribe from a topic.

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

        Nr,   ro  s     r/   r7  zIPubsub.unsubscribe  r9  rV   datac                    K   yw)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.   rm  rr  s      r/   rP  zIPubsub.publish  s      	rV   rL   timeoutc                    K   yw)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.   rL   rt  s      r/   wait_for_peerzIPubsub.wait_for_peer  s     > 	rV   c                    K   yw)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.   rL   rm  rt  s       r/   wait_for_subscriptionzIPubsub.wait_for_subscription  s     H 	rV   rd   )g      @)r6   r7   r8   r9   ri   r   r   r`  r   r   r   r   r   rd  r   r:   rh  rj  rl  r5  rp  r7  r<   r  rP  r   rv  rx  r,   r1   r/   r^  r^  \  s    
r 
  
 
5C0 
  
 
8C= 
  
 %0FJ	 $ 
C 
D 
 
    0@  " 
# 
$ 
 
 cDIo U t   2    @ ;>##%(#38#	# #r1   r^  c            
       r    e Zd ZdZedd       Zedd       Zedefd       Zede	de
d	e
dee   fd
       Zy)IPerfzv
    Interface for the perf protocol service.

    Spec: https://github.com/libp2p/specs/blob/master/perf/perf.md
    r*   Nc                    K   yw)z9Start the perf service and register the protocol handler.Nr,   r-   s    r/   rT   zIPerf.start6        	rV   c                    K   yw)z:Stop the perf service and unregister the protocol handler.Nr,   r-   s    r/   stopz
IPerf.stop;  r|  rV   c                      y)z*Check if the service is currently running.Nr,   r-   s    r/   
is_startedzIPerf.is_started@  s     	r1   r  
send_bytes
recv_bytesc                      y)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  r  r  s       r/   measure_performancezIPerf.measure_performanceE  s    2 	r1   rd   )r6   r7   r8   r9   r   rT   r~  r:   r  r   ry   r   r   r  r,   r1   r/   rz  rz  /  s         D     	
 
s	 r1   rz  )aabcr   r   collections.abcr   r   r   r   r	   
contextlibr
   dataclassesr   typesr   typingr   r   r   r   r  r   rg   libp2p.connection_typesr   libp2p.crypto.keysr   r   r   libp2p.custom_typesr   r   r   r   r   libp2p.events.busr   libp2p.io.abcr   r   libp2p.peer.idr   libp2p.peer.pb.peer_record_pb2peerr  peer_record_pb2libp2p.peer.peerinfor   libp2p.network.tag_storer    libp2p.peer.enveloper!   libp2p.peer.peer_recordr"   !libp2p.protocol_muxer.multiselectr#   libp2p.pubsub.pubsubr$   libp2p.pubsub.pbr%   libp2p.tools.anyio_service.apir&   r(   r>   rI   rK   rf   r}   r   r   r   r   r   r   r   r   r!  r+  rS  rZ  rP  r  r  r  r  r  r  r
  r  r  r"  r(  r:  r5  r<  r^  rz  r,   r1   r/   <module>r     s    3 !   
  ' , + 1-2= 6
_ J
' 'T$n h hV-?$7$G -f& &X;v ;B'C 'ZT Tp= =FWs Wz.s .ho ojXL90(HjXL|1 1nqs qh   @Rh
 Rp[s [BGC GV
:# :|1 1nB BP
s HL LdF FX)c )X3 85s 5vo oj*+]7??-K@QC QhMj Mf/C /r1   