py-libp2p
The Python implementation of the libp2p networking stack
Contents
Introduction
py-libp2p is the Python implementation of the libp2p networking stack. It hopes to someday be fully compatible with other implementations of libp2p.
This project is still in its early stages, and is not yet ready for production use.
Further Reading
Quickstart
TODO - add quickstart instructions
Release Notes
libp2p v0.1.5 (2020-03-25)
Features
Dial all multiaddrs stored for a peer when attempting to connect (not just the first one in the peer store). (#386)
Migrate transport stack to trio-compatible code. Merge in #404. (#396)
Migrate network stack to trio-compatible code. Merge in #404. (#397)
Migrate host, peer and protocols stacks to trio-compatible code. Merge in #404. (#398)
Migrate muxer and security transport stacks to trio-compatible code. Merge in #404. (#399)
Migrate pubsub stack to trio-compatible code. Merge in #404. (#400)
Fix interop tests w/ new trio-style code. Merge in #404. (#401)
Fix remainder of test code w/ new trio-style code. Merge in #404. (#402)
Add initial infrastructure for noise security transport. (#405)
Add PatternXX of noise security transport. (#406)
The msg_id in a pubsub message is now configurable by the user of the library. (#410)
Bugfixes
Internal Changes - for py-libp2p Contributors
Add support for fastecdsa on windows (and thereby supporting windows installation via pip) (#380)
Prefer f-string style formatting everywhere except logging statements. (#389)
Mark lru dependency as third-party to fix a windows inconsistency. (#392)
Bump multiaddr dependency to version 0.0.9 so that multiaddr objects are hashable. (#393)
Remove incremental mode of mypy to disable some warnings. (#403)
libp2p v0.1.4 (2019-12-12)
Features
Internal Changes - for py-libp2p Contributors
Refactor and cleanup gossipsub (#373)
libp2p v0.1.3 (2019-11-27)
Bugfixes
Handle Stream* errors (like
StreamClosed
) during calls tostream.write()
andstream.read()
(#350)Relax the protobuf dependency to play nicely with other libraries. It was pinned to 3.9.0, and now permits v3.10 up to (but not including) v4. (#354)
Fixes KeyError when peer in a stream accidentally closes and resets the stream, because handlers for both will try to
del streams[stream_id]
without checking if the entry still exists. (#355)
Improved Documentation
Use Sphinx & autodoc to generate docs, now available on py-libp2p.readthedocs.io (#318)
Internal Changes - for py-libp2p Contributors
Miscellaneous changes
v0.1.2
Welcome to the great beyond, where changes were not tracked by release…
examples package
Subpackages
examples.chat package
Submodules
examples.chat.chat module
- async examples.chat.chat.read_data(stream: INetStream) None
- async examples.chat.chat.write_data(stream: INetStream) None
Module contents
Module contents
libp2p package
Subpackages
libp2p.crypto package
Subpackages
Submodules
libp2p.crypto.authenticated_encryption module
- class libp2p.crypto.authenticated_encryption.EncryptionParameters(cipher_type: str, hash_type: str, iv: bytes, mac_key: bytes, cipher_key: bytes)
Bases:
object
- class libp2p.crypto.authenticated_encryption.MacAndCipher(parameters: EncryptionParameters)
Bases:
object
- libp2p.crypto.authenticated_encryption.initialize_pair(cipher_type: str, hash_type: str, secret: bytes) Tuple[EncryptionParameters, EncryptionParameters]
Return a pair of
Keys
for use in securing a communications channel with authenticated encryption derived from thesecret
and using the requestedcipher_type
andhash_type
.
libp2p.crypto.ecc module
- class libp2p.crypto.ecc.ECCPrivateKey(impl: int, curve: <MagicMock name='mock.curve.Curve' id='140201204687776'>)
Bases:
PrivateKey
- classmethod new(curve: str) ECCPrivateKey
- class libp2p.crypto.ecc.ECCPublicKey(impl: <MagicMock name='mock.point.Point' id='140201204699920'>, curve: <MagicMock name='mock.curve.Curve' id='140201204687776'>)
Bases:
PublicKey
- classmethod from_bytes(data: bytes, curve: str) ECCPublicKey
libp2p.crypto.ed25519 module
- class libp2p.crypto.ed25519.Ed25519PrivateKey(impl: PrivateKey)
Bases:
PrivateKey
- classmethod from_bytes(data: bytes) Ed25519PrivateKey
- classmethod new(seed: bytes | None = None) Ed25519PrivateKey
- class libp2p.crypto.ed25519.Ed25519PublicKey(impl: PublicKey)
Bases:
PublicKey
- classmethod from_bytes(key_bytes: bytes) Ed25519PublicKey
libp2p.crypto.exceptions module
- exception libp2p.crypto.exceptions.CryptographyError
Bases:
BaseLibp2pError
- exception libp2p.crypto.exceptions.MissingDeserializerError
Bases:
CryptographyError
Raise if the requested deserialization routine is missing for some type of cryptographic key.
libp2p.crypto.key_exchange module
libp2p.crypto.keys module
- class libp2p.crypto.keys.KeyPair(private_key: libp2p.crypto.keys.PrivateKey, public_key: libp2p.crypto.keys.PublicKey)
Bases:
object
- private_key: PrivateKey
- class libp2p.crypto.keys.KeyType(value)
Bases:
Enum
An enumeration.
- ECC_P256 = 4
- ECDSA = 3
- Ed25519 = 1
- RSA = 0
- Secp256k1 = 2
- class libp2p.crypto.keys.PrivateKey
Bases:
Key
A
PrivateKey
represents a cryptographic private key.- classmethod deserialize_from_protobuf(protobuf_data: bytes) PrivateKey
libp2p.crypto.rsa module
- class libp2p.crypto.rsa.RSAPrivateKey(impl: RsaKey)
Bases:
PrivateKey
- classmethod new(bits: int = 2048, e: int = 65537) RSAPrivateKey
- class libp2p.crypto.rsa.RSAPublicKey(impl: RsaKey)
Bases:
PublicKey
- classmethod from_bytes(key_bytes: bytes) RSAPublicKey
libp2p.crypto.secp256k1 module
- class libp2p.crypto.secp256k1.Secp256k1PrivateKey(impl: PrivateKey)
Bases:
PrivateKey
- classmethod deserialize(data: bytes) Secp256k1PrivateKey
- classmethod from_bytes(data: bytes) Secp256k1PrivateKey
- classmethod new(secret: bytes | None = None) Secp256k1PrivateKey
- class libp2p.crypto.secp256k1.Secp256k1PublicKey(impl: PublicKey)
Bases:
PublicKey
- classmethod deserialize(data: bytes) Secp256k1PublicKey
- classmethod from_bytes(data: bytes) Secp256k1PublicKey
libp2p.crypto.serialization module
- libp2p.crypto.serialization.deserialize_private_key(data: bytes) PrivateKey
Module contents
libp2p.host package
Submodules
libp2p.host.basic_host module
- class libp2p.host.basic_host.BasicHost(network: INetworkService, default_protocols: OrderedDict[TProtocol, StreamHandlerFn] = None)
Bases:
IHost
BasicHost is a wrapper of a INetwork implementation.
It performs protocol negotiation on a stream with multistream-select right after a stream is initialized.
- async connect(peer_info: PeerInfo) None
Ensure there is a connection between this host and the peer with given peer_info.peer_id. connect will absorb the addresses in peer_info into its internal peerstore. If there is not an active connection, connect will issue a dial, and block until a connection is opened, or an error is returned.
- Parameters:
peer_info (peer.peerinfo.PeerInfo) – peer_info of the peer we want to connect to
- get_mux() Multiselect
- Returns:
mux instance of host
- get_network() INetworkService
- Returns:
network instance of host
- get_peerstore() IPeerStore
- Returns:
peerstore of the host (same one as in its network instance)
- get_private_key() PrivateKey
- Returns:
the private key belonging to the peer
- multiselect: Multiselect
- multiselect_client: MultiselectClient
- async new_stream(peer_id: ID, protocol_ids: Sequence[TProtocol]) INetStream
- Parameters:
peer_id – peer_id that host is connecting
protocol_ids – available protocol ids to use for stream
- Returns:
stream: new stream created
- peerstore: IPeerStore
- run(listen_addrs: Sequence[Multiaddr]) AsyncIterator[None]
Run the host instance and listen to
listen_addrs
.- Parameters:
listen_addrs – a sequence of multiaddrs that we want to listen to
libp2p.host.defaults module
libp2p.host.exceptions module
- exception libp2p.host.exceptions.ConnectionFailure
Bases:
HostException
- exception libp2p.host.exceptions.HostException
Bases:
BaseLibp2pError
A generic exception in IHost.
- exception libp2p.host.exceptions.StreamFailure
Bases:
HostException
libp2p.host.host_interface module
- class libp2p.host.host_interface.IHost
Bases:
ABC
- abstract async connect(peer_info: PeerInfo) None
Ensure there is a connection between this host and the peer with given peer_info.peer_id. connect will absorb the addresses in peer_info into its internal peerstore. If there is not an active connection, connect will issue a dial, and block until a connection is opened, or an error is returned.
- Parameters:
peer_info (peer.peerinfo.PeerInfo) – peer_info of the peer we want to connect to
- abstract get_addrs() List[Multiaddr]
- Returns:
all the multiaddr addresses this host is listening to
- abstract get_network() INetworkService
- Returns:
network instance of host
- abstract get_private_key() PrivateKey
- Returns:
the private key belonging to the peer
- abstract async new_stream(peer_id: ID, protocol_ids: Sequence[TProtocol]) INetStream
- Parameters:
peer_id – peer_id that host is connecting
protocol_ids – available protocol ids to use for stream
- Returns:
stream: new stream created
libp2p.host.ping module
- async libp2p.host.ping.handle_ping(stream: INetStream) None
Respond to incoming ping requests until one side errors or closes the
stream
.
libp2p.host.routed_host module
- class libp2p.host.routed_host.RoutedHost(network: INetworkService, router: IPeerRouting)
Bases:
BasicHost
- async connect(peer_info: PeerInfo) None
Ensure there is a connection between this host and the peer with given peer_info.peer_id. See (basic_host).connect for more information.
RoutedHost’s Connect differs in that if the host has no addresses for a given peer, it will use its routing system to try to find some.
- Parameters:
peer_info (peer.peerinfo.PeerInfo) – peer_info of the peer we want to connect to
Module contents
libp2p.identity package
Subpackages
Module contents
libp2p.io package
Submodules
libp2p.io.abc module
- class libp2p.io.abc.EncryptedMsgReadWriter
Bases:
MsgReadWriteCloser
,Encrypter
Read/write message with encryption/decryption.
libp2p.io.exceptions module
- exception libp2p.io.exceptions.DecryptionFailedException
Bases:
MsgioException
- exception libp2p.io.exceptions.IOException
Bases:
BaseLibp2pError
- exception libp2p.io.exceptions.IncompleteReadError
Bases:
IOException
Fewer bytes were read than requested.
- exception libp2p.io.exceptions.MessageTooLarge
Bases:
MsgioException
- exception libp2p.io.exceptions.MissingLengthException
Bases:
MsgioException
- exception libp2p.io.exceptions.MissingMessageException
Bases:
MsgioException
- exception libp2p.io.exceptions.MsgioException
Bases:
IOException
libp2p.io.msgio module
msgio
is an implementation of https://github.com/libp2p/go-msgio.
from that repo: “a simple package to r/w length-delimited slices.”
NOTE: currently missing the capability to indicate lengths by “varint” method.
- class libp2p.io.msgio.BaseMsgReadWriter(read_write_closer: ReadWriteCloser)
Bases:
MsgReadWriteCloser
- read_write_closer: ReadWriteCloser
- class libp2p.io.msgio.FixedSizeLenMsgReadWriter(read_write_closer: ReadWriteCloser)
Bases:
BaseMsgReadWriter
- class libp2p.io.msgio.VarIntLengthMsgReadWriter(read_write_closer: ReadWriteCloser)
Bases:
BaseMsgReadWriter
libp2p.io.trio module
libp2p.io.utils module
Module contents
libp2p.network package
Subpackages
libp2p.network.connection package
Submodules
libp2p.network.connection.exceptions module
- exception libp2p.network.connection.exceptions.RawConnError
Bases:
IOException
libp2p.network.connection.net_connection_interface module
- class libp2p.network.connection.net_connection_interface.INetConn
Bases:
Closer
- event_started: Event
- abstract get_streams() Tuple[INetStream, ...]
- muxed_conn: IMuxedConn
- abstract async new_stream() INetStream
libp2p.network.connection.raw_connection module
- class libp2p.network.connection.raw_connection.RawConnection(stream: ReadWriteCloser, initiator: bool)
Bases:
IRawConnection
- async read(n: int | None = None) bytes
Read up to
n
bytes from the underlying stream. This call is delegated directly to the underlyingself.reader
.Raise RawConnError if the underlying connection breaks
- stream: ReadWriteCloser
libp2p.network.connection.raw_connection_interface module
- class libp2p.network.connection.raw_connection_interface.IRawConnection
Bases:
ReadWriteCloser
A Raw Connection provides a Reader and a Writer.
libp2p.network.connection.swarm_connection module
- class libp2p.network.connection.swarm_connection.SwarmConn(muxed_conn: IMuxedConn, swarm: Swarm)
Bases:
INetConn
- event_closed: Event
- muxed_conn: IMuxedConn
Module contents
libp2p.network.stream package
Submodules
libp2p.network.stream.exceptions module
- exception libp2p.network.stream.exceptions.StreamClosed
Bases:
StreamError
- exception libp2p.network.stream.exceptions.StreamEOF
Bases:
StreamError
,EOFError
- exception libp2p.network.stream.exceptions.StreamError
Bases:
IOException
- exception libp2p.network.stream.exceptions.StreamReset
Bases:
StreamError
libp2p.network.stream.net_stream module
- class libp2p.network.stream.net_stream.NetStream(muxed_stream: IMuxedStream)
Bases:
INetStream
- get_protocol() TProtocol
- Returns:
protocol id that stream runs on
- muxed_stream: IMuxedStream
- async read(n: int | None = None) bytes
Read from stream.
- Parameters:
n – number of bytes to read
- Returns:
bytes of input
libp2p.network.stream.net_stream_interface module
- class libp2p.network.stream.net_stream_interface.INetStream
Bases:
ReadWriteCloser
- abstract get_protocol() TProtocol
- Returns:
protocol id that stream runs on
- muxed_conn: IMuxedConn
Module contents
Submodules
libp2p.network.exceptions module
- exception libp2p.network.exceptions.SwarmException
Bases:
BaseLibp2pError
libp2p.network.network_interface module
- class libp2p.network.network_interface.INetwork
Bases:
ABC
- abstract async dial_peer(peer_id: ID) INetConn
dial_peer try to create a connection to peer_id.
- Parameters:
peer_id – peer if we want to dial
- Raises:
SwarmException – raised when an error occurs
- Returns:
muxed connection
- abstract async listen(*multiaddrs: Sequence[Multiaddr]) bool
- Parameters:
multiaddrs – one or many multiaddrs to start listening on
- Returns:
True if at least one success
- abstract async new_stream(peer_id: ID) INetStream
- Parameters:
peer_id – peer_id of destination
protocol_ids – available protocol ids to use for stream
- Returns:
net stream instance
- peerstore: IPeerStore
libp2p.network.notifee_interface module
- class libp2p.network.notifee_interface.INotifee
Bases:
ABC
- abstract async closed_stream(network: INetwork, stream: INetStream) None
- Parameters:
network – network the stream was closed on
stream – stream that was closed
- abstract async connected(network: INetwork, conn: INetConn) None
- Parameters:
network – network the connection was opened on
conn – connection that was opened
- abstract async disconnected(network: INetwork, conn: INetConn) None
- Parameters:
network – network the connection was closed on
conn – connection that was closed
- abstract async listen(network: INetwork, multiaddr: Multiaddr) None
- Parameters:
network – network the listener is listening on
multiaddr – multiaddress listener is listening on
- abstract async listen_close(network: INetwork, multiaddr: Multiaddr) None
- Parameters:
network – network the connection was opened on
multiaddr – multiaddress listener is no longer listening on
- abstract async opened_stream(network: INetwork, stream: INetStream) None
- Parameters:
network – network the stream was opened on
stream – stream that was opened
libp2p.network.swarm module
- class libp2p.network.swarm.Swarm(peer_id: ID, peerstore: IPeerStore, upgrader: TransportUpgrader, transport: ITransport)
Bases:
Service
,INetworkService
- async add_conn(muxed_conn: IMuxedConn) SwarmConn
Add a IMuxedConn to Swarm as a SwarmConn, notify “connected”, and start to monitor the connection for its new streams and disconnection.
- common_stream_handler: Callable[[INetStream], Awaitable[None]]
- async dial_addr(addr: Multiaddr, peer_id: ID) INetConn
Try to create a connection to peer_id with addr.
- Parameters:
addr – the address we want to connect with
peer_id – the peer we want to connect to
- Raises:
SwarmException – raised when an error occurs
- Returns:
network connection
- async dial_peer(peer_id: ID) INetConn
Try to create a connection to peer_id.
- Parameters:
peer_id – peer if we want to dial
- Raises:
SwarmException – raised when an error occurs
- Returns:
muxed connection
- event_listener_nursery_created: Event
- async listen(*multiaddrs: Multiaddr) bool
- Parameters:
multiaddrs – one or many multiaddrs to start listening on
- Returns:
true if at least one success
For each multiaddr
Check if a listener for multiaddr exists already
If listener already exists, continue
Otherwise:
Capture multiaddr in conn handler
Have conn handler delegate to stream handler
Call listener listen with the multiaddr
Map multiaddr to listener
- async new_stream(peer_id: ID) INetStream
- Parameters:
peer_id – peer_id of destination
- Raises:
SwarmException – raised when an error occurs
- Returns:
net stream instance
- async notify_closed_stream(stream: INetStream) None
- async notify_opened_stream(stream: INetStream) None
- peerstore: IPeerStore
- register_notifee(notifee: INotifee) None
- Parameters:
notifee – object implementing Notifee interface
- Returns:
true if notifee registered successfully, false otherwise
- remove_conn(swarm_conn: SwarmConn) None
Simply remove the connection from Swarm’s records, without closing the connection.
- async run() None
Primary entry point for all service logic.
Note
This method should not be directly invoked by user code.
Services may be run using the following approaches.
- set_stream_handler(stream_handler: Callable[[INetStream], Awaitable[None]]) None
Set the stream handler for all incoming streams.
- transport: ITransport
- upgrader: TransportUpgrader
- libp2p.network.swarm.create_default_stream_handler(network: INetworkService) Callable[[INetStream], Awaitable[None]]
Module contents
libp2p.peer package
Submodules
libp2p.peer.addrbook_interface module
- class libp2p.peer.addrbook_interface.IAddrBook
Bases:
ABC
- abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None
Calls add_addrs(peer_id, [addr], ttl)
- Parameters:
peer_id – the peer to add address for
addr – multiaddress of the peer
ttl – time-to-live for the address (after this time, address is no longer valid)
- abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None
Adds addresses for a given peer all with the same time-to-live. If one of the addresses already exists for the peer and has a longer TTL, no operation should take place. If one of the addresses exists with a shorter TTL, extend the TTL to equal param ttl.
- Parameters:
peer_id – the peer to add address for
addr – multiaddresses of the peer
ttl – time-to-live for the address (after this time, address is no longer valid
- abstract addrs(peer_id: ID) List[Multiaddr]
- Parameters:
peer_id – peer to get addresses of
- Returns:
all known (and valid) addresses for the given peer
libp2p.peer.id module
libp2p.peer.peerdata module
- class libp2p.peer.peerdata.PeerData
Bases:
IPeerData
- add_privkey(privkey: PrivateKey) None
- Parameters:
privkey –
- get_metadata(key: str) Any
- Parameters:
key – key in KV pair
- Returns:
val for key
- Raises:
PeerDataError – key not found
- get_privkey() PrivateKey
- Returns:
private key of the peer
- Raises:
PeerDataError – if private key not found
- get_pubkey() PublicKey
- Returns:
public key of the peer
- Raises:
PeerDataError – if public key not found
- privkey: PrivateKey
libp2p.peer.peerdata_interface module
- class libp2p.peer.peerdata_interface.IPeerData
Bases:
ABC
- abstract add_privkey(privkey: PrivateKey) None
- Parameters:
privkey –
- abstract get_metadata(key: str) IPeerMetadata
- Parameters:
key – key in KV pair
- Returns:
val for key
- Raises:
PeerDataError – key not found
- abstract get_privkey() PrivateKey
- Returns:
private key of the peer
- Raises:
PeerDataError – if private key not found
- abstract get_pubkey() PublicKey
- Returns:
public key of the peer
- Raises:
PeerDataError – if public key not found
libp2p.peer.peerinfo module
- exception libp2p.peer.peerinfo.InvalidAddrError
Bases:
ValueError
libp2p.peer.peermetadata_interface module
libp2p.peer.peerstore module
- class libp2p.peer.peerstore.PeerStore
Bases:
IPeerStore
- add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None
- Parameters:
peer_id – peer ID to add address for
addr –
ttl – time-to-live for the this record
- add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None
- Parameters:
peer_id – peer ID to add address for
addrs –
ttl – time-to-live for the this record
- add_key_pair(peer_id: ID, key_pair: KeyPair) None
- Parameters:
peer_id – peer ID to add private key for
key_pair –
- add_privkey(peer_id: ID, privkey: PrivateKey) None
- Parameters:
peer_id – peer ID to add private key for
privkey –
- Raises:
PeerStoreError – if peer ID or peer privkey not found
- add_protocols(peer_id: ID, protocols: Sequence[str]) None
- Parameters:
peer_id – peer ID to add protocols for
protocols – protocols to add
- add_pubkey(peer_id: ID, pubkey: PublicKey) None
- Parameters:
peer_id – peer ID to add public key for
pubkey –
- Raises:
PeerStoreError – if peer ID and pubkey does not match
- addrs(peer_id: ID) List[Multiaddr]
- Parameters:
peer_id – peer ID to get addrs for
- Returns:
list of addrs
- Raises:
PeerStoreError – if peer ID not found
- get(peer_id: ID, key: str) Any
- Parameters:
peer_id – peer ID to get peer data for
key – the key to search value for
- Returns:
value corresponding to the key
- Raises:
PeerStoreError – if peer ID or value not found
- get_protocols(peer_id: ID) List[str]
- Parameters:
peer_id – peer ID to get protocols for
- Returns:
protocols (as list of strings)
- Raises:
PeerStoreError – if peer ID not found
- peer_info(peer_id: ID) PeerInfo
- Parameters:
peer_id – peer ID to get info for
- Returns:
peer info object
- privkey(peer_id: ID) PrivateKey
- Parameters:
peer_id – peer ID to get private key for
- Returns:
private key of the peer
- Raises:
PeerStoreError – if peer ID or peer privkey not found
- pubkey(peer_id: ID) PublicKey
- Parameters:
peer_id – peer ID to get public key for
- Returns:
public key of the peer
- Raises:
PeerStoreError – if peer ID or peer pubkey not found
libp2p.peer.peerstore_interface module
- class libp2p.peer.peerstore_interface.IPeerStore
Bases:
IAddrBook
,IPeerMetadata
- abstract add_addr(peer_id: ID, addr: Multiaddr, ttl: int) None
- Parameters:
peer_id – peer ID to add address for
addr –
ttl – time-to-live for the this record
- abstract add_addrs(peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) None
- Parameters:
peer_id – peer ID to add address for
addrs –
ttl – time-to-live for the this record
- abstract add_key_pair(peer_id: ID, key_pair: KeyPair) None
- Parameters:
peer_id – peer ID to add private key for
key_pair –
- Raises:
PeerStoreError – if peer ID already has pubkey or privkey set
- abstract add_privkey(peer_id: ID, privkey: PrivateKey) None
- Parameters:
peer_id – peer ID to add private key for
privkey –
- Raises:
PeerStoreError – if peer ID already has privkey set
- abstract add_protocols(peer_id: ID, protocols: Sequence[str]) None
- Parameters:
peer_id – peer ID to add protocols for
protocols – protocols to add
- abstract add_pubkey(peer_id: ID, pubkey: PublicKey) None
- Parameters:
peer_id – peer ID to add public key for
pubkey –
- Raises:
PeerStoreError – if peer ID already has pubkey set
- abstract addrs(peer_id: ID) List[Multiaddr]
- Parameters:
peer_id – peer ID to get addrs for
- Returns:
list of addrs
- abstract get(peer_id: ID, key: str) Any
- Parameters:
peer_id – peer ID to get peer data for
key – the key to search value for
- Returns:
value corresponding to the key
- Raises:
PeerStoreError – if peer ID or value not found
- abstract get_protocols(peer_id: ID) List[str]
- Parameters:
peer_id – peer ID to get protocols for
- Returns:
protocols (as list of strings)
- Raises:
PeerStoreError – if peer ID not found
- abstract peer_info(peer_id: ID) PeerInfo
- Parameters:
peer_id – peer ID to get info for
- Returns:
peer info object
- abstract peers_with_addrs() List[ID]
- Returns:
all of the peer IDs which has addrs stored in peer store
- abstract privkey(peer_id: ID) PrivateKey
- Parameters:
peer_id – peer ID to get private key for
- Returns:
private key of the peer
- Raises:
PeerStoreError – if peer ID not found
- abstract pubkey(peer_id: ID) PublicKey
- Parameters:
peer_id – peer ID to get public key for
- Returns:
public key of the peer
- Raises:
PeerStoreError – if peer ID not found
Module contents
libp2p.protocol_muxer package
Submodules
libp2p.protocol_muxer.exceptions module
- exception libp2p.protocol_muxer.exceptions.MultiselectClientError
Bases:
BaseLibp2pError
Raised when an error occurs in protocol selection process.
- exception libp2p.protocol_muxer.exceptions.MultiselectCommunicatorError
Bases:
BaseLibp2pError
Raised when an error occurs during read/write via communicator.
- exception libp2p.protocol_muxer.exceptions.MultiselectError
Bases:
BaseLibp2pError
Raised when an error occurs in multiselect process.
libp2p.protocol_muxer.multiselect module
- class libp2p.protocol_muxer.multiselect.Multiselect(default_handlers: Dict[TProtocol, Callable[[INetStream], Awaitable[None]]] = None)
Bases:
IMultiselectMuxer
Multiselect module that is responsible for responding to a multiselect client and deciding on a specific protocol and handler pair to use for communication.
- add_handler(protocol: TProtocol, handler: Callable[[INetStream], Awaitable[None]]) None
Store the handler with the given protocol.
- Parameters:
protocol – protocol name
handler – handler function
- async handshake(communicator: IMultiselectCommunicator) None
Perform handshake to agree on multiselect protocol.
- Parameters:
communicator – communicator to use
- Raises:
MultiselectError – raised when handshake failed
- async negotiate(communicator: IMultiselectCommunicator) Tuple[TProtocol, Callable[[INetStream], Awaitable[None]]]
Negotiate performs protocol selection.
- Parameters:
stream – stream to negotiate on
- Returns:
selected protocol name, handler function
- Raises:
MultiselectError – raised when negotiation failed
libp2p.protocol_muxer.multiselect_client module
- class libp2p.protocol_muxer.multiselect_client.MultiselectClient
Bases:
IMultiselectClient
Client for communicating with receiver’s multiselect module in order to select a protocol id to communicate over.
- async handshake(communicator: IMultiselectCommunicator) None
Ensure that the client and multiselect are both using the same multiselect protocol.
- Parameters:
stream – stream to communicate with multiselect over
- Raises:
MultiselectClientError – raised when handshake failed
- async select_one_of(protocols: Sequence[TProtocol], communicator: IMultiselectCommunicator) TProtocol
For each protocol, send message to multiselect selecting protocol and fail if multiselect does not return same protocol. Returns first protocol that multiselect agrees on (i.e. that multiselect selects)
- Parameters:
protocol – protocol to select
stream – stream to communicate with multiselect over
- Returns:
selected protocol
- Raises:
MultiselectClientError – raised when protocol negotiation failed
- async try_select(communicator: IMultiselectCommunicator, protocol: TProtocol) TProtocol
Try to select the given protocol or raise exception if fails.
- Parameters:
communicator – communicator to use to communicate with counterparty
protocol – protocol to select
- Raises:
MultiselectClientError – raised when protocol negotiation failed
- Returns:
selected protocol
libp2p.protocol_muxer.multiselect_client_interface module
- class libp2p.protocol_muxer.multiselect_client_interface.IMultiselectClient
Bases:
ABC
Client for communicating with receiver’s multiselect module in order to select a protocol id to communicate over.
- abstract async handshake(communicator: IMultiselectCommunicator) None
Ensure that the client and multiselect are both using the same multiselect protocol.
- Parameters:
stream – stream to communicate with multiselect over
- Raises:
Exception – multiselect protocol ID mismatch
- abstract async select_one_of(protocols: Sequence[TProtocol], communicator: IMultiselectCommunicator) TProtocol
For each protocol, send message to multiselect selecting protocol and fail if multiselect does not return same protocol. Returns first protocol that multiselect agrees on (i.e. that multiselect selects)
- Parameters:
protocol – protocol to select
stream – stream to communicate with multiselect over
- Returns:
selected protocol
- abstract async try_select(communicator: IMultiselectCommunicator, protocol: TProtocol) TProtocol
Try to select the given protocol or raise exception if fails.
- Parameters:
communicator – communicator to use to communicate with counterparty
protocol – protocol to select
- Raises:
Exception – error in protocol selection
- Returns:
selected protocol
libp2p.protocol_muxer.multiselect_communicator module
- class libp2p.protocol_muxer.multiselect_communicator.MultiselectCommunicator(read_writer: ReadWriteCloser)
Bases:
IMultiselectCommunicator
- async read() str
- Raises:
MultiselectCommunicatorError – raised when failed to read from underlying reader
- read_writer: ReadWriteCloser
- async write(msg_str: str) None
- Raises:
MultiselectCommunicatorError – raised when failed to write to underlying reader
libp2p.protocol_muxer.multiselect_communicator_interface module
libp2p.protocol_muxer.multiselect_muxer_interface module
- class libp2p.protocol_muxer.multiselect_muxer_interface.IMultiselectMuxer
Bases:
ABC
Multiselect module that is responsible for responding to a multiselect client and deciding on a specific protocol and handler pair to use for communication.
- abstract add_handler(protocol: TProtocol, handler: Callable[[INetStream], Awaitable[None]]) None
Store the handler with the given protocol.
- Parameters:
protocol – protocol name
handler – handler function
- abstract async negotiate(communicator: IMultiselectCommunicator) Tuple[TProtocol, Callable[[INetStream], Awaitable[None]]]
Negotiate performs protocol selection.
- Parameters:
stream – stream to negotiate on
- Returns:
selected protocol name, handler function
- Raises:
Exception – negotiation failed exception
Module contents
libp2p.pubsub package
Subpackages
libp2p.pubsub.pb package
Submodules
libp2p.pubsub.pb.rpc_pb2 module
Generated protocol buffer code.
- class libp2p.pubsub.pb.rpc_pb2.ControlGraft
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.ControlIHave
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.ControlIWant
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.ControlMessage
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.ControlPrune
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.Message
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
- class libp2p.pubsub.pb.rpc_pb2.RPC
Bases:
Message
,Message
- DESCRIPTOR = <google._upb._message.Descriptor object>
Module contents
Submodules
libp2p.pubsub.abc module
- class libp2p.pubsub.abc.IPubsub
Bases:
ServiceAPI
- abstract set_topic_validator(topic: str, validator: Callable[[ID, Message], bool] | Callable[[ID, Message], Awaitable[bool]], is_async_validator: bool) None
- abstract async subscribe(topic_id: str) ISubscriptionAPI
- class libp2p.pubsub.abc.IPubsubRouter
Bases:
ABC
- abstract add_peer(peer_id: ID, protocol_id: TProtocol) None
Notifies the router that a new peer has been connected.
- Parameters:
peer_id – id of peer to add
- abstract attach(pubsub: Pubsub) None
Attach is invoked by the PubSub constructor to attach the router to a freshly initialized PubSub instance.
- Parameters:
pubsub – pubsub instance to attach to
- abstract async handle_rpc(rpc: RPC, sender_peer_id: ID) None
Invoked to process control messages in the RPC envelope. It is invoked after subscriptions and payload messages have been processed TODO: Check if this interface is ok. It’s not the exact same as the go code, but the go code is really confusing with the msg origin, they specify rpc.from even when the rpc shouldn’t have a from :param rpc: rpc message
- abstract async join(topic: str) None
Join notifies the router that we want to receive and forward messages in a topic. It is invoked after the subscription announcement.
- Parameters:
topic – topic to join
- abstract async leave(topic: str) None
Leave notifies the router that we are no longer interested in a topic. It is invoked after the unsubscription announcement.
- Parameters:
topic – topic to leave
- class libp2p.pubsub.abc.ISubscriptionAPI(*args, **kwds)
Bases:
AbstractAsyncContextManager
[ISubscriptionAPI
],AsyncIterable
[Message
]
libp2p.pubsub.exceptions module
- exception libp2p.pubsub.exceptions.NoPubsubAttached
Bases:
PubsubRouterError
- exception libp2p.pubsub.exceptions.PubsubRouterError
Bases:
BaseLibp2pError
libp2p.pubsub.floodsub module
- class libp2p.pubsub.floodsub.FloodSub(protocols: Sequence[TProtocol])
Bases:
IPubsubRouter
- add_peer(peer_id: ID, protocol_id: TProtocol) None
Notifies the router that a new peer has been connected.
- Parameters:
peer_id – id of peer to add
- attach(pubsub: Pubsub) None
Attach is invoked by the PubSub constructor to attach the router to a freshly initialized PubSub instance.
- Parameters:
pubsub – pubsub instance to attach to
- async handle_rpc(rpc: RPC, sender_peer_id: ID) None
Invoked to process control messages in the RPC envelope. It is invoked after subscriptions and payload messages have been processed.
- Parameters:
rpc – rpc message
- async join(topic: str) None
Join notifies the router that we want to receive and forward messages in a topic. It is invoked after the subscription announcement.
- Parameters:
topic – topic to join
- async leave(topic: str) None
Leave notifies the router that we are no longer interested in a topic. It is invoked after the unsubscription announcement.
- Parameters:
topic – topic to leave
- async publish(msg_forwarder: ID, pubsub_msg: Message) None
Invoked to forward a new message that has been validated. This is where the “flooding” part of floodsub happens.
With flooding, routing is almost trivial: for each incoming message, forward to all known peers in the topic. There is a bit of logic, as the router maintains a timed cache of previous messages, so that seen messages are not further forwarded. It also never forwards a message back to the source or the peer that forwarded the message. :param msg_forwarder: peer ID of the peer who forwards the message to us :param pubsub_msg: pubsub message in protobuf.
libp2p.pubsub.gossipsub module
- class libp2p.pubsub.gossipsub.GossipSub(protocols: Sequence[TProtocol], degree: int, degree_low: int, degree_high: int, time_to_live: int, gossip_window: int = 3, gossip_history: int = 5, heartbeat_initial_delay: float = 0.1, heartbeat_interval: int = 120)
Bases:
IPubsubRouter
,Service
- add_peer(peer_id: ID, protocol_id: TProtocol) None
Notifies the router that a new peer has been connected.
- Parameters:
peer_id – id of peer to add
protocol_id – router protocol the peer speaks, e.g., floodsub, gossipsub
- attach(pubsub: Pubsub) None
Attach is invoked by the PubSub constructor to attach the router to a freshly initialized PubSub instance.
- Parameters:
pubsub – pubsub instance to attach to
- async emit_control_message(control_msg: ControlMessage, to_peer: ID) None
- async emit_ihave(topic: str, msg_ids: Any, to_peer: ID) None
Emit ihave message, sent to to_peer, for topic and msg_ids.
- async emit_iwant(msg_ids: Any, to_peer: ID) None
Emit iwant message, sent to to_peer, for msg_ids.
- async handle_graft(graft_msg: ControlGraft, sender_peer_id: ID) None
- async handle_ihave(ihave_msg: ControlIHave, sender_peer_id: ID) None
Checks the seen set and requests unknown messages with an IWANT message.
- async handle_iwant(iwant_msg: ControlIWant, sender_peer_id: ID) None
Forwards all request messages that are present in mcache to the requesting peer.
- async handle_prune(prune_msg: ControlPrune, sender_peer_id: ID) None
- async handle_rpc(rpc: RPC, sender_peer_id: ID) None
Invoked to process control messages in the RPC envelope. It is invoked after subscriptions and payload messages have been processed.
- Parameters:
rpc – RPC message
sender_peer_id – id of the peer who sent the message
- async heartbeat() None
Call individual heartbeats.
Note: the heartbeats are called with awaits because each heartbeat depends on the state changes in the preceding heartbeat
- async join(topic: str) None
Join notifies the router that we want to receive and forward messages in a topic. It is invoked after the subscription announcement.
- Parameters:
topic – topic to join
- async leave(topic: str) None
Leave notifies the router that we are no longer interested in a topic. It is invoked after the unsubscription announcement.
- Parameters:
topic – topic to leave
- mcache: MessageCache
- mesh_heartbeat() Tuple[DefaultDict[ID, List[str]], DefaultDict[ID, List[str]]]
- pack_control_msgs(ihave_msgs: List[ControlIHave], graft_msgs: List[ControlGraft], prune_msgs: List[ControlPrune]) ControlMessage
- async publish(msg_forwarder: ID, pubsub_msg: Message) None
Invoked to forward a new message that has been validated.
- remove_peer(peer_id: ID) None
Notifies the router that a peer has been disconnected.
- Parameters:
peer_id – id of peer to remove
- async run() None
Primary entry point for all service logic.
Note
This method should not be directly invoked by user code.
Services may be run using the following approaches.
- static select_from_minus(num_to_select: int, pool: Iterable[Any], minus: Iterable[Any]) List[Any]
Select at most num_to_select subset of elements from the set (pool - minus) randomly. :param num_to_select: number of elements to randomly select :param pool: list of items to select from (excluding elements in minus) :param minus: elements to be excluded from selection pool :return: list of selected elements
libp2p.pubsub.mcache module
- class libp2p.pubsub.mcache.CacheEntry(mid: Tuple[bytes, bytes], topics: Sequence[str])
Bases:
object
- class libp2p.pubsub.mcache.MessageCache(window_size: int, history_size: int)
Bases:
object
- get(mid: Tuple[bytes, bytes]) Message | None
Get a message from the mcache.
- Parameters:
mid – (seqno, from_id) of the message to get.
- Returns:
The rpc message associated with this mid
- history: List[List[CacheEntry]]
- put(msg: Message) None
Put a message into the mcache.
- Parameters:
msg – The rpc message to put in. Should contain seqno and from_id
libp2p.pubsub.pubsub module
- class libp2p.pubsub.pubsub.Pubsub(host: ~libp2p.host.host_interface.IHost, router: IPubsubRouter, cache_size: int = None, strict_signing: bool = True, msg_id_constructor: ~typing.Callable[[~libp2p.pubsub.pb.rpc_pb2.Message], bytes] = <function get_peer_and_seqno_msg_id>)
Bases:
Service
,IPubsub
- async continuously_read_stream(stream: INetStream) None
Read from input stream in an infinite loop. Process messages from other nodes.
- Parameters:
stream – stream to continously read from
- event_handle_dead_peer_queue_started: Event
- event_handle_peer_queue_started: Event
- get_hello_packet() RPC
Generate subscription message with all topics we are subscribed to only send hello packet if we have subscribed topics.
- get_msg_validators(msg: Message) Tuple[TopicValidator, ...]
Get all validators corresponding to the topics in the message.
- Parameters:
msg – the message published to the topic
- async handle_dead_peer_queue() None
Continuously read from dead peer channel and close the stream between that peer and remove peer info from pubsub and pubsub router.
- async handle_peer_queue() None
Continuously read from peer queue and each time a new peer is found, open a stream to the peer using a supported pubsub protocol pubsub protocols we support.
- handle_subscription(origin_id: ID, sub_message: SubOpts) None
Handle an incoming subscription message from a peer. Update internal mapping to mark the peer as subscribed or unsubscribed to topics as defined in the subscription message.
- Parameters:
origin_id – id of the peer who subscribe to the message
sub_message – RPC.SubOpts
- async message_all_peers(raw_msg: bytes) None
Broadcast a message to peers.
- Parameters:
raw_msg – raw contents of the message to broadcast
- notify_subscriptions(publish_message: Message) None
Put incoming message from a peer onto my blocking queue.
- Parameters:
publish_message – RPC.Message format
- peers: Dict[ID, INetStream]
- async publish(topic_id: str, data: bytes) None
Publish data to a topic.
- Parameters:
topic_id – topic which we are going to publish the data to
data – data which we are publishing
- async push_msg(msg_forwarder: ID, msg: Message) None
Push a pubsub message to others.
- Parameters:
msg_forwarder – the peer who forward us the message.
msg – the message we are going to push out.
- remove_topic_validator(topic: str) None
Remove the validator from the given topic.
- Parameters:
topic – the topic to remove validator from
- router: IPubsubRouter
- async run() None
Primary entry point for all service logic.
Note
This method should not be directly invoked by user code.
Services may be run using the following approaches.
- seen_messages: LRU
- set_topic_validator(topic: str, validator: Callable[[ID, Message], bool] | Callable[[ID, Message], Awaitable[bool]], is_async_validator: bool) None
Register a validator under the given topic. One topic can only have one validtor.
- Parameters:
topic – the topic to register validator under
validator – the validator used to validate messages published to the topic
is_async_validator – indicate if the validator is an asynchronous validator
- sign_key: PrivateKey
- async stream_handler(stream: INetStream) None
Stream handler for pubsub. Gets invoked whenever a new stream is created on one of the supported pubsub protocols.
- Parameters:
stream – newly created stream
- async subscribe(topic_id: str) ISubscriptionAPI
Subscribe ourself to a topic.
- Parameters:
topic_id – topic_id to subscribe to
- subscribed_topics_receive: Dict[str, TrioSubscriptionAPI]
- subscribed_topics_send: Dict[str, trio.MemorySendChannel[rpc_pb2.Message]]
- topic_validators: Dict[str, TopicValidator]
- async unsubscribe(topic_id: str) None
Unsubscribe ourself from a topic.
- Parameters:
topic_id – topic_id to unsubscribe from
libp2p.pubsub.pubsub_notifee module
- class libp2p.pubsub.pubsub_notifee.PubsubNotifee(initiator_peers_queue: trio.MemorySendChannel[ID], dead_peers_queue: trio.MemorySendChannel[ID])
Bases:
INotifee
- async closed_stream(network: INetwork, stream: INetStream) None
- Parameters:
network – network the stream was closed on
stream – stream that was closed
- async connected(network: INetwork, conn: INetConn) None
Add peer_id to initiator_peers_queue, so that this peer_id can be used to create a stream and we only want to have one pubsub stream with each peer.
- Parameters:
network – network the connection was opened on
conn – connection that was opened
- async disconnected(network: INetwork, conn: INetConn) None
Add peer_id to dead_peers_queue, so that pubsub and its router can remove this peer_id and close the stream inbetween.
- Parameters:
network – network the connection was opened on
conn – connection that was opened
- async listen(network: INetwork, multiaddr: Multiaddr) None
- Parameters:
network – network the listener is listening on
multiaddr – multiaddress listener is listening on
- async listen_close(network: INetwork, multiaddr: Multiaddr) None
- Parameters:
network – network the connection was opened on
multiaddr – multiaddress listener is no longer listening on
- async opened_stream(network: INetwork, stream: INetStream) None
- Parameters:
network – network the stream was opened on
stream – stream that was opened
libp2p.pubsub.subscription module
- class libp2p.pubsub.subscription.BaseSubscriptionAPI(*args, **kwds)
Bases:
ISubscriptionAPI
- class libp2p.pubsub.subscription.TrioSubscriptionAPI(receive_channel: trio.MemoryReceiveChannel[rpc_pb2.Message], unsubscribe_fn: Callable[[], Awaitable[None]])
Bases:
BaseSubscriptionAPI
- receive_channel: trio.MemoryReceiveChannel[rpc_pb2.Message]
libp2p.pubsub.typing module
libp2p.pubsub.validators module
Module contents
libp2p.routing package
Submodules
libp2p.routing.interfaces module
Module contents
libp2p.security package
Subpackages
libp2p.security.insecure package
Subpackages
Submodules
libp2p.security.insecure.transport module
- class libp2p.security.insecure.transport.InsecureSession(*, local_peer: ID, local_private_key: PrivateKey, remote_peer: ID, remote_permanent_pubkey: PublicKey, is_initiator: bool, conn: ReadWriteCloser)
Bases:
BaseSession
- local_private_key: PrivateKey
- class libp2p.security.insecure.transport.InsecureTransport(local_key_pair: ~libp2p.crypto.keys.KeyPair, secure_bytes_provider: ~typing.Callable[[int], bytes] = <function default_secure_bytes_provider>)
Bases:
BaseSecureTransport
Provides the “identity” upgrader for a
IRawConnection
, i.e. the upgraded transport does not add any additional security.- async secure_inbound(conn: IRawConnection) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are not the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- class libp2p.security.insecure.transport.PlaintextHandshakeReadWriter(read_write_closer: ReadWriteCloser)
Bases:
VarIntLengthMsgReadWriter
- read_write_closer: ReadWriteCloser
- async libp2p.security.insecure.transport.run_handshake(local_peer: ID, local_private_key: PrivateKey, conn: IRawConnection, is_initiator: bool, remote_peer_id: ID) ISecureConn
Raise HandshakeFailure when handshake failed.
Module contents
libp2p.security.noise package
Subpackages
Submodules
libp2p.security.noise.exceptions module
- exception libp2p.security.noise.exceptions.HandshakeHasNotFinished
Bases:
NoiseFailure
- exception libp2p.security.noise.exceptions.InvalidSignature
Bases:
NoiseFailure
- exception libp2p.security.noise.exceptions.NoiseFailure
Bases:
HandshakeFailure
- exception libp2p.security.noise.exceptions.NoiseStateError
Bases:
NoiseFailure
Raised when anything goes wrong in the noise state in noiseprotocol package.
- exception libp2p.security.noise.exceptions.PeerIDMismatchesPubkey
Bases:
NoiseFailure
libp2p.security.noise.io module
- class libp2p.security.noise.io.BaseNoiseMsgReadWriter(conn: IRawConnection, noise_state: NoiseConnection)
Bases:
EncryptedMsgReadWriter
The base implementation of noise message reader/writer.
encrypt and decrypt are not implemented here, which should be implemented by the subclasses.
- noise_state: NoiseConnection
- prefix: bytes = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- read_writer: MsgReadWriteCloser
- class libp2p.security.noise.io.NoiseHandshakeReadWriter(conn: IRawConnection, noise_state: NoiseConnection)
Bases:
BaseNoiseMsgReadWriter
- noise_state: NoiseConnection
- read_writer: MsgReadWriteCloser
- class libp2p.security.noise.io.NoisePacketReadWriter(read_write_closer: ReadWriteCloser)
Bases:
FixedSizeLenMsgReadWriter
- read_write_closer: ReadWriteCloser
- class libp2p.security.noise.io.NoiseTransportReadWriter(conn: IRawConnection, noise_state: NoiseConnection)
Bases:
BaseNoiseMsgReadWriter
- noise_state: NoiseConnection
- read_writer: MsgReadWriteCloser
libp2p.security.noise.messages module
- class libp2p.security.noise.messages.NoiseHandshakePayload(id_pubkey: libp2p.crypto.keys.PublicKey, id_sig: bytes, early_data: bytes = None)
Bases:
object
- classmethod deserialize(protobuf_bytes: bytes) NoiseHandshakePayload
- libp2p.security.noise.messages.make_handshake_payload_sig(id_privkey: PrivateKey, noise_static_pubkey: PublicKey) bytes
- libp2p.security.noise.messages.verify_handshake_payload_sig(payload: NoiseHandshakePayload, noise_static_pubkey: PublicKey) bool
- Verify if the signature
is composed of the data SIGNED_DATA_PREFIX`++`noise_static_pubkey and
signed by the private key corresponding to id_pubkey
libp2p.security.noise.patterns module
- class libp2p.security.noise.patterns.BasePattern
Bases:
IPattern
- create_noise_state() NoiseConnection
- libp2p_privkey: PrivateKey
- make_handshake_payload() NoiseHandshakePayload
- noise_static_key: PrivateKey
- class libp2p.security.noise.patterns.IPattern
Bases:
ABC
- abstract async handshake_inbound(conn: IRawConnection) ISecureConn
- abstract async handshake_outbound(conn: IRawConnection, remote_peer: ID) ISecureConn
- class libp2p.security.noise.patterns.PatternXX(local_peer: ID, libp2p_privkey: PrivateKey, noise_static_key: PrivateKey, early_data: bytes | None = None)
Bases:
BasePattern
- async handshake_inbound(conn: IRawConnection) ISecureConn
- async handshake_outbound(conn: IRawConnection, remote_peer: ID) ISecureConn
- libp2p_privkey: PrivateKey
- noise_static_key: PrivateKey
libp2p.security.noise.transport module
- class libp2p.security.noise.transport.Transport(libp2p_keypair: KeyPair, noise_privkey: PrivateKey | None = None, early_data: bytes | None = None, with_noise_pipes: bool = False)
Bases:
ISecureTransport
- libp2p_privkey: PrivateKey
- noise_privkey: PrivateKey
- async secure_inbound(conn: IRawConnection) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are not the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
Module contents
libp2p.security.secio package
Subpackages
Submodules
libp2p.security.secio.exceptions module
- exception libp2p.security.secio.exceptions.IncompatibleChoices
Bases:
SecioException
- exception libp2p.security.secio.exceptions.InconsistentNonce
Bases:
SecioException
- exception libp2p.security.secio.exceptions.InvalidSignatureOnExchange
Bases:
SecioException
- exception libp2p.security.secio.exceptions.PeerMismatchException
Bases:
SecioException
- exception libp2p.security.secio.exceptions.SecioException
Bases:
HandshakeFailure
- exception libp2p.security.secio.exceptions.SedesException
Bases:
SecioException
- exception libp2p.security.secio.exceptions.SelfEncryption
Bases:
SecioException
Raised to indicate that a host is attempting to encrypt communications with itself.
libp2p.security.secio.transport module
- class libp2p.security.secio.transport.Proposal(nonce: bytes, public_key: PublicKey, exchanges: str = 'P-256', ciphers: str = 'AES-128', hashes: str = 'SHA256')
Bases:
object
Represents the set of session parameters one peer in a pair of peers attempting to negotiate a secio channel prefers.
- class libp2p.security.secio.transport.SecioMsgReadWriter(local_encryption_parameters: EncryptionParameters, remote_encryption_parameters: EncryptionParameters, read_writer: SecioPacketReadWriter)
Bases:
EncryptedMsgReadWriter
- read_writer: SecioPacketReadWriter
- class libp2p.security.secio.transport.SecioPacketReadWriter(read_write_closer: ReadWriteCloser)
Bases:
FixedSizeLenMsgReadWriter
- read_write_closer: ReadWriteCloser
- class libp2p.security.secio.transport.SessionParameters
Bases:
object
- local_encryption_parameters: EncryptionParameters
- remote_encryption_parameters: EncryptionParameters
- class libp2p.security.secio.transport.Transport(local_key_pair: ~libp2p.crypto.keys.KeyPair, secure_bytes_provider: ~typing.Callable[[int], bytes] = <function default_secure_bytes_provider>)
Bases:
BaseSecureTransport
Provide a security upgrader for a
IRawConnection
, following the secio protocol defined in the libp2p specs.- async secure_inbound(conn: IRawConnection) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are not the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async libp2p.security.secio.transport.create_secure_session(local_nonce: bytes, local_peer: ID, local_private_key: PrivateKey, conn: IRawConnection, remote_peer: ID | None = None) ISecureConn
Attempt the initial secio handshake with the remote peer.
If successful, return an object that provides secure communication to the
remote_peer
. Raise SecioException when conn closed. Raise InconsistentNonce when handshake failed
Module contents
Submodules
libp2p.security.base_session module
- class libp2p.security.base_session.BaseSession(*, local_peer: ID, local_private_key: PrivateKey, remote_peer: ID, remote_permanent_pubkey: PublicKey, is_initiator: bool)
Bases:
ISecureConn
BaseSession
is not fully instantiated from its abstract classes as it is only meant to be used in clases that derive from it.- get_local_private_key() PrivateKey
- local_private_key: PrivateKey
libp2p.security.base_transport module
- class libp2p.security.base_transport.BaseSecureTransport(local_key_pair: ~libp2p.crypto.keys.KeyPair, secure_bytes_provider: ~typing.Callable[[int], bytes] = <function default_secure_bytes_provider>)
Bases:
ISecureTransport
BaseSecureTransport
is not fully instantiated from its abstract classes as it is only meant to be used in clases that derive from it.Clients can provide a strategy to get cryptographically secure bytes of a given length. A default implementation is provided using the
secrets
module from the standard library.
libp2p.security.exceptions module
- exception libp2p.security.exceptions.HandshakeFailure
Bases:
BaseLibp2pError
libp2p.security.secure_conn_interface module
- class libp2p.security.secure_conn_interface.AbstractSecureConn
Bases:
ABC
- abstract get_local_private_key() PrivateKey
- class libp2p.security.secure_conn_interface.ISecureConn
Bases:
AbstractSecureConn
,IRawConnection
libp2p.security.secure_session module
- class libp2p.security.secure_session.SecureSession(*, local_peer: ID, local_private_key: PrivateKey, remote_peer: ID, remote_permanent_pubkey: PublicKey, is_initiator: bool, conn: EncryptedMsgReadWriter)
Bases:
BaseSession
- buf: BytesIO
libp2p.security.secure_transport_interface module
- class libp2p.security.secure_transport_interface.ISecureTransport
Bases:
ABC
- abstract async secure_inbound(conn: IRawConnection) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are not the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- abstract async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
libp2p.security.security_multistream module
- class libp2p.security.security_multistream.SecurityMultistream(secure_transports_by_protocol: Mapping[TProtocol, ISecureTransport])
Bases:
ABC
SSMuxer is a multistream stream security transport multiplexer.
Go implementation: github.com/libp2p/go-conn-security-multistream/ssms.go
- add_transport(protocol: TProtocol, transport: ISecureTransport) None
Add a protocol and its corresponding transport to multistream- select(multiselect). The order that a protocol is added is exactly the precedence it is negotiated in multiselect.
- Parameters:
protocol – the protocol name, which is negotiated in multiselect.
transport – the corresponding transportation to the
protocol
.
- multiselect: Multiselect
- multiselect_client: MultiselectClient
- async secure_inbound(conn: IRawConnection) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are not the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async secure_outbound(conn: IRawConnection, peer_id: ID) ISecureConn
Secure the connection, either locally or by communicating with opposing node via conn, for an inbound connection (i.e. we are the initiator)
- Returns:
secure connection object (that implements secure_conn_interface)
- async select_transport(conn: IRawConnection, is_initiator: bool) ISecureTransport
Select a transport that both us and the node on the other end of conn support and agree on.
- Parameters:
conn – conn to choose a transport over
is_initiator – true if we are the initiator, false otherwise
- Returns:
selected secure transport
- transports: OrderedDict[TProtocol, ISecureTransport]
Module contents
libp2p.stream_muxer package
Subpackages
libp2p.stream_muxer.mplex package
Submodules
libp2p.stream_muxer.mplex.constants module
libp2p.stream_muxer.mplex.datastructures module
libp2p.stream_muxer.mplex.exceptions module
- exception libp2p.stream_muxer.mplex.exceptions.MplexError
Bases:
MuxedConnError
- exception libp2p.stream_muxer.mplex.exceptions.MplexStreamClosed
Bases:
MuxedStreamClosed
- exception libp2p.stream_muxer.mplex.exceptions.MplexStreamEOF
Bases:
MuxedStreamEOF
- exception libp2p.stream_muxer.mplex.exceptions.MplexStreamReset
Bases:
MuxedStreamReset
Bases:
MuxedConnUnavailable
libp2p.stream_muxer.mplex.mplex module
- class libp2p.stream_muxer.mplex.mplex.Mplex(secured_conn: ISecureConn, peer_id: ID)
Bases:
IMuxedConn
reference: https://github.com/libp2p/go-mplex/blob/master/multiplex.go
- async accept_stream() IMuxedStream
Accept a muxed stream opened by the other end.
- event_closed: Event
- event_shutting_down: Event
- event_started: Event
- async handle_incoming() None
Read a message off of the secured connection and add it to the corresponding message buffer.
- new_stream_receive_channel: trio.MemoryReceiveChannel[IMuxedStream]
- new_stream_send_channel: trio.MemorySendChannel[IMuxedStream]
- async open_stream() IMuxedStream
Create a new muxed_stream.
- Returns:
a new
MplexStream
- async read_message() Tuple[int, int, bytes]
Read a single message off of the secured connection.
- Returns:
stream_id, flag, message contents
- secured_conn: ISecureConn
- async send_message(flag: HeaderTags, data: bytes | None, stream_id: StreamID) int
Send a message over the connection.
- Parameters:
flag – header to use
data – data to send in the message
stream_id – stream the message is in
- streams: Dict[StreamID, MplexStream]
- streams_lock: Lock
libp2p.stream_muxer.mplex.mplex_stream module
- class libp2p.stream_muxer.mplex.mplex_stream.MplexStream(name: str, stream_id: StreamID, muxed_conn: Mplex, incoming_data_channel: trio.MemoryReceiveChannel[bytes])
Bases:
IMuxedStream
reference: https://github.com/libp2p/go-mplex/blob/master/stream.go
- async close() None
Closing a stream closes it for writing and closes the remote end for reading but allows writing in the other direction.
- close_lock: Lock
- event_local_closed: Event
- event_remote_closed: Event
- event_reset: Event
- async read(n: int | None = None) bytes
Read up to n bytes. Read possibly returns fewer than n bytes, if there are not enough bytes in the Mplex buffer. If n is None, read until EOF.
- Parameters:
n – number of bytes to read
- Returns:
bytes actually read
Module contents
Submodules
libp2p.stream_muxer.abc module
- class libp2p.stream_muxer.abc.IMuxedConn(conn: ISecureConn, peer_id: ID)
Bases:
ABC
reference: https://github.com/libp2p/go-stream-muxer/blob/master/muxer.go
- abstract async accept_stream() IMuxedStream
Accept a muxed stream opened by the other end.
- event_started: Event
- abstract async open_stream() IMuxedStream
Create a new muxed_stream.
- Returns:
a new
IMuxedStream
stream
- class libp2p.stream_muxer.abc.IMuxedStream
Bases:
ReadWriteCloser
- muxed_conn: IMuxedConn
libp2p.stream_muxer.exceptions module
- exception libp2p.stream_muxer.exceptions.MuxedConnError
Bases:
BaseLibp2pError
Bases:
MuxedConnError
- exception libp2p.stream_muxer.exceptions.MuxedStreamClosed
Bases:
MuxedStreamError
- exception libp2p.stream_muxer.exceptions.MuxedStreamEOF
Bases:
MuxedStreamError
,EOFError
- exception libp2p.stream_muxer.exceptions.MuxedStreamError
Bases:
BaseLibp2pError
- exception libp2p.stream_muxer.exceptions.MuxedStreamReset
Bases:
MuxedStreamError
libp2p.stream_muxer.muxer_multistream module
- class libp2p.stream_muxer.muxer_multistream.MuxerMultistream(muxer_transports_by_protocol: Mapping[TProtocol, Type[IMuxedConn]])
Bases:
object
MuxerMultistream is a multistream stream muxed transport multiplexer.
go implementation: github.com/libp2p/go-stream-muxer-multistream/multistream.go
- add_transport(protocol: TProtocol, transport: Type[IMuxedConn]) None
Add a protocol and its corresponding transport to multistream- select(multiselect). The order that a protocol is added is exactly the precedence it is negotiated in multiselect.
- Parameters:
protocol – the protocol name, which is negotiated in multiselect.
transport – the corresponding transportation to the
protocol
.
- multiselect: Multiselect
- multiselect_client: MultiselectClient
- async new_conn(conn: ISecureConn, peer_id: ID) IMuxedConn
- async select_transport(conn: IRawConnection) Type[IMuxedConn]
Select a transport that both us and the node on the other end of conn support and agree on.
- Parameters:
conn – conn to choose a transport over
- Returns:
selected muxer transport
- transports: OrderedDict[TProtocol, TMuxerClass]
Module contents
libp2p.tools package
Subpackages
libp2p.tools.pubsub package
Submodules
libp2p.tools.pubsub.dummy_account_node module
- class libp2p.tools.pubsub.dummy_account_node.DummyAccountNode(pubsub: Pubsub)
Bases:
Service
Node which has an internal balance mapping, meant to serve as a dummy crypto blockchain.
There is no actual blockchain, just a simple map indicating how much crypto each user in the mappings holds
- classmethod create(number: int) AsyncIterator[Tuple[DummyAccountNode, ...]]
Create a new DummyAccountNode and attach a libp2p node, a floodsub, and a pubsub instance to this new node.
We use create as this serves as a factory function and allows us to use async await, unlike the init function
- get_balance(user: str) int
Get balance in crypto for a particular user.
- Parameters:
user – user to get balance for
- Returns:
balance of user
- handle_send_crypto(source_user: str, dest_user: str, amount: int) None
Handle incoming send_crypto message.
- Parameters:
source_user – user to send crypto from
dest_user – user to send crypto to
amount – amount of crypto to send
- handle_set_crypto(dest_user: str, amount: int) None
Handle incoming set_crypto message.
- Parameters:
dest_user – user to set crypto for
amount – amount of crypto
- async publish_send_crypto(source_user: str, dest_user: str, amount: int) None
Create a send crypto message and publish that message to all other nodes.
- Parameters:
source_user – user to send crypto from
dest_user – user to send crypto to
amount – amount of crypto to send
libp2p.tools.pubsub.floodsub_integration_test_settings module
- async libp2p.tools.pubsub.floodsub_integration_test_settings.perform_test_from_obj(obj, pubsub_factory) None
Perform pubsub tests from a test object, which is composed as follows:
{ "supported_protocols": ["supported/protocol/1.0.0",...], "adj_list": { "node1": ["neighbor1_of_node1", "neighbor2_of_node1", ...], "node2": ["neighbor1_of_node2", "neighbor2_of_node2", ...], ... }, "topic_map": { "topic1": ["node1_subscribed_to_topic1", "node2_subscribed_to_topic1", ...] }, "messages": [ { "topics": ["topic1_for_message", "topic2_for_message", ...], "data": b"some contents of the message (newlines are not supported)", "node_id": "message sender node id" }, ... ] }
Note
In adj_list, for any neighbors A and B, only list B as a neighbor of A or B as a neighbor of A once. Do NOT list both A: [“B”] and B:[“A”] as the behavior is undefined (even if it may work)
libp2p.tools.pubsub.utils module
Module contents
Submodules
libp2p.tools.constants module
libp2p.tools.factories module
- class libp2p.tools.factories.DummyRouter
Bases:
IPeerRouting
- class libp2p.tools.factories.FloodsubFactory(**kwargs)
Bases:
Factory
- protocols = ('/floodsub/1.0.0',)
- class libp2p.tools.factories.GossipsubFactory(**kwargs)
Bases:
Factory
- degree = 10
- degree_high = 11
- degree_low = 9
- gossip_history = 5
- gossip_window = 3
- heartbeat_initial_delay = 0.1
- heartbeat_interval = 0.5
- protocols = ('/meshsub/1.0.0',)
- time_to_live = 30
- class libp2p.tools.factories.HostFactory(**kwargs)
Bases:
Factory
- classmethod create_batch_and_listen(number: int, security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[BasicHost, ...]]
- network = <factory.declarations.LazyAttribute object>
- class libp2p.tools.factories.IDFactory(**kwargs)
Bases:
Factory
- peer_id_bytes = <factory.declarations.LazyFunction object>
- class libp2p.tools.factories.PubsubFactory(**kwargs)
Bases:
Factory
- cache_size = None
- classmethod create_and_start(host: IHost, router: IPubsubRouter, cache_size: int, strict_signing: bool, msg_id_constructor: Callable[[Message], bytes] = None) AsyncIterator[Pubsub]
- classmethod create_batch_with_floodsub(number: int, cache_size: int = None, strict_signing: bool = False, protocols: ~typing.Sequence[TProtocol] = None, security_protocol: TProtocol = None, muxer_opt: ~typing.Mapping[TProtocol, ~typing.Type[~libp2p.stream_muxer.abc.IMuxedConn]] = None, msg_id_constructor: ~typing.Callable[[~libp2p.pubsub.pb.rpc_pb2.Message], bytes] = <function get_peer_and_seqno_msg_id>) AsyncIterator[Tuple[Pubsub, ...]]
- classmethod create_batch_with_gossipsub(number: int, *, cache_size: int = None, strict_signing: bool = False, protocols: ~typing.Sequence[TProtocol] = None, degree: int = 10, degree_low: int = 9, degree_high: int = 11, time_to_live: int = 30, gossip_window: int = 3, gossip_history: int = 5, heartbeat_interval: float = 0.5, heartbeat_initial_delay: float = 0.1, security_protocol: TProtocol = None, muxer_opt: ~typing.Mapping[TProtocol, ~typing.Type[~libp2p.stream_muxer.abc.IMuxedConn]] = None, msg_id_constructor: ~typing.Callable[[~libp2p.pubsub.pb.rpc_pb2.Message], bytes] = <function get_peer_and_seqno_msg_id>) AsyncIterator[Tuple[Pubsub, ...]]
- host = <factory.declarations.SubFactory object>
- router = None
- strict_signing = False
- class libp2p.tools.factories.RoutedHostFactory(**kwargs)
Bases:
Factory
- classmethod create_batch_and_listen(number: int, security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[RoutedHost, ...]]
- network = <factory.declarations.LazyAttribute object>
- router = <factory.declarations.LazyFunction object>
- class libp2p.tools.factories.SwarmFactory(**kwargs)
Bases:
Factory
- classmethod create_and_listen(key_pair: KeyPair = None, security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Swarm]
- classmethod create_batch_and_listen(number: int, security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[Swarm, ...]]
- peer_id = <factory.declarations.LazyAttribute object>
- peerstore = <factory.declarations.LazyAttribute object>
- transport = <factory.declarations.LazyFunction object>
- upgrader = <factory.declarations.LazyAttribute object>
- libp2p.tools.factories.default_muxer_transport_factory() Mapping[TProtocol, Type[IMuxedConn]]
- libp2p.tools.factories.host_pair_factory(security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[BasicHost, BasicHost]]
- libp2p.tools.factories.initialize_peerstore_with_our_keypair(self_id: ID, key_pair: KeyPair) PeerStore
- libp2p.tools.factories.mplex_conn_pair_factory(security_protocol: TProtocol = None) AsyncIterator[Tuple[Mplex, Mplex]]
- libp2p.tools.factories.mplex_stream_pair_factory(security_protocol: TProtocol = None) AsyncIterator[Tuple[MplexStream, MplexStream]]
- libp2p.tools.factories.mplex_transport_factory() Mapping[TProtocol, Type[IMuxedConn]]
- libp2p.tools.factories.net_stream_pair_factory(security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[INetStream, INetStream]]
- libp2p.tools.factories.noise_conn_factory(nursery: Nursery) AsyncIterator[Tuple[ISecureConn, ISecureConn]]
- libp2p.tools.factories.noise_handshake_payload_factory() NoiseHandshakePayload
- libp2p.tools.factories.noise_static_key_factory() PrivateKey
- libp2p.tools.factories.noise_transport_factory(key_pair: KeyPair) ISecureTransport
- libp2p.tools.factories.plaintext_transport_factory(key_pair: KeyPair) ISecureTransport
- libp2p.tools.factories.raw_conn_factory(nursery: Nursery) AsyncIterator[Tuple[IRawConnection, IRawConnection]]
- libp2p.tools.factories.secio_transport_factory(key_pair: KeyPair) ISecureTransport
- libp2p.tools.factories.security_options_factory_factory(protocol_id: TProtocol | None = None) Callable[[KeyPair], Mapping[TProtocol, ISecureTransport]]
- libp2p.tools.factories.swarm_conn_pair_factory(security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[SwarmConn, SwarmConn]]
- libp2p.tools.factories.swarm_pair_factory(security_protocol: TProtocol = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] = None) AsyncIterator[Tuple[Swarm, Swarm]]
libp2p.tools.utils module
Module contents
libp2p.transport package
Subpackages
libp2p.transport.tcp package
Submodules
libp2p.transport.tcp.tcp module
- class libp2p.transport.tcp.tcp.TCP
Bases:
ITransport
- 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.
- Parameters:
maddr – multiaddr of peer
- Returns:
RawConnection if successful
- Raises:
OpenConnectionError – raised when failed to open connection
- class libp2p.transport.tcp.tcp.TCPListener(handler_function: Callable[[ReadWriteCloser], Awaitable[None]])
Bases:
IListener
- get_addrs() Tuple[Multiaddr, ...]
Retrieve list of addresses the listener is listening on.
- Returns:
return list of addrs
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.listener_interface module
libp2p.transport.transport_interface module
- class libp2p.transport.transport_interface.ITransport
Bases:
ABC
- abstract create_listener(handler_function: Callable[[ReadWriteCloser], Awaitable[None]]) IListener
Create listener on transport.
- Parameters:
handler_function – a function called when a new conntion is received that takes a connection as argument which implements interface-connection
- Returns:
a listener object that implements listener_interface.py
- abstract async dial(maddr: Multiaddr) IRawConnection
Dial a transport to peer listening on multiaddr.
- Parameters:
multiaddr – multiaddr of peer
self_id – peer_id of the dialer (to send to receiver)
- Returns:
list of multiaddrs
libp2p.transport.typing module
libp2p.transport.upgrader module
- class libp2p.transport.upgrader.TransportUpgrader(secure_transports_by_protocol: Mapping[TProtocol, ISecureTransport], muxer_transports_by_protocol: Mapping[TProtocol, Type[IMuxedConn]])
Bases:
object
- muxer_multistream: MuxerMultistream
- security_multistream: SecurityMultistream
- async upgrade_connection(conn: ISecureConn, peer_id: ID) IMuxedConn
Upgrade secured connection to a muxed connection.
- upgrade_listener(transport: ITransport, listeners: IListener) None
Upgrade multiaddr listeners to libp2p-transport listeners.
- async upgrade_security(raw_conn: IRawConnection, peer_id: ID, is_initiator: bool) ISecureConn
Upgrade conn to a secured connection.
Module contents
Submodules
libp2p.exceptions module
- exception libp2p.exceptions.MultiError
Bases:
BaseLibp2pError
Raised with multiple exceptions.
- exception libp2p.exceptions.ParseError
Bases:
BaseLibp2pError
- exception libp2p.exceptions.ValidationError
Bases:
BaseLibp2pError
Raised when something does not pass a validation check.
libp2p.typing module
libp2p.utils module
Module contents
- libp2p.new_host(key_pair: KeyPair | None = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] | None = None, sec_opt: Mapping[TProtocol, ISecureTransport] | None = None, peerstore_opt: IPeerStore | None = None, disc_opt: IPeerRouting | 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
- Returns:
return a host instance
- libp2p.new_swarm(key_pair: KeyPair | None = None, muxer_opt: Mapping[TProtocol, Type[IMuxedConn]] | None = None, sec_opt: Mapping[TProtocol, ISecureTransport] | None = None, peerstore_opt: IPeerStore | None = None) INetworkService
Create a swarm instance based on the 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
- Returns:
return a default swarm instance
Contributing
TODO - instructions for contributing
Code of Conduct
The libp2p project operates under the IPFS Code of Conduct
tl;dr:
Be respectful.
We’re here to help: abuse@ipfs.io
Abusive behavior is never tolerated.
Violations of this code may result in swift and permanent expulsion from the IPFS [and libp2p] community.
“Too long, didn’t read” is not a valid excuse for not knowing what is in this document.