libp2p.transport package
Subpackages
- libp2p.transport.quic package
- Connection ID Management
- Submodules
- libp2p.transport.quic.config module
QUICStreamFlowControlConfigQUICTransportConfigQUICTransportConfig.CONNECTION_CLOSE_TIMEOUTQUICTransportConfig.CONNECTION_FLOW_CONTROL_WINDOWQUICTransportConfig.CONNECTION_HANDSHAKE_TIMEOUTQUICTransportConfig.ENABLE_STREAM_BATCHINGQUICTransportConfig.ENABLE_STREAM_KEEP_ALIVEQUICTransportConfig.ENABLE_STREAM_METRICSQUICTransportConfig.ENABLE_STREAM_RESET_ON_ERRORQUICTransportConfig.ENABLE_STREAM_RESOURCE_TRACKINGQUICTransportConfig.ENABLE_STREAM_TIMELINE_TRACKINGQUICTransportConfig.MAX_CONCURRENT_STREAMSQUICTransportConfig.MAX_INCOMING_STREAMSQUICTransportConfig.MAX_OUTGOING_STREAMSQUICTransportConfig.MAX_STREAM_RECEIVE_BUFFERQUICTransportConfig.NEGOTIATE_TIMEOUTQUICTransportConfig.NEGOTIATION_SEMAPHORE_LIMITQUICTransportConfig.PROTOCOL_QUIC_DRAFT29QUICTransportConfig.PROTOCOL_QUIC_V1QUICTransportConfig.STREAM_ACCEPT_TIMEOUTQUICTransportConfig.STREAM_BATCH_SIZEQUICTransportConfig.STREAM_CLOSE_TIMEOUTQUICTransportConfig.STREAM_ERROR_RETRY_ATTEMPTSQUICTransportConfig.STREAM_ERROR_RETRY_BACKOFF_FACTORQUICTransportConfig.STREAM_ERROR_RETRY_DELAYQUICTransportConfig.STREAM_FLOW_CONTROL_WINDOWQUICTransportConfig.STREAM_KEEP_ALIVE_INTERVALQUICTransportConfig.STREAM_MEMORY_LIMIT_PER_CONNECTIONQUICTransportConfig.STREAM_MEMORY_LIMIT_PER_STREAMQUICTransportConfig.STREAM_METRICS_COLLECTION_INTERVALQUICTransportConfig.STREAM_OPEN_TIMEOUTQUICTransportConfig.STREAM_PROCESSING_CONCURRENCYQUICTransportConfig.STREAM_READ_TIMEOUTQUICTransportConfig.STREAM_RECEIVE_BUFFER_HIGH_WATERMARKQUICTransportConfig.STREAM_RECEIVE_BUFFER_LOW_WATERMARKQUICTransportConfig.STREAM_RESET_ERROR_CODEQUICTransportConfig.STREAM_WRITE_TIMEOUTQUICTransportConfig.alpn_protocolsQUICTransportConfig.connection_timeoutQUICTransportConfig.connection_windowQUICTransportConfig.enable_draft29QUICTransportConfig.enable_qlogQUICTransportConfig.enable_v1QUICTransportConfig.get_stream_config_dict()QUICTransportConfig.idle_timeoutQUICTransportConfig.local_portQUICTransportConfig.max_concurrent_streamsQUICTransportConfig.max_connectionsQUICTransportConfig.max_datagram_sizeQUICTransportConfig.qlog_dirQUICTransportConfig.stream_windowQUICTransportConfig.verify_mode
QUICTransportKwargsQUICTransportKwargs.PROTOCOL_QUIC_DRAFT29QUICTransportKwargs.PROTOCOL_QUIC_V1QUICTransportKwargs.alpn_protocolsQUICTransportKwargs.connection_timeoutQUICTransportKwargs.connection_windowQUICTransportKwargs.enable_draft29QUICTransportKwargs.enable_qlogQUICTransportKwargs.enable_v1QUICTransportKwargs.idle_timeoutQUICTransportKwargs.local_portQUICTransportKwargs.max_concurrent_streamsQUICTransportKwargs.max_connectionsQUICTransportKwargs.max_datagram_sizeQUICTransportKwargs.qlog_dirQUICTransportKwargs.stream_windowQUICTransportKwargs.verify_mode
create_stream_config_for_use_case()
- libp2p.transport.quic.connection module
QUICConnectionQUICConnection.accept_stream()QUICConnection.close()QUICConnection.connect()QUICConnection.get_active_streams()QUICConnection.get_connection_id_stats()QUICConnection.get_connection_type()QUICConnection.get_current_connection_id()QUICConnection.get_peer_certificate()QUICConnection.get_remote_address()QUICConnection.get_security_info()QUICConnection.get_security_manager()QUICConnection.get_stream_stats()QUICConnection.get_streams_by_protocol()QUICConnection.get_transport_addresses()QUICConnection.is_closedQUICConnection.is_establishedQUICConnection.is_initiatorQUICConnection.is_peer_verifiedQUICConnection.is_startedQUICConnection.local_peer_id()QUICConnection.multiaddr()QUICConnection.open_stream()QUICConnection.read()QUICConnection.remote_peer_id()QUICConnection.set_listener_context()QUICConnection.set_resource_scope()QUICConnection.set_stream_handler()QUICConnection.start()QUICConnection.write()
- libp2p.transport.quic.exceptions module
QUICAddressErrorQUICAddressResolutionErrorQUICCertificateErrorQUICConfigurationErrorQUICConnectionClosedErrorQUICConnectionErrorQUICConnectionLimitErrorQUICConnectionTimeoutErrorQUICDialErrorQUICErrorQUICErrorContextQUICFlowControlDeadlockErrorQUICFlowControlErrorQUICFlowControlViolationErrorQUICHandshakeErrorQUICInvalidConfigErrorQUICInvalidMultiaddrErrorQUICListenErrorQUICMemoryLimitErrorQUICPeerVerificationErrorQUICProtocolErrorQUICResourceErrorQUICSecurityErrorQUICStreamBackpressureErrorQUICStreamClosedErrorQUICStreamErrorQUICStreamLimitErrorQUICStreamResetErrorQUICStreamStateErrorQUICStreamTimeoutErrorQUICTransportErrorQUICUnsupportedVersionErrorQUICVersionNegotiationErrorcreate_connection_error()create_stream_error()map_quic_error_code()
- libp2p.transport.quic.listener module
- libp2p.transport.quic.security module
CertificateGeneratorLibP2PExtensionHandlerLibP2PKeyConverterPeerAuthenticatorQUICTLSConfigManagerQUICTLSSecurityConfigQUICTLSSecurityConfig.alpn_protocolsQUICTLSSecurityConfig.certificateQUICTLSSecurityConfig.certificate_chainQUICTLSSecurityConfig.check_hostnameQUICTLSSecurityConfig.config_nameQUICTLSSecurityConfig.debug_config()QUICTLSSecurityConfig.get_certificate_info()QUICTLSSecurityConfig.has_libp2p_extension()QUICTLSSecurityConfig.is_certificate_valid()QUICTLSSecurityConfig.is_client_configQUICTLSSecurityConfig.peer_idQUICTLSSecurityConfig.private_keyQUICTLSSecurityConfig.request_client_certificateQUICTLSSecurityConfig.validate_certificate_key_match()QUICTLSSecurityConfig.verify_mode
TLSConfigcreate_client_tls_config()create_quic_security_transport()create_server_tls_config()
- libp2p.transport.quic.stream module
QUICStreamQUICStream.can_read()QUICStream.can_write()QUICStream.close()QUICStream.close_read()QUICStream.close_write()QUICStream.directionQUICStream.get_remote_address()QUICStream.handle_data_received()QUICStream.handle_flow_control_update()QUICStream.handle_reset()QUICStream.handle_stop_sending()QUICStream.is_closed()QUICStream.is_initiatorQUICStream.is_reset()QUICStream.muxed_connQUICStream.protocolQUICStream.read()QUICStream.reset()QUICStream.set_deadline()QUICStream.stateQUICStream.stream_idQUICStream.wait_ready_for_io()QUICStream.write()
StreamDirectionStreamStateStreamTimeline
- libp2p.transport.quic.transport module
QUICTransportQUICTransport.can_dial()QUICTransport.can_listen()QUICTransport.close()QUICTransport.create_listener()QUICTransport.dial()QUICTransport.get_listener_socket()QUICTransport.get_security_manager()QUICTransport.get_stats()QUICTransport.listen_order()QUICTransport.protocols()QUICTransport.provides_native_muxingQUICTransport.set_background_nursery()QUICTransport.set_swarm()
- libp2p.transport.quic.utils module
- Module contents
- libp2p.transport.websocket package
- Submodules
- libp2p.transport.websocket.connection module
P2PWebSocketConnectionWebSocketConnectionErrorWebSocketHandshakeErrorWebSocketMessageErrorWebSocketProtocolErrorWebSocketStatsWebSocketStats.bytes_receivedWebSocketStats.bytes_sentWebSocketStats.connected_atWebSocketStats.created_atWebSocketStats.errorsWebSocketStats.is_secureWebSocketStats.last_activityWebSocketStats.last_errorWebSocketStats.messages_receivedWebSocketStats.messages_sentWebSocketStats.ping_rtt_msWebSocketStats.protocolWebSocketStats.record_error()WebSocketStats.record_message_received()WebSocketStats.record_message_sent()WebSocketStats.update_activity()
- libp2p.transport.websocket.listener module
WebsocketListenerWebsocketListenerConfigWebsocketListenerConfig.advanced_tls_configWebsocketListenerConfig.autotls_configWebsocketListenerConfig.close_timeoutWebsocketListenerConfig.handshake_timeoutWebsocketListenerConfig.max_connectionsWebsocketListenerConfig.max_message_sizeWebsocketListenerConfig.ping_intervalWebsocketListenerConfig.ping_timeoutWebsocketListenerConfig.tls_config
- libp2p.transport.websocket.manager module
WebSocketConnectionManagerWebSocketConnectionManager.add_connection()WebSocketConnectionManager.close_all()WebSocketConnectionManager.get_active_connections()WebSocketConnectionManager.get_connection()WebSocketConnectionManager.get_connection_stats()WebSocketConnectionManager.get_manager_stats()WebSocketConnectionManager.remove_connection()
- libp2p.transport.websocket.multiaddr_utils module
- libp2p.transport.websocket.proxy module
- libp2p.transport.websocket.proxy_env module
- libp2p.transport.websocket.transport module
WebsocketConfigWebsocketConfig.autotls_configWebsocketConfig.close_timeoutWebsocketConfig.dns_max_retriesWebsocketConfig.dns_resolution_timeoutWebsocketConfig.handshake_timeoutWebsocketConfig.max_buffered_amountWebsocketConfig.max_connectionsWebsocketConfig.max_message_sizeWebsocketConfig.ping_intervalWebsocketConfig.ping_timeoutWebsocketConfig.proxy_authWebsocketConfig.proxy_urlWebsocketConfig.tls_client_configWebsocketConfig.tls_configWebsocketConfig.tls_server_configWebsocketConfig.validate()
WebsocketTransportWebsocketTransport.can_dial()WebsocketTransport.can_listen()WebsocketTransport.create_listener()WebsocketTransport.dial()WebsocketTransport.get_connections()WebsocketTransport.get_listeners()WebsocketTransport.get_stats()WebsocketTransport.protocols()WebsocketTransport.resolve()WebsocketTransport.set_background_nursery()WebsocketTransport.set_peer_id()
WithAdvancedTLS()WithAutoTLS()WithHandshakeTimeout()WithMaxConnections()WithProxy()WithProxyFromEnvironment()WithTLSClientConfig()WithTLSServerConfig()combine_configs()
- Module contents
AutoTLSConfigP2PWebSocketConnectionWebSocketTransportWebsocketConfigWebsocketConfig.autotls_configWebsocketConfig.close_timeoutWebsocketConfig.dns_max_retriesWebsocketConfig.dns_resolution_timeoutWebsocketConfig.handshake_timeoutWebsocketConfig.max_buffered_amountWebsocketConfig.max_connectionsWebsocketConfig.max_message_sizeWebsocketConfig.ping_intervalWebsocketConfig.ping_timeoutWebsocketConfig.proxy_authWebsocketConfig.proxy_urlWebsocketConfig.tls_client_configWebsocketConfig.tls_configWebsocketConfig.tls_server_configWebsocketConfig.validate()
WebsocketListenerWebsocketListenerConfigWebsocketListenerConfig.advanced_tls_configWebsocketListenerConfig.autotls_configWebsocketListenerConfig.close_timeoutWebsocketListenerConfig.handshake_timeoutWebsocketListenerConfig.max_connectionsWebsocketListenerConfig.max_message_sizeWebsocketListenerConfig.ping_intervalWebsocketListenerConfig.ping_timeoutWebsocketListenerConfig.tls_config
WebsocketTransportWebsocketTransport.can_dial()WebsocketTransport.can_listen()WebsocketTransport.create_listener()WebsocketTransport.dial()WebsocketTransport.get_connections()WebsocketTransport.get_listeners()WebsocketTransport.get_stats()WebsocketTransport.protocols()WebsocketTransport.resolve()WebsocketTransport.set_background_nursery()WebsocketTransport.set_peer_id()
WithAdvancedTLS()WithAutoTLS()WithHandshakeTimeout()WithMaxConnections()WithProxy()WithProxyFromEnvironment()WithTLSClientConfig()WithTLSServerConfig()combine_configs()
- libp2p.transport.webrtc package
- Subpackages
- Submodules
- libp2p.transport.webrtc.certificate module
- libp2p.transport.webrtc.config module
WebRTCTransportConfigWebRTCTransportConfig.accept_queue_sizeWebRTCTransportConfig.certificateWebRTCTransportConfig.get_or_generate_certificate()WebRTCTransportConfig.handshake_timeoutWebRTCTransportConfig.ice_disconnection_timeoutWebRTCTransportConfig.ice_failure_timeoutWebRTCTransportConfig.ice_keepalive_intervalWebRTCTransportConfig.ice_serversWebRTCTransportConfig.max_concurrent_streamsWebRTCTransportConfig.max_in_flight_connectionsWebRTCTransportConfig.max_message_sizeWebRTCTransportConfig.stream_accept_timeoutWebRTCTransportConfig.stream_open_timeout
- libp2p.transport.webrtc.connection module
WebRTCConnectionWebRTCConnection.accept_stream()WebRTCConnection.close()WebRTCConnection.get_connection_type()WebRTCConnection.get_remote_address()WebRTCConnection.get_transport_addresses()WebRTCConnection.is_closedWebRTCConnection.is_establishedWebRTCConnection.is_initiatorWebRTCConnection.on_channel_closed()WebRTCConnection.on_channel_message()WebRTCConnection.on_datachannel()WebRTCConnection.open_stream()WebRTCConnection.read()WebRTCConnection.remove_stream()WebRTCConnection.start()WebRTCConnection.write()
- libp2p.transport.webrtc.constants module
- libp2p.transport.webrtc.exceptions module
- libp2p.transport.webrtc.listener module
- libp2p.transport.webrtc.multiaddr_utils module
- libp2p.transport.webrtc.noise_handshake module
- libp2p.transport.webrtc.private_listener module
- libp2p.transport.webrtc.private_transport module
- libp2p.transport.webrtc.sdp module
- libp2p.transport.webrtc.signaling module
- libp2p.transport.webrtc.stream module
- libp2p.transport.webrtc.transport module
- Module contents
Submodules
libp2p.transport.exceptions module
- exception libp2p.transport.exceptions.MuxerUpgradeFailure
Bases:
UpgradeFailure
- exception libp2p.transport.exceptions.OpenConnectionError
Bases:
BaseLibp2pError
- exception libp2p.transport.exceptions.SecurityUpgradeFailure
Bases:
UpgradeFailure
- exception libp2p.transport.exceptions.UpgradeFailure
Bases:
BaseLibp2pError
libp2p.transport.upgrader module
- class libp2p.transport.upgrader.TransportUpgrader(secure_transports_by_protocol: Mapping[TProtocol, object], muxer_transports_by_protocol: Mapping[TProtocol, type[object]], negotiate_timeout: int = 30)
Bases:
object- muxer_multistream: MuxerMultistream
- security_multistream: SecurityMultistream
- async upgrade_connection(conn: ISecureConn, peer_id: ID) IMuxedConn
Upgrade secured connection to a muxed connection.
- async upgrade_security(raw_conn: IRawConnection, is_initiator: bool, peer_id: ID | None = None) ISecureConn
Upgrade conn to a secured connection.
Module contents
- class libp2p.transport.DemultiplexedConnType(value)
Bases:
IntEnumMirrors
tcpreuse.DemultiplexedConnTypefrom go-libp2p.Used to route an incoming TCP connection to the correct transport listener after peeking at the first 3 bytes of the stream.
- HTTP = 2
WebSocket (plain) connections start with an HTTP upgrade request. Matches GET / HEAD / POST / PUT / DELETE / CONNECT / OPTIONS / TRACE / PATCH and also PRI (HTTP/2 cleartext preface).
- MULTISTREAM_SELECT = 1
Raw libp2p TCP connections start with the multistream-select header
\\x13/multistream/1.0.0\\n. The first 3 bytes are\\x13/m.
- TLS = 3
WebSocket-Secure (WSS) connections are wrapped in TLS. Matches TLS 1.0–1.3
ClientHellorecord headers.
- UNKNOWN = 0
- class libp2p.transport.DemultiplexedListener(conn_type: DemultiplexedConnType, recv_channel: MemoryReceiveChannel[PeekableStream], listen_maddr: Multiaddr, close_callback: Callable[[DemultiplexedConnType], None], conn_handler: Callable[[Stream], Awaitable[None]] | None = None)
Bases:
IListenerA listener that receives pre-classified connections from
PortDemultiplexer.Each instance holds one end of a
trio.open_memory_channel()and exposes anaccept()async iterator consumed by the transport that registered for this connection type.When a conn_handler is provided,
listen()spawns a background Trio task that drains the channel and calls the handler for every incoming connection. This is the Trio equivalent of the goroutine that reads from a bufferedchan *connWithScopein go-libp2p’sdemultiplexedListener.Mirrors
tcpreuse.demultiplexedListenerfrom go-libp2p.- async connections() AsyncIterator[PeekableStream]
Async-iterate over pre-classified connections.
- get_addrs() tuple[Multiaddr, ...]
Retrieve the list of addresses on which the listener is active.
Returns
- tuple[Multiaddr, …]
A tuple of multiaddresses.
- async listen(maddr: Multiaddr) None
Start the connection-drain loop (no-op when no handler is registered).
When a conn_handler was supplied, this spawns a Trio system task that continuously reads
PeekableStreamobjects from the channel and calls the handler for each one. The actual TCP socket is created byPortDemultiplexer— this method only starts the consumer side.
- class libp2p.transport.PortDemultiplexer(host: str, port: int)
Bases:
IListenerEnables sharing a single TCP port between multiple transports.
Each transport calls
demultiplexed_listen()with its expectedDemultiplexedConnType. Internally, one OS-level TCP socket is opened and a background task classifies every new connection by peeking at its first 3 bytes, then routes it into the matchingDemultiplexedListener’s channel.Mirrors
tcpreuse.PortDemultiplexerfrom go-libp2p (p2p/transport/tcpreuse).Usage:
port_demux = PortDemultiplexer("0.0.0.0", 4001) # TCP transport registers for raw libp2p connections tcp_listener = port_demux.demultiplexed_listen( maddr, DemultiplexedConnType.MULTISTREAM_SELECT ) # WebSocket transport registers for HTTP-upgrade connections ws_listener = port_demux.demultiplexed_listen( maddr, DemultiplexedConnType.HTTP ) await port_demux.listen(maddr) # binds the socket and starts routing
- demultiplexed_listen(maddr: Multiaddr, conn_type: DemultiplexedConnType, conn_handler: Callable[[Stream], Awaitable[None]] | None = None) DemultiplexedListener
Register a listener for conn_type connections on this shared port.
Must be called before
listen(). RaisesValueErrorif a listener for the same conn_type is already registered (mirrorstcpreuse.ErrListenerExists).- Parameters:
maddr – The multiaddress that will be bound (used for
DemultiplexedListener.get_addrs()).conn_type – The connection type this listener should receive.
conn_handler – Optional async callable called per connection. When provided,
DemultiplexedListener.listen()starts a background drain task that calls this handler for each classified connection.
- Returns:
A
DemultiplexedListenerwhoseconnections()yields classified connections.- Raises:
ValueError – If conn_type already has a registered listener.
- get_listener(conn_type: DemultiplexedConnType) DemultiplexedListener | None
Return the listener registered for this conn_type, or None.
- has_listener(conn_type: DemultiplexedConnType) bool
Return True if a listener is registered for this conn_type.
- class libp2p.transport.TCP(*, dns_resolution_timeout: float = 5.0, dns_max_retries: int = 3)
Bases:
ITransport- can_dial(maddr: Multiaddr) bool
Return True if this TCP transport can dial the given multiaddr.
Accepts pure TCP addresses (/ip4/…/tcp/… or /ip6/…/tcp/…) but rejects WebSocket addresses (/ws, /wss) even though they use TCP underneath, so the TransportManager routes those to WebsocketTransport instead.
- Parameters:
maddr – The multiaddress to check.
- Returns:
True if this transport handles the multiaddr.
- can_listen(maddr: Multiaddr) bool
Return True if this TCP transport can listen on the given multiaddr.
- Parameters:
maddr – The multiaddress to check.
- Returns:
True if this transport can listen on the multiaddr.
- create_listener(handler_function: Callable[[ReadWriteCloser], Awaitable[None]]) TCPListener
Create listener on transport.
- Parameters:
handler_function – a function called when a new connection is received that takes a connection as argument which implements interface-connection
- Returns:
a listener object that implements listener_interface.py
- async dial(maddr: Multiaddr) IRawConnection
Dial a transport to peer listening on multiaddr.
Resolves DNS (dns, dns4, dns6, dnsaddr) before dialing (Phase 3.1).
- Parameters:
maddr – multiaddr of peer
- Returns:
RawConnection if successful
- Raises:
OpenConnectionError – raised when failed to open connection
- class libp2p.transport.TransportManager(port_demux: PortDemultiplexer | None = None, port_demuxers: dict[tuple[str, int], PortDemultiplexer] | None = None)
Bases:
objectMaintains an ordered list of
ITransportinstances and provides routing helpers used by theSwarm.Transports are checked in the order they were added. For dialing, the first transport whose
can_dial()returnsTrueis selected. For listening, the same logic applies viacan_listen().This is the Python equivalent of go-libp2p’s
Swarm.TransportForDialing/Swarm.TransportForListeningpair.- Parameters:
port_demux – Optional
PortDemultiplexerfor sharing a single TCP port between multiple transports (TCP + WS). Mirrors thesharedTCP *tcpreuse.PortDemultiplexerparameter passed toNewTCPTransport/websocket.Newin go-libp2p.
- add_listen_addr(maddr: Multiaddr, conn_handler: Callable[[ReadWriteCloser], Awaitable[None]]) IListener | None
Create and return a listener for maddr.
Mirrors
Swarm.AddListenAddr()from go-libp2p.When a
PortDemultiplexerwas supplied at construction and the address is TCP-based, the manager callsdemultiplexed_listen()on the appropriateDemultiplexedConnTypeso that TCP and WebSocket transports can share the same OS socket.For non-TCP transports (e.g. QUIC) the transport’s own
create_listener()is used directly.- Parameters:
maddr – The multiaddress to listen on.
conn_handler – Handler called for every accepted connection.
- Returns:
An
IListener, orNoneif no transport supports maddr.
- add_transport(transport: ITransport) None
Append a transport to the routing list.
- Parameters:
transport – A transport instance implementing
ITransport.
- add_transports(transports: list[ITransport]) None
Convenience helper to register multiple transports at once.
- Parameters:
transports – List of transport instances.
- async close_all() None
Close all registered transports concurrently.
Called by
close()during teardown.
- get_transports() list[ITransport]
Return a shallow copy of the registered transports list.
- Returns:
List of registered
ITransportinstances.
- has_transport_for(maddr: Multiaddr) bool
Return
Trueif any registered transport can dial maddr.- Parameters:
maddr – The multiaddress to check.
- Returns:
Trueif a matching transport exists,Falseotherwise.
- listen_on(maddr: Multiaddr, conn_handler: Callable[[ReadWriteCloser], Awaitable[None]]) IListener | None
Deprecated alias for
add_listen_addr().
- set_background_nursery(nursery: Nursery) None
Pass the Swarm’s background nursery to all transports that need one.
Called once by
run()as soon as the background nursery is ready. Delegates to every transport that exposes aset_background_nurserymethod (currently QUIC and WebSocket).- Parameters:
nursery – The trio nursery to share with transports.
- set_swarm(swarm: object) None
Pass a reference to the Swarm to all transports that need it.
Called once by
run(). Needed byQUICTransportso it can calladd_conn()for inbound QUIC connections.- Parameters:
swarm – The
Swarminstance.
- transport_for_dialing(maddr: Multiaddr) ITransport | None
Return the first registered transport that can dial maddr, or
None.The manager first performs a cheap pre-filter using each transport’s
protocols()list (set intersection), and only callscan_dial()when there is at least one protocol name overlap. This avoids unnecessary work when many transports are registered.This is the Python equivalent of go-libp2p’s
Swarm.TransportForDialing().- Parameters:
maddr – The multiaddress to route.
- Returns:
The matching transport, or
Noneif no transport can handle the address.
- transport_for_listening(maddr: Multiaddr) ITransport | None
Return the first registered transport that can listen on maddr, or
None.Uses the same two-step pre-filter logic as
transport_for_dialing().This is the Python equivalent of go-libp2p’s
Swarm.TransportForListening().- Parameters:
maddr – The multiaddress to route.
- Returns:
The matching transport, or
Noneif no transport can handle the address.
- class libp2p.transport.WebsocketTransport(upgrader: TransportUpgrader, config: WebsocketConfig | None = None, tls_client_config: SSLContext | None = None, tls_server_config: SSLContext | None = None, handshake_timeout: float | None = None)
Bases:
ITransportLibp2p WebSocket transport implementation with production features:
Features: - WS and WSS protocol support with configurable TLS - Connection management with limits and tracking - Flow control and buffer management - SOCKS5 proxy support - Proper error handling and connection cleanup - Configurable timeouts and limits - Connection state monitoring - Concurrent connection handling
- can_dial(maddr: Multiaddr) bool
Return True if this WebSocket transport can dial the given multiaddr.
Checks whether the multiaddr matches the WebSocket multiaddr pattern (e.g.
/ip4/.../tcp/.../wsor/ip4/.../tcp/.../wss).The check is purely protocol-level (no I/O); it changed from async to sync to satisfy the
ITransportinterface.- Parameters:
maddr – The multiaddress to check.
- Returns:
True if this transport handles the multiaddr.
- can_listen(maddr: Multiaddr) bool
Return True if this WebSocket transport can listen on the given multiaddr.
- Parameters:
maddr – The multiaddress to check.
- Returns:
True if this transport can listen on the multiaddr.
- create_listener(handler: Callable[[ReadWriteCloser], Awaitable[None]]) IListener
Create a WebSocket listener with the given handler.
- Args:
handler: Connection handler function
- Returns:
A WebSocket listener
- Raises:
ValueError – If configuration validation fails
- async dial(maddr: Multiaddr) RawConnection
Dial a WebSocket connection to the given multiaddr.
Resolves DNS (dns, dns4, dns6, dnsaddr) before dialing (Phase 3.1).
- Args:
maddr: The multiaddr to dial (e.g., /ip4/127.0.0.1/tcp/8000/ws)
- Returns:
An upgraded RawConnection
- Raises:
OpenConnectionError – If connection fails, cannot dial the multiaddr, connection upgrade fails, or maximum connections reached
ValueError – If multiaddr is invalid or cannot be parsed
- async get_connections() dict[str, P2PWebSocketConnection]
Get all active connections.
- get_listeners() set[WebsocketListener]
Get all active listeners.
- protocols() list[str]
Return the list of multiaddr protocol names handled by WebSocket transport.
- Returns:
[“ws”, “wss”]
- resolve(maddr: Multiaddr) list[Multiaddr]
Resolve a WebSocket multiaddr to its concrete addresses. Currently, just validates and returns the input multiaddr.
- Args:
maddr: The multiaddr to resolve
- Returns:
List containing the original multiaddr
- libp2p.transport.identify_conn_type(prefix: bytes) DemultiplexedConnType
Classify a connection from its first 3 bytes.
Directly mirrors
tcpreuse.identifyConnType/IsMultistreamSelect/IsHTTP/IsTLSfrom go-libp2p.- Parameters:
prefix – Exactly 3 bytes read from the start of the stream.
- Returns:
The detected
DemultiplexedConnType.