libp2p package

Subpackages

Submodules

libp2p.abc module

class libp2p.abc.AbstractSecureConn

Bases: ABC

Abstract interface for secure connections.

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

abstract get_local_peer() ID

Retrieve the local peer’s identifier.

Returns:

The local peer ID.

abstract get_local_private_key() PrivateKey

Retrieve the local peer’s private key.

Returns:

The private key of the local peer.

abstract get_remote_peer() ID

Retrieve the remote peer’s identifier.

Returns:

The remote peer ID.

abstract get_remote_public_key() PublicKey

Retrieve the remote peer’s public key.

Returns:

The public key of the remote peer.

class libp2p.abc.IAddrBook

Bases: ABC

Interface for an address book.

Provides methods for managing peer addresses.

abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None

Add a single address for a given peer.

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

Parameters

peer_idID

The peer identifier for which to add the address.

addrMultiaddr

The multiaddress of the peer.

ttlint

The time-to-live for the address, after which it is no longer valid.

abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None

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_idID

The peer identifier for which to add addresses.

addrsSequence[Multiaddr]

A sequence of multiaddresses to add.

ttlint

The time-to-live for the addresses, after which they become invalid.

abstract addrs(peer_id: ID) list[Multiaddr]

Retrieve all known and valid addresses for the specified peer.

Parameters

peer_idID

The peer identifier whose addresses are requested.

Returns

list[Multiaddr]

A list of valid multiaddresses for the given peer.

abstract clear_addrs(peer_id: ID) None

Remove all stored addresses for the specified peer.

Parameters

peer_idID

The peer identifier whose addresses are to be removed.

abstract peers_with_addrs() list[ID]

Retrieve all peer identifiers that have stored addresses.

Returns

list[ID]

A list of peer IDs with stored addresses.

class libp2p.abc.ICertifiedAddrBook

Bases: ABC

Interface for a certified address book.

Provides methods for managing signed peer records

abstract consume_peer_record(envelope: Envelope, ttl: int) bool

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).

abstract get_peer_record(peer_id: ID) Envelope | None

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_idID

The peer to look up.

abstract maybe_delete_peer_record(peer_id: ID) None

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_idID

The peer whose record we may delete.

class libp2p.abc.IContentRouting

Bases: ABC

Interface for content routing.

Provides methods to advertise and search for content providers.

abstract find_provider_iter(cid: bytes, count: int) Iterable[PeerInfo]

Search for peers that can provide the content identified by the given CID.

Parameters

cidbytes

The content identifier.

countint

The maximum number of providers to return.

Returns

Iterable[PeerInfo]

An iterator of PeerInfo objects for peers that provide the content.

abstract provide(cid: bytes, announce: bool = True) None

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

cidbytes

The content identifier.

announcebool, optional

Whether to announce the provided content (default is True).

class libp2p.abc.IEnvelope

Bases: ABC

abstract equal(other: Any) bool

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

Parameters:

other – Another object to compare.

Returns:

True if equal, False otherwise.

abstract marshal_envelope() bytes

Serialize this Envelope into its protobuf wire format.

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

Returns:

Serialized envelope as bytes.

abstract record() PeerRecord

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.

Returns:

Decoded PeerRecord object.

Raises:

Exception – If decoding fails or payload type is unsupported.

abstract validate(domain: str) None

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.

Parameters:

domain – Domain string that contextualizes the signature.

Raises:

ValueError – If the signature is invalid.

class libp2p.abc.IHost

Bases: ABC

Interface for the host.

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

abstract async close() None

Close the host and all underlying connections and services.

abstract async connect(peer_info: PeerInfo) None

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_infoPeerInfo

The peer information of the peer to connect to.

abstract async disconnect(peer_id: ID) None

Disconnect from the specified peer.

Parameters

peer_idID

The identifier of the peer to disconnect from.

abstract get_addrs() list[Multiaddr]

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.

abstract get_connected_peers() list[ID]

Retrieve the identifiers of peers currently connected to the host.

Returns

list[ID]

A list of peer identifiers.

abstract get_id() ID

Retrieve the host’s peer identifier.

Returns

ID

The host’s peer identifier.

abstract get_live_peers() list[ID]
Returns:

List of peer IDs that have active connections

abstract get_mux() Multiselect

Retrieve the muxer instance for the host.

Returns

Any

The muxer instance of the host.

abstract get_network() INetworkService

Retrieve the network service instance associated with the host.

Returns

INetworkService

The network instance of the host.

abstract get_peerstore() IPeerStore
Returns:

the peerstore of the host

abstract get_private_key() PrivateKey

Retrieve the private key of the host.

Returns

PrivateKey

The private key belonging to the host.

abstract get_public_key() PublicKey

Retrieve the public key of the host.

Returns

PublicKey

The public key belonging to the host.

abstract get_transport_addrs() list[Multiaddr]

Retrieve the raw multiaddr addresses this host is listening to, without the /p2p/{peer_id} suffix.

Returns

list[Multiaddr]

A list of raw multiaddresses.

abstract async initiate_autotls_procedure(public_ip: str | None = None) None

Initiate the ACME-AUTO-TLS-BROKER negotiation for TLS certificate

abstract async new_stream(peer_id: ID, protocol_ids: Sequence[TProtocol]) INetStream

Create a new stream to the specified peer.

Parameters

peer_idID

The identifier of the peer to connect.

protocol_idsSequence[TProtocol]

A sequence of available protocol identifiers to use for the stream.

Returns

INetStream

The newly created network stream.

abstract remove_stream_handler(protocol_id: TProtocol) None

Remove the stream handler for the specified protocol.

Parameters

protocol_idTProtocol

The protocol identifier to remove the handler for.

abstract run(listen_addrs: Sequence[Multiaddr], *, task_status: Any = TASK_STATUS_IGNORED) AbstractAsyncContextManager[None]

Run the host and start listening on the specified multiaddresses.

Parameters

listen_addrsSequence[Multiaddr]

A sequence of multiaddresses on which the host should listen.

task_statusAny

Task status for trio nursery compatibility (ignored).

abstract set_stream_handler(protocol_id: TProtocol, stream_handler: Callable[[object], Awaitable[None]]) None

Set the stream handler for the specified protocol.

Parameters

protocol_idTProtocol

The protocol identifier used on the stream.

stream_handlerStreamHandlerFn

The stream handler function to be set.

abstract async upgrade_inbound_connection(raw_conn: IRawConnection, maddr: Multiaddr) IMuxedConn

Upgrade a raw inbound connection to a fully secure and multiplexed network connection for the given multiaddress.

Parameters

raw_connIRawConnection

The inbound raw connection to upgrade.

maddrMultiaddr

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

abstract async upgrade_outbound_connection(raw_conn: IRawConnection, peer_id: ID) INetConn

Upgrade a raw outbound connection to a fully secure and multiplexed network connection for the specified peer.

Parameters

raw_connIRawConnection

The raw (unencrypted/unmultiplexed) connection to upgrade.

peer_idID

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

class libp2p.abc.IKeyBook

Bases: ABC

Interface for an key book.

Provides methods for managing cryptographic keys.

abstract add_key_pair(peer_id: ID, key_pair: KeyPair) None

Adds the key pair for a specified peer

Parameters

peer_idID

The peer identifier whose key pair is to be added

key_pair: KeyPair

The key pair of the peer

abstract add_privkey(peer_id: ID, privkey: PrivateKey) None

Adds the private key for a specified peer

Parameters

peer_idID

The peer identifier whose private key is to be added

privkey: PrivateKey

The private key of the peer

abstract add_pubkey(peer_id: ID, pubkey: PublicKey) None

Adds the public key for a specified peer

Parameters

peer_idID

The peer identifier whose public key is to be added

pubkey: PublicKey

The public key of the peer

abstract clear_keydata(peer_id: ID) None

Remove all stored keydata for the specified peer.

Parameters

peer_idID

The peer identifier whose keys are to be removed.

abstract peer_with_keys() list[ID]

Returns all the peer IDs stored in the AddrBook

abstract privkey(peer_id: ID) PrivateKey

Returns the private key of the specified peer

Parameters

peer_idID

The peer identifier whose private key is to be returned.

abstract pubkey(peer_id: ID) PublicKey

Returns the public key of the specified peer

Parameters

peer_idID

The peer identifier whose public key is to be returned.

class libp2p.abc.IListener

Bases: ABC

Interface for a network listener.

Provides methods for starting a listener, retrieving its addresses, and closing it.

abstract async close() None

Close the listener.

abstract get_addrs() tuple[Multiaddr, ...]

Retrieve the list of addresses on which the listener is active.

Returns

tuple[Multiaddr, …]

A tuple of multiaddresses.

abstract async listen(maddr: Multiaddr) None

Start listening on the specified multiaddress.

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

Parameters

maddrMultiaddr

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).

class libp2p.abc.IMetrics

Bases: ABC

Interface for metrics of peer interaction.

Provides methods for managing the metrics.

abstract clear_metrics(peer_id: ID) None

Clears the stored latency metrics for the specified peer.

Parameters

peer_idID

The identifier of the peer whose latency metrics are to be cleared.

abstract latency_EWMA(peer_id: ID) float

Returns the current latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).

Parameters

peer_idID

The identifier of the peer whose latency EWMA is to be returned.

abstract record_latency(peer_id: ID, RTT: float) None

Records a new round-trip time (RTT) latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).

Parameters

peer_idID

The identifier of the peer for which latency is being recorded.

RTTfloat

The round-trip time latency value to record.

class libp2p.abc.IMultiselectClient

Bases: ABC

Client for multiselect negotiation.

Communicates with the receiver’s multiselect module to select a protocol for communication.

abstract async handshake(communicator: IMultiselectCommunicator) None

Ensure that the client and multiselect module are using the same multiselect protocol.

Parameters

communicatorIMultiselectCommunicator

The communicator used for negotiating the multiselect protocol.

Raises

Exception

If there is a multiselect protocol ID mismatch.

abstract async select_one_of(protocols: Sequence[TProtocol], communicator: IMultiselectCommunicator) TProtocol

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

protocolsSequence[TProtocol]

The protocols to attempt selection.

communicatorIMultiselectCommunicator

The communicator used for negotiating the protocol.

Returns

TProtocol

The protocol selected by the multiselect module.

abstract async try_select(communicator: IMultiselectCommunicator, protocol: TProtocol) TProtocol

Attempt to select the given protocol.

Parameters

communicatorIMultiselectCommunicator

The communicator used to interact with the counterparty.

protocolTProtocol

The protocol to select.

Returns

TProtocol

The protocol if successfully selected.

Raises

Exception

If protocol selection fails.

class libp2p.abc.IMultiselectCommunicator

Bases: ABC

Communicator helper for multiselect.

Ensures that both the client and multistream module follow the same multistream protocol.

abstract async read() str

Read a message from the stream until EOF.

Returns

str

The message read from the stream.

abstract async write(msg_str: str) None

Write a message to the stream.

Parameters

msg_strstr

The message string to write.

class libp2p.abc.IMultiselectMuxer

Bases: ABC

Multiselect module for protocol negotiation.

Responsible for responding to a multiselect client by selecting a protocol and its corresponding handler for communication.

abstract add_handler(protocol: TProtocol, handler: Callable[[object], Awaitable[None]]) None

Store a handler for the specified protocol.

Parameters

protocolTProtocol

The protocol name.

handlerStreamHandlerFn

The handler function associated with the protocol.

abstract get_protocols() tuple[TProtocol | None, ...]

Retrieve the protocols for which handlers have been registered.

Returns

tuple[TProtocol, …]

A tuple of registered protocol names.

handlers: dict[TProtocol | None, Callable[[object], Awaitable[None]] | None]
abstract async negotiate(communicator: IMultiselectCommunicator) tuple[TProtocol | None, Callable[[object], Awaitable[None]] | None]

Negotiate a protocol selection with a multiselect client.

Parameters

communicatorIMultiselectCommunicator

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.

abstract remove_handler(protocol: TProtocol) None

Remove the handler for the specified protocol.

Parameters

protocolTProtocol

The protocol name to remove.

class libp2p.abc.IMuxedConn(conn: ISecureConn, peer_id: ID)

Bases: ABC

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.

abstract async accept_stream() IMuxedStream

Accept a new multiplexed stream initiated by the remote peer.

Returns:

A new instance of IMuxedStream.

abstract async close() None

Close the multiplexed connection.

event_started: Event
abstract get_connection_type() ConnectionType

Get connection type by delegating to secured_conn.

abstract get_transport_addresses() list[Multiaddr]

Get transport addresses by delegating to secured_conn.

abstract property is_closed: bool

Check if the connection is fully closed.

Returns:

True if the connection is closed, otherwise False.

abstract property is_established: bool

Check if the connection is fully established and ready for streams.

Returns:

True if the connection is established, otherwise False.

abstract property is_initiator: bool

Determine if this connection is the initiator.

Returns:

True if this connection initiated the connection, otherwise False.

abstract async open_stream() IMuxedStream

Create and open a new multiplexed stream.

Returns:

A new instance of IMuxedStream.

peer_id: ID
abstract async start() None

Start the multiplexer.

class libp2p.abc.IMuxedStream

Bases: ReadWriteCloser, AsyncContextManager[IMuxedStream]

Interface for a multiplexed stream.

Represents a stream multiplexed over a single connection.

Attributes

muxed_conn (IMuxedConn):

The underlying multiplexed connection.

muxed_conn: IMuxedConn
abstract async reset() None

Reset the stream.

This method closes both ends of the stream, instructing the remote side to hang up.

abstract set_deadline(ttl: int) None

Set a deadline for the stream.

Parameters:

ttl – Time-to-live for the stream in seconds.

Raises:

ValueError – if ttl is invalid (e.g. negative).

class libp2p.abc.INetConn

Bases: Closer

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.

event_started: Event
abstract get_connection_type() ConnectionType

Get the type of connection (direct, relayed, etc.)

abstract get_streams() tuple[INetStream, ...]

Retrieve all active streams associated with this connection.

Returns:

A tuple containing instances of INetStream.

abstract get_transport_addresses() list[Multiaddr]

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.

Returns:

A list of multiaddresses used by the transport.

abstract property is_closed: bool

Check if the connection is fully closed.

Returns:

True if the connection is closed, otherwise False.

muxed_conn: IMuxedConn
abstract async new_stream() INetStream

Create a new network stream over the connection.

Returns:

A new instance of INetStream.

class libp2p.abc.INetStream

Bases: ReadWriteCloser

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.

abstract get_protocol() TProtocol | None

Retrieve the protocol identifier for the stream.

Returns:

The protocol ID associated with the stream.

muxed_conn: IMuxedConn
abstract async reset() None

Reset the network stream.

This method closes both ends of the stream.

abstract set_protocol(protocol_id: TProtocol) None

Set the protocol identifier for the stream.

Parameters:

protocol_id – The protocol ID to assign to the stream.

class libp2p.abc.INetwork

Bases: ABC

Interface for the network.

Provides methods for managing connections, streams, and listeners.

Attributes

peerstoreIPeerStore

The peer store for managing peer information.

connectionsdict[ID, list[INetConn]]

A mapping of peer IDs to lists of network connections (multiple connections per peer).

listenersdict[str, IListener]

A mapping of listener identifiers to listener instances.

abstract async close() None

Close the network and all associated connections and listeners.

abstract async close_peer(peer_id: ID) None

Close the connection to the specified peer.

Parameters

peer_idID

The identifier of the peer whose connection should be closed.

connections: dict[ID, list[INetConn]]
abstract async dial_peer(peer_id: ID) list[INetConn]

Create connections to the specified peer with load balancing.

Parameters

peer_idID

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.

abstract get_connection(peer_id: ID) INetConn | None

Get single connection for backward compatibility.

Parameters

peer_idID

The peer ID to get a connection for.

Returns

INetConn | None

The first available connection, or None if no connections exist.

abstract get_connections(peer_id: ID | None = None) list[INetConn]

Get connections for peer (like JS getConnections, Go ConnsToPeer).

Parameters

peer_idID | 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.

abstract get_connections_map() dict[ID, list[INetConn]]

Get all connections map (like JS getConnectionsMap).

Returns

dict[ID, list[INetConn]]

The complete mapping of peer IDs to their connection lists.

abstract get_peer_id() ID

Retrieve the peer identifier for this network.

Returns

ID

The identifier of this peer.

abstract async listen(*multiaddrs: Multiaddr) bool

Start listening on one or more multiaddresses.

Parameters

multiaddrsSequence[Multiaddr]

One or more multiaddresses on which to start listening.

Returns

bool

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

listeners: dict[str, IListener]
abstract async new_stream(peer_id: ID) INetStream

Create a new network stream to the specified peer.

Parameters

peer_idID

The identifier of the destination peer.

Returns

INetStream

The newly created network stream.

peerstore: IPeerStore
abstract register_notifee(notifee: INotifee) None

Register a notifee instance to receive network events.

Parameters

notifeeINotifee

An object implementing the INotifee interface.

abstract set_stream_handler(stream_handler: Callable[[object], Awaitable[None]]) None

Set the stream handler for incoming streams.

Parameters

stream_handlerStreamHandlerFn

The handler function to process incoming streams.

abstract async upgrade_inbound_raw_conn(raw_conn: IRawConnection, maddr: Multiaddr) IMuxedConn

Secure and upgrade a raw inbound connection to a multiplexed network connection

Parameters

raw_connIRawConnection

The incoming raw connection to upgrade.

maddrMultiaddr

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.

abstract async upgrade_outbound_raw_conn(raw_conn: IRawConnection, peer_id: ID) INetConn

Secure and upgrade a raw outbound connection to a multiplexed network connection

Parameters

raw_connIRawConnection

The raw connection to upgrade.

peer_idID

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.

class libp2p.abc.INetworkService

Bases: INetwork, ServiceAPI

Interface for a network service with connection management capabilities.

Extends INetwork with go-libp2p style connection manager methods.

connection_gate: Any
abstract get_metrics() dict[str, int]

Get connection metrics (go-libp2p style).

Returns

dict[str, int]

Connection metrics including total, inbound, and outbound counts.

abstract get_tag_info(peer_id: ID) Any

Get the metadata associated with a peer.

Parameters

peer_idID

The peer to get info for.

Returns

Any

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

abstract get_total_connections() int

Get total number of connections (inbound + outbound).

Returns

int

Total number of active connections.

abstract is_protected(peer_id: ID, tag: str = '') bool

Check if a peer is protected.

Parameters

peer_idID

The peer to check.

tagstr

If provided, check if protected by this specific tag.

Returns

bool

True if the peer is protected.

abstract protect(peer_id: ID, tag: str) None

Protect a peer from having its connection(s) pruned.

Parameters

peer_idID

The peer to protect.

tagstr

Protection tag.

abstract tag_peer(peer_id: ID, tag: str, value: int) None

Tag a peer with a string, associating a weight with the tag.

Parameters

peer_idID

The peer to tag.

tagstr

The tag name.

valueint

The weight/value associated with the tag.

abstract unprotect(peer_id: ID, tag: str) bool

Remove a protection that may have been placed on a peer.

Parameters

peer_idID

The peer to unprotect.

tagstr

The protection tag to remove.

Returns

bool

True if the peer is still protected by other tags.

abstract untag_peer(peer_id: ID, tag: str) None

Remove the tagged value from the peer.

Parameters

peer_idID

The peer to untag.

tagstr

The tag name to remove.

class libp2p.abc.INotifee

Bases: ABC

Interface for a network service.

Extends the INetwork interface with additional service management capabilities.

abstract async closed_stream(network: INetwork, stream: INetStream) None

Called when a stream is closed.

Parameters

networkINetwork

The network instance on which the stream was closed.

streamINetStream

The stream that was closed.

abstract async connected(network: INetwork, conn: INetConn) None

Called when a new connection is established.

Parameters

networkINetwork

The network instance where the connection was established.

connINetConn

The connection that was opened.

abstract async disconnected(network: INetwork, conn: INetConn) None

Called when a connection is closed.

Parameters

networkINetwork

The network instance where the connection was closed.

connINetConn

The connection that was closed.

abstract async listen(network: INetwork, multiaddr: Multiaddr) None

Called when a listener starts on a multiaddress.

Parameters

networkINetwork

The network instance where the listener is active.

multiaddrMultiaddr

The multiaddress on which the listener is listening.

abstract async listen_close(network: INetwork, multiaddr: Multiaddr) None

Called when a listener stops listening on a multiaddress.

Parameters

networkINetwork

The network instance where the listener was active.

multiaddrMultiaddr

The multiaddress that is no longer being listened on.

abstract async opened_stream(network: INetwork, stream: INetStream) None

Called when a new stream is opened.

Parameters

networkINetwork

The network instance on which the stream was opened.

streamINetStream

The stream that was opened.

class libp2p.abc.IPeerData

Bases: ABC

Interface for managing peer data.

Provides methods for handling protocols, addresses, metadata, and keys associated with a peer.

abstract add_addrs(addrs: Sequence[Multiaddr]) None

Add multiple multiaddresses to the peer’s data.

Parameters

addrsSequence[Multiaddr]

A sequence of multiaddresses to add.

ttl: inr

Time to live for the peer record

abstract add_privkey(privkey: PrivateKey) None

Add a private key to the peer’s data.

Parameters

privkeyPrivateKey

The private key to add.

abstract add_protocols(protocols: Sequence[str]) None

Add one or more protocols to the peer’s data.

Parameters

protocolsSequence[str]

A sequence of protocols to add.

abstract add_pubkey(pubkey: PublicKey) None

Add a public key to the peer’s data.

Parameters

pubkeyPublicKey

The public key to add.

abstract clear_addrs() None

Clear all addresses associated with the peer.

abstract clear_keydata() None

Clears all cryptographic key data associated with this peer, including both public and private keys.

abstract clear_metadata() None

Clears all metadata entries associated with this peer.

abstract clear_metrics() None

Clears all latency-related metrics and resets the internal state.

abstract clear_protocol_data() None

Clears all protocol data associated with this peer.

abstract first_supported_protocol(protocols: Sequence[str]) str

Returns the first protocol from the input list that this peer supports.

Parameters

protocolsSequence[str]

A sequence of protocol strings to check for support.

Returns

str

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

abstract get_addrs() list[Multiaddr]

Retrieve all multiaddresses associated with the peer.

Returns

list[Multiaddr]

A list of multiaddresses.

abstract get_last_identified() int

Fetch the last identified timestamp

Returns

last_identified_timestamp

The lastIdentified time of peer.

abstract get_metadata(key: str) str | int | float | bool | None

Retrieve metadata for a given key.

Parameters

keystr

The metadata key.

Returns

MetadataValue

The metadata value for the given key.

Raises

PeerDataError

If the key is not found.

abstract get_privkey() PrivateKey

Retrieve the private key for the peer.

Returns

PrivateKey

The private key of the peer.

Raises

PeerDataError

If the private key is not found.

abstract get_protocols() list[str]

Retrieve all protocols associated with the peer.

Returns

list[str]

A list of protocols associated with the peer.

abstract get_pubkey() PublicKey

Retrieve the public key for the peer.

Returns

PublicKey

The public key of the peer.

Raises

PeerDataError

If the public key is not found.

abstract get_ttl() int

Get ttl value for the peer for validity check

Returns

int

The ttl of the peer.

abstract is_expired() bool

Check if the peer is expired based on last_identified and ttl

Returns

bool

True, if last_identified + ttl > current_time

abstract latency_EWMA() float

Returns the current EWMA value of the recorded latency.

Returns

float

The current latency estimate based on EWMA.

abstract put_metadata(key: str, val: str | int | float | bool | None) None

Store a metadata key-value pair for the peer.

Parameters

keystr

The metadata key.

valMetadataValue

The value to associate with the key.

abstract record_latency(new_latency: float) None

Records a new latency measurement using Exponentially Weighted Moving Average (EWMA).

Parameters

new_latencyfloat

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

abstract remove_protocols(protocols: Sequence[str]) None

Removes the specified protocols from this peer’s list of supported protocols.

Parameters

protocolsSequence[str]

A sequence of protocol strings to be removed.

abstract set_protocols(protocols: Sequence[str]) None

Set the protocols for the peer.

Parameters

protocolsSequence[str]

A sequence of protocols to set.

abstract set_ttl(ttl: int) None

Set ttl value for the peer for validity check

Parameters

ttlint

The ttl for the peer.

abstract supports_protocols(protocols: Sequence[str]) list[str]

Returns the list of protocols from the input sequence that are supported by this peer.

Parameters

protocolsSequence[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.

abstract update_last_identified() None

Updates timestamp to current time.

class libp2p.abc.IPeerMetadata

Bases: ABC

Interface for managing peer metadata.

Provides methods for storing and retrieving metadata associated with peers.

abstract clear_metadata(peer_id: ID) None

Remove all stored metadata for the specified peer.

Parameters

peer_idID

The peer identifier whose metadata are to be removed.

abstract get(peer_id: ID, key: str) str | int | float | bool | None

Retrieve metadata for a specified peer.

Parameters:
  • peer_id – The ID of the peer.

  • key – The key for the metadata to retrieve.

Returns:

The metadata value associated with the key.

Raises:

Exception – If the peer ID is not found.

abstract put(peer_id: ID, key: str, val: str | int | float | bool | None) None

Store metadata for a specified peer.

Parameters:
  • peer_id – The ID of the peer.

  • key – The key for the metadata.

  • val – The value to store.

Raises:

Exception – If the operation is unsuccessful.

class libp2p.abc.IPeerRecord

Bases: ABC

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.

abstract codec() bytes

Return a binary codec prefix that identifies the PeerRecord type.

This is prepended in signed envelopes to allow type-safe decoding.

abstract domain() str

Return the domain string for this record type.

Used in envelope validation to distinguish different record types.

abstract equal(other: object) bool

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

Parameters:

other – Object to compare with.

Returns:

True if equal, False otherwise.

abstract marshal_record() bytes

Serialize this PeerRecord into a byte string.

Used when signing or sealing the record in an envelope.

Raises:

ValueError – if protobuf serialization fails.

Returns:

Byte-encoded PeerRecord.

abstract to_protobuf() PeerRecord

Convert this PeerRecord into its Protobuf representation.

Raises:

ValueError – if serialization fails (e.g., invalid peer ID).

Returns:

A populated protobuf PeerRecord message.

class libp2p.abc.IPeerRouting

Bases: ABC

Interface for peer routing.

Provides methods to search for a specific peer.

abstract async find_peer(peer_id: ID) PeerInfo | None

Search for a peer with the specified peer ID.

Parameters

peer_idID

The identifier of the peer to search for.

Returns

PeerInfo

The peer information containing relevant addresses.

class libp2p.abc.IPeerStore

Bases: IPeerMetadata, IAddrBook, ICertifiedAddrBook, IKeyBook, IMetrics, IProtoBook

Interface for a peer store.

Provides methods for managing peer information including address management, protocol handling, and key storage.

abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None

Add an address for the specified peer.

Parameters

peer_idID

The identifier of the peer.

addrMultiaddr

The multiaddress to add.

ttlint

The time-to-live for the record.

abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None

Add multiple addresses for the specified peer.

Parameters

peer_idID

The identifier of the peer.

addrsSequence[Multiaddr]

A sequence of multiaddresses to add.

ttlint

The time-to-live for the record.

abstract add_key_pair(peer_id: ID, key_pair: KeyPair) None

Add a key pair for the specified peer.

Parameters

peer_idID

The identifier of the peer.

key_pairKeyPair

The key pair to add.

Raises

PeerStoreError

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

abstract add_privkey(peer_id: ID, privkey: PrivateKey) None

Add a private key for the specified peer.

Parameters

peer_idID

The identifier of the peer.

privkeyPrivateKey

The private key to add.

Raises

PeerStoreError

If the peer already has a private key set.

abstract add_protocols(peer_id: ID, protocols: Sequence[str]) None

Add additional protocols for the specified peer.

Parameters

peer_idID

The identifier of the peer.

protocolsSequence[str]

The protocols to add.

abstract add_pubkey(peer_id: ID, pubkey: PublicKey) None

Add a public key for the specified peer.

Parameters

peer_idID

The identifier of the peer.

pubkeyPublicKey

The public key to add.

Raises

PeerStoreError

If the peer already has a public key set.

abstract addrs(peer_id: ID) list[Multiaddr]

Retrieve the addresses for the specified peer.

Parameters

peer_idID

The identifier of the peer.

Returns

list[Multiaddr]

A list of multiaddresses.

abstract clear_addrs(peer_id: ID) None

Clear all addresses for the specified peer.

Parameters

peer_idID

The identifier of the peer.

abstract clear_keydata(peer_id: ID) None

Remove all stored keydata for the specified peer.

Parameters

peer_idID

The peer identifier whose keys are to be removed.

abstract clear_metadata(peer_id: ID) None

Clears the stored latency metrics for the specified peer.

Parameters

peer_idID

The identifier of the peer whose latency metrics are to be cleared.

abstract clear_metrics(peer_id: ID) None

Clears the stored latency metrics for the specified peer.

Parameters

peer_idID

The identifier of the peer whose latency metrics are to be cleared.

abstract clear_peerdata(peer_id: ID) None
abstract clear_protocol_data(peer_id: ID) None

Clears all protocol data associated with the specified peer.

Parameters

peer_idID

The identifier of the peer whose protocol data will be cleared.

abstract consume_peer_record(envelope: Envelope, ttl: int) bool

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).

abstract first_supported_protocol(peer_id: ID, protocols: Sequence[str]) str

Returns the first protocol from the input list that the peer supports.

Parameters

peer_idID

The identifier of the peer to check for supported protocols.

protocolsSequence[str]

A sequence of protocol strings to check.

Returns

str

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

abstract get(peer_id: ID, key: str) str | int | float | bool | None

Retrieve the value associated with a key for a specified peer.

Parameters

peer_idID

The identifier of the peer.

keystr

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.

abstract get_local_record() Envelope | None

Get the local-peer-record wrapped in Envelope

abstract get_peer_record(peer_id: ID) Envelope | None

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_idID

The peer to look up.

abstract get_protocols(peer_id: ID) list[str]

Retrieve the protocols associated with the specified peer.

Parameters

peer_idID

The identifier of the peer.

Returns

list[str]

A list of protocol identifiers.

Raises

PeerStoreError

If the peer ID is not found.

abstract latency_EWMA(peer_id: ID) float

Returns the current latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).

Parameters

peer_idID

The identifier of the peer whose latency EWMA is to be returned.

abstract maybe_delete_peer_record(peer_id: ID) None

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_idID

The peer whose record we may delete.

abstract peer_ids() list[ID]

Retrieve all peer identifiers stored in the peer store.

Returns

list[ID]

A list of all peer IDs in the store.

abstract peer_info(peer_id: ID) PeerInfo

Retrieve the peer information for the specified peer.

Parameters

peer_idID

The identifier of the peer.

Returns

PeerInfo

The peer information object for the given peer.

abstract peer_with_keys() list[ID]

Returns all the peer IDs stored in the AddrBook

abstract peers_with_addrs() list[ID]

Retrieve all peer identifiers with stored addresses.

Returns

list[ID]

A list of peer IDs.

abstract privkey(peer_id: ID) PrivateKey

Retrieve the private key for the specified peer.

Parameters

peer_idID

The identifier of the peer.

Returns

PrivateKey

The private key of the peer.

Raises

PeerStoreError

If the peer ID is not found.

abstract pubkey(peer_id: ID) PublicKey

Retrieve the public key for the specified peer.

Parameters

peer_idID

The identifier of the peer.

Returns

PublicKey

The public key of the peer.

Raises

PeerStoreError

If the peer ID is not found.

abstract put(peer_id: ID, key: str, val: str | int | float | bool | None) None

Store a key-value pair for the specified peer.

Parameters

peer_idID

The identifier of the peer.

keystr

The key for the data.

valMetadataValue

The value to store.

abstract record_latency(peer_id: ID, RTT: float) None

Records a new round-trip time (RTT) latency value for the specified peer using Exponentially Weighted Moving Average (EWMA).

Parameters

peer_idID

The identifier of the peer for which latency is being recorded.

RTTfloat

The round-trip time latency value to record.

abstract remove_protocols(peer_id: ID, protocols: Sequence[str]) None

Removes the specified protocols from the peer’s protocol list.

Parameters

peer_idID

The identifier of the peer from which protocols will be removed.

protocolsSequence[str]

A sequence of protocol strings to remove.

abstract set_local_record(envelope: Envelope) None

Set the local-peer-record wrapped in Envelope

abstract set_protocols(peer_id: ID, protocols: Sequence[str]) None

Set the protocols for the specified peer.

Parameters

peer_idID

The identifier of the peer.

protocolsSequence[str]

The protocols to set.

abstract async start_cleanup_task(cleanup_interval: int = 3600) None

Start periodic cleanup of expired peer records and addresses.

abstract supports_protocols(peer_id: ID, protocols: Sequence[str]) list[str]

Returns the list of protocols from the input sequence that the peer supports.

Parameters

peer_idID

The identifier of the peer to check for protocol support.

protocolsSequence[str]

A sequence of protocol strings to check against the peer’s supported protocols.

class libp2p.abc.IPerf

Bases: ABC

Interface for the perf protocol service.

Spec: https://github.com/libp2p/specs/blob/master/perf/perf.md

abstract is_started() bool

Check if the service is currently running.

abstract measure_performance(multiaddr: Multiaddr, send_bytes: int, recv_bytes: int) AsyncIterator[Any]

Measure transfer performance to a remote peer.

Parameters

multiaddrMultiaddr

The address of the remote peer to test against.

send_bytesint

Number of bytes to upload to the remote peer.

recv_bytesint

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.

abstract async start() None

Start the perf service and register the protocol handler.

abstract async stop() None

Stop the perf service and unregister the protocol handler.

class libp2p.abc.IProtoBook

Bases: ABC

Interface for a protocol book.

Provides methods for managing the list of supported protocols.

abstract add_protocols(peer_id: ID, protocols: Sequence[str]) None

Adds the given protocols to the specified peer’s protocol list.

Parameters

peer_idID

The identifier of the peer to which protocols will be added.

protocolsSequence[str]

A sequence of protocol strings to add.

abstract clear_protocol_data(peer_id: ID) None

Clears all protocol data associated with the specified peer.

Parameters

peer_idID

The identifier of the peer whose protocol data will be cleared.

abstract first_supported_protocol(peer_id: ID, protocols: Sequence[str]) str

Returns the first protocol from the input list that the peer supports.

Parameters

peer_idID

The identifier of the peer to check for supported protocols.

protocolsSequence[str]

A sequence of protocol strings to check.

Returns

str

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

abstract get_protocols(peer_id: ID) list[str]

Returns the list of protocols associated with the specified peer.

Parameters

peer_idID

The identifier of the peer whose supported protocols are to be returned.

abstract remove_protocols(peer_id: ID, protocols: Sequence[str]) None

Removes the specified protocols from the peer’s protocol list.

Parameters

peer_idID

The identifier of the peer from which protocols will be removed.

protocolsSequence[str]

A sequence of protocol strings to remove.

abstract set_protocols(peer_id: ID, protocols: Sequence[str]) None

Replaces the existing protocols of the specified peer with the given list.

Parameters

peer_idID

The identifier of the peer whose protocols are to be set.

protocolsSequence[str]

A sequence of protocol strings to assign.

abstract supports_protocols(peer_id: ID, protocols: Sequence[str]) list[str]

Returns the list of protocols from the input sequence that the peer supports.

Parameters

peer_idID

The identifier of the peer to check for protocol support.

protocolsSequence[str]

A sequence of protocol strings to check against the peer’s supported protocols.

class libp2p.abc.IPubsub

Bases: ServiceAPI

Interface for the pubsub system.

Provides properties and methods to manage topics, subscriptions, and message publishing.

abstract property my_id: ID

Retrieve the identifier for this pubsub instance.

Returns

ID

The pubsub identifier.

abstract property protocols: tuple[TProtocol, ...]

Retrieve the protocols used by the pubsub system.

Returns

tuple[TProtocol, …]

A tuple of protocol identifiers.

abstract async publish(topic_id: str | list[str], data: bytes) None

Publish a message to a topic or multiple topics.

Parameters

topic_idstr | list[str]

The identifier of the topic (str) or topics (list[str]).

databytes

The data to publish.

abstract remove_topic_validator(topic: str) None

Remove the validator for a specific topic.

Parameters

topicstr

The topic whose validator should be removed.

abstract set_topic_validator(topic: str, validator: Callable[[ID, Message], bool] | Callable[[ID, Message], Awaitable[bool]], is_async_validator: bool) None

Set a validator for a specific topic.

Parameters

topicstr

The topic for which to set the validator.

validatorValidatorFn

The validator function.

is_async_validatorbool

Whether the validator is asynchronous.

abstract async subscribe(topic_id: str) ISubscriptionAPI

Subscribe to a topic.

Parameters

topic_idstr

The identifier of the topic to subscribe to.

Returns

ISubscriptionAPI

An object representing the subscription.

abstract property topic_ids: KeysView[str]

Retrieve the set of topic identifiers.

Returns

KeysView[str]

A view of the topic identifiers.

abstract async unsubscribe(topic_id: str) None

Unsubscribe from a topic.

Parameters

topic_idstr

The identifier of the topic to unsubscribe from.

abstract async wait_for_peer(peer_id: ID, timeout: float = 5.0) None

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 trio.Event so the task consumes zero CPU while waiting.

Parameters

peer_idID

The identifier of the peer to wait for.

timeoutfloat

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
abstract async wait_for_subscription(peer_id: ID, topic_id: str, timeout: float = 5.0) None

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 trio.Event so the task consumes zero CPU while waiting.

Parameters

peer_idID

The identifier of the peer to wait for.

topic_idstr

The topic to check subscription for.

timeoutfloat

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
abstract async wait_until_ready() None

Wait until the pubsub system is fully initialized and ready.

class libp2p.abc.IPubsubRouter

Bases: ABC

Interface for a pubsub router.

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

abstract add_peer(peer_id: ID, protocol_id: TProtocol | None) None

Notify the router that a new peer has connected.

Parameters

peer_idID

The identifier of the peer.

protocol_idTProtocol

The protocol the peer supports (e.g., floodsub, gossipsub).

abstract attach(pubsub: Pubsub) None

Attach the router to a newly initialized PubSub instance.

Parameters

pubsubPubsub

The PubSub instance to attach to.

degree: int
fanout: dict[str, set[ID]]
abstract get_protocols() list[TProtocol]

Retrieve the list of protocols supported by the router.

Returns

list[TProtocol]

A list of supported protocol identifiers.

abstract async handle_rpc(rpc: RPC, sender_peer_id: ID) None

Process an RPC message received from a peer.

Parameters

rpcrpc_pb2.RPC

The RPC message to process.

sender_peer_idID

The identifier of the peer that sent the message.

abstract async join(topic: str) None

Join a topic to receive and forward messages.

Parameters

topicstr

The topic to join.

abstract async leave(topic: str) None

Leave a topic, stopping message forwarding for that topic.

Parameters

topicstr

The topic to leave.

mesh: dict[str, set[ID]]
peer_protocol: dict[ID, TProtocol]
abstract async publish(msg_forwarder: ID, pubsub_msg: Message) None

Forward a validated pubsub message.

Parameters

msg_forwarderID

The identifier of the message sender.

pubsub_msgrpc_pb2.Message

The pubsub message to forward.

abstract remove_peer(peer_id: ID) None

Notify the router that a peer has disconnected.

Parameters

peer_idID

The identifier of the peer to remove.

class libp2p.abc.IRawConnection

Bases: ReadWriteCloser

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.

abstract get_connection_type() ConnectionType

Get the type of connection (direct, relayed, etc.)

abstract get_transport_addresses() list[Multiaddr]

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.

is_initiator: bool
class libp2p.abc.ISecureConn

Bases: AbstractSecureConn, IRawConnection

Interface for a secure connection.

Combines secure connection functionalities with raw I/O operations.

class libp2p.abc.ISecureTransport

Bases: ABC

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

abstract async secure_inbound(conn: IRawConnection) ISecureConn

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

connIRawConnection

The raw connection to secure.

Returns

ISecureConn

The secured connection instance.

abstract async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn

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

connIRawConnection

The raw connection to secure.

peer_idID

The identifier of the remote peer.

Returns

ISecureConn

The secured connection instance.

class libp2p.abc.ISubscriptionAPI

Bases: AsyncContextManager[ISubscriptionAPI], AsyncIterable[Message]

Interface for a subscription in pubsub.

Combines asynchronous context management and iteration over messages.

abstract async get() Message

Retrieve the next message from the subscription.

Returns

rpc_pb2.Message

The next pubsub message.

abstract async unsubscribe() None

Unsubscribe from the current topic.

class libp2p.abc.ITransport

Bases: ABC

Interface for a transport.

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

abstract create_listener(handler_function: Callable[[ReadWriteCloser], Awaitable[None]]) IListener

Create a listener on the transport.

Parameters

handler_functionTHandler

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.

abstract async dial(maddr: Multiaddr) IRawConnection

Dial a peer on the specified multiaddress.

Parameters

maddrMultiaddr

The multiaddress of the peer to dial.

Returns

IRawConnection

The raw connection established to the peer.

libp2p.exceptions module

exception libp2p.exceptions.BaseLibp2pError

Bases: Exception

exception libp2p.exceptions.MultiError(errors: Sequence[Exception])

Bases: BaseLibp2pError

A combined error that wraps multiple exceptions into a single error object. This error is raised when multiple exceptions need to be reported together, typically in scenarios where parallel operations or multiple validations fail.

Example:

>>> from libp2p.exceptions import MultiError
>>> errors = [
...     ValueError("Invalid input"),
...     TypeError("Wrong type"),
...     RuntimeError("Operation failed")
... ]
>>> multi_error = MultiError(errors)
>>> print(multi_error)
Error 1: Invalid input
Error 2: Wrong type
Error 3: Operation failed

Note:

The string representation of this error will number and list all contained errors sequentially, making it easier to identify individual issues in complex error scenarios.

exception libp2p.exceptions.ParseError

Bases: BaseLibp2pError

exception libp2p.exceptions.ValidationError

Bases: BaseLibp2pError

Raised when something does not pass a validation check.

libp2p.custom_types module

Module contents

Libp2p Python implementation.

libp2p.create_mplex_muxer_option() Mapping[TProtocol, type[object]]

Returns muxer options with Mplex as the primary choice.

Returns:

Muxer options with Mplex first

libp2p.create_yamux_muxer_option() Mapping[TProtocol, type[object]]

Returns muxer options with Yamux as the primary choice.

Returns:

Muxer options with Yamux first

libp2p.generate_new_ed25519_identity() KeyPair

Generate a new Ed25519 identity key pair.

Ed25519 is preferred for better interoperability with other libp2p implementations (e.g., Rust, Go) which often disable RSA support.

libp2p.generate_new_rsa_identity() KeyPair
libp2p.generate_peer_id_from(key_pair: KeyPair) ID
libp2p.get_default_muxer() str

Returns the currently selected default muxer.

Returns:

Either “YAMUX” or “MPLEX”

libp2p.get_default_muxer_options() Mapping[TProtocol, type[object]]

Returns the default muxer options based on the current default muxer setting.

Returns:

Muxer options with the preferred muxer first

libp2p.load_keypair(type: str = 'ed25519') KeyPair | None

Load a private key from disk and reconstruct its KeyPair.

Currently supports only Ed25519 keys. Returns None if the key file does not exist.

Parameters:

type – Type of key to load (default: “ed25519”).

Returns:

KeyPair object if found, or None.

Raises:

ValueError – if an unsupported key type is provided.

libp2p.new_host(key_pair: KeyPair | None = None, muxer_opt: TMuxerOptions | None = None, sec_opt: TSecurityOptions | None = None, peerstore_opt: IPeerStore | None = None, disc_opt: IPeerRouting | None = None, muxer_preference: Literal['YAMUX', 'MPLEX'] | None = None, listen_addrs: Sequence[multiaddr.Multiaddr] | None = None, enable_mDNS: bool = False, enable_upnp: bool = False, enable_autotls: bool = False, bootstrap: list[str] | None = None, negotiate_timeout: int = 30, enable_quic: bool = False, quic_transport_opt: QUICTransportConfig | None = None, tls_client_config: ssl.SSLContext | None = None, tls_server_config: ssl.SSLContext | None = None, resource_manager: ResourceManager | None = None, psk: str | None = None, bootstrap_allow_ipv6: bool = False, bootstrap_dns_timeout: float = 10.0, bootstrap_dns_max_retries: int = 3, connection_config: ConnectionConfig | None = None, announce_addrs: Sequence[multiaddr.Multiaddr] | None = None) IHost

Create a new libp2p host based on the given parameters.

Parameters:
  • key_pair – optional choice of the KeyPair

  • muxer_opt – optional choice of stream muxer

  • sec_opt – optional choice of security upgrade

  • peerstore_opt – optional peerstore

  • disc_opt – optional discovery

  • muxer_preference – optional explicit muxer preference

  • listen_addrs – optional list of multiaddrs to listen on

  • enable_mDNS – whether to enable mDNS discovery

  • bootstrap – optional list of bootstrap peer addresses as strings

  • enable_quic – optinal choice to use QUIC for transport

  • enable_autotls – optinal choice to use AutoTLS for security

  • quic_transport_opt – optional configuration for quic transport

  • tls_client_config – optional TLS client configuration for WebSocket transport

  • tls_server_config – optional TLS server configuration for WebSocket transport

  • resource_manager (libp2p.rcmgr.ResourceManager or None) – optional resource manager for connection/stream limits

  • psk – optional pre-shared key (PSK)

  • bootstrap_allow_ipv6 – if True, bootstrap accepts IPv6+TCP addresses

  • bootstrap_dns_timeout – DNS resolution timeout in seconds per attempt

  • bootstrap_dns_max_retries – max DNS resolution retries with backoff

  • connection_config – optional connection configuration for connection manager

  • announce_addrs – if set, these replace listen addrs in get_addrs()

Returns:

return a host instance

libp2p.new_swarm(key_pair: KeyPair | None = None, muxer_opt: TMuxerOptions | None = None, sec_opt: TSecurityOptions | None = None, peerstore_opt: IPeerStore | None = None, muxer_preference: Literal['YAMUX', 'MPLEX'] | None = None, listen_addrs: Sequence[multiaddr.Multiaddr] | None = None, enable_quic: bool = False, enable_autotls: bool = False, retry_config: RetryConfig | None = None, connection_config: ConnectionConfig | QUICTransportConfig | None = None, tls_client_config: ssl.SSLContext | None = None, tls_server_config: ssl.SSLContext | None = None, resource_manager: ResourceManager | None = None, psk: str | None = None) INetworkService
libp2p.save_keypair(key_pair: KeyPair, type: str = 'ed25519') None

Persist a private key to disk in PEM format.

Currently supports only Ed25519 keys. Writes the key to a predefined path for later retrieval.

Parameters:
  • key_pair – KeyPair object containing private and public keys.

  • type – Type of key to save (default: “ed25519”).

Raises:

ValueError – if an unsupported key type is provided.

libp2p.set_default_muxer(muxer_name: Literal['YAMUX', 'MPLEX']) None

Set the default multiplexer protocol to use.

Parameters:

muxer_name – Either “YAMUX” or “MPLEX”

Raises:

ValueError – If an unsupported muxer name is provided