libp2p.peer package
Submodules
libp2p.peer.envelope module
- class libp2p.peer.envelope.Envelope(public_key: PublicKey, payload_type: Code | str | bytes, raw_payload: bytes, signature: bytes)
Bases:
objectA signed wrapper around a serialized libp2p record.
Envelopes are cryptographically signed by the author’s private key and are scoped to a specific ‘domain’ to prevent cross-protocol replay.
- Attributes:
public_key: The public key that can verify the envelope’s signature. payload_type: A multicodec code identifying the type of payload inside. raw_payload: The raw serialized record data. signature: Signature over the domain-scoped payload content.
- 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.
- 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.
- payload_type_code: Code
- 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.
- 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.
- libp2p.peer.envelope.consume_envelope(data: bytes, domain: str) tuple[Envelope, PeerRecord]
Parse, validate, and decode an Envelope from bytes.
Validates the envelope’s signature using the given domain and decodes the inner payload into a PeerRecord.
- Parameters:
data – Serialized envelope bytes.
domain – Domain string to verify signature against.
- Returns:
Tuple of (Envelope, PeerRecord).
- Raises:
ValueError – If signature validation or decoding fails.
- libp2p.peer.envelope.make_unsigned(domain: str, payload_type: bytes, payload: bytes) bytes
Build a byte buffer to be signed for an Envelope.
- The unsigned byte structure is:
varint(len(domain)) || domain || varint(len(payload_type)) || payload_type || varint(len(payload)) || payload
This is the exact input used during signing and verification.
- Parameters:
domain – Domain string for signature scoping.
payload_type – Identifier for the type of payload.
payload – Raw serialized payload bytes.
- Returns:
Byte buffer to be signed or verified.
- libp2p.peer.envelope.pub_key_from_protobuf(pb_key: PublicKey) PublicKey
Parse a protobuf PublicKey message into a native libp2p PublicKey.
Supports Ed25519, RSA, and Secp256k1 key types.
- Parameters:
pb_key – Protobuf representation of a public key.
- Returns:
Parsed PublicKey object.
- Raises:
ValueError – If the key type is unrecognized.
- libp2p.peer.envelope.pub_key_to_protobuf(pub_key: PublicKey) PublicKey
Convert a Python PublicKey object to its protobuf equivalent.
- Parameters:
pub_key – A libp2p-compatible PublicKey instance.
- Returns:
Serialized protobuf PublicKey message.
- libp2p.peer.envelope.seal_record(record: PeerRecord, private_key: PrivateKey) Envelope
Create and sign a new Envelope from a PeerRecord.
The record is serialized and signed in the scope of its domain and codec. The result is a self-contained, verifiable Envelope.
- Parameters:
record – A PeerRecord to encapsulate.
private_key – The signer’s private key.
- Returns:
A signed Envelope instance.
- libp2p.peer.envelope.unmarshal_envelope(data: bytes) Envelope
Deserialize an Envelope from its wire format.
This parses the protobuf fields without verifying the signature.
- Parameters:
data – Serialized envelope bytes.
- Returns:
Parsed Envelope object.
- Raises:
DecodeError – If protobuf parsing fails.
libp2p.peer.id module
- class libp2p.peer.id.ID(peer_id_bytes: bytes)
Bases:
object- extract_public_key() PublicKey | None
Extract the public key from this peer ID if it uses an identity multihash.
For Ed25519 and other small keys, the public key is embedded directly in the peer ID using an identity multihash. For larger keys like RSA, the peer ID uses a SHA-256 hash and the key cannot be extracted.
- Returns:
The public key if it can be extracted, None otherwise.
- classmethod from_multibase(multibase_str: str) ID
Parse a peer ID from a multibase-encoded string.
Parameters
- multibase_strstr
A multibase-encoded string (e.g.
"zQm…"for base58btc,"bafz…"for base32).
Raises
- multibase.InvalidMultibaseStringError
If multibase_str is not a valid multibase-encoded string.
- multibase.DecodingError
If the multibase prefix is recognised but the payload cannot be decoded.
- classmethod from_string(peer_id_str: str) ID
Decode a peer ID string that may be multibase or base58.
Follows the same logic as go-libp2p’s
peer.Decode():Strings starting with
"Qm"or"1"are treated as legacy base58-encoded peer IDs (SHA-256 and identity multihashes respectively).Everything else is tried as multibase first. If multibase decoding succeeds and the result is a valid multihash the peer ID is returned. Otherwise we fall back to base58.
Parameters
- peer_id_strstr
A peer ID encoded as either a multibase string or a legacy base58 string.
Raises
- ValueError
If peer_id_str cannot be decoded as either multibase or base58.
libp2p.peer.peer_record module
- class libp2p.peer.peer_record.PeerRecord(peer_id: ID | None = None, addrs: list[Multiaddr] | None = None, seq: int | None = None)
Bases:
IPeerRecordA record that contains metatdata about a peer in the libp2p network.
This includes: - peer_id: The peer’s globally unique indentifier. - addrs: A list of the peer’s publicly reachable multiaddrs. - seq: A strictly monotonically increasing timestamp used to order records over time.
PeerRecords are designed to be signed and transmitted in libp2p routing Envelopes.
- codec() bytes
Return the codec identifier for PeerRecords.
This binary perfix helps distinguish PeerRecords in serialized envelopes.
- domain() str
Return the domain string associated with this PeerRecord.
Used during record signing and envelope validation to identify the record type.
- equal(other: Any) bool
Check if this PeerRecord is identical to another.
Two PeerRecords are considered equal if: - Their peer IDs match. - Their sequence numbers are identical. - Their address lists are identical and in the same order.
- Parameters:
other – Another PeerRecord instance.
- Returns:
True if all fields mathch, False otherwise.
- marshal_record() bytes
Serialize a PeerRecord into raw bytes suitable for embedding in an Envelope.
This is typically called during the process of signing or sealing the record. :raises ValueError: if serialization to protobuf fails. :return: Serialized PeerRecord bytes.
- to_protobuf() PeerRecord
Convert the current PeerRecord into a ProtoBuf PeerRecord message.
- Raises:
ValueError – if peer_id serialization fails.
- Returns:
A ProtoBuf-encoded PeerRecord message object.
- libp2p.peer.peer_record.addrs_from_protobuf(addrs: Sequence[AddressInfo]) list[Multiaddr]
Convert a list of protobuf address records to Multiaddr objects.
- Parameters:
addrs – A list of protobuf PeerRecord.AddressInfo messages.
- Returns:
A list of decoded Multiaddr instances (invalid ones are skipped).
- libp2p.peer.peer_record.addrs_to_protobuf(addrs: list[Multiaddr]) list[AddressInfo]
Convert a list of Multiaddr objects into their protobuf representation.
- Parameters:
addrs – A list of Multiaddr instances.
- Returns:
A list of PeerRecord.AddressInfo protobuf messages.
- libp2p.peer.peer_record.peer_record_from_peer_info(info: PeerInfo) PeerRecord
Create a PeerRecord from a PeerInfo object.
This automatically assigns a timestamp-based sequence number to the record. :param info: A PeerInfo instance (contains peer_id and addrs). :return: A PeerRecord instance.
- libp2p.peer.peer_record.peer_record_from_protobuf(msg: PeerRecord) PeerRecord
Convert a protobuf PeerRecord message into a PeerRecord object.
- Parameters:
msg – Protobuf PeerRecord message.
- Raises:
ValueError – if the peer_id cannot be parsed.
- Returns:
A deserialized PeerRecord instance.
- libp2p.peer.peer_record.timestamp_seq() int
Generate a strictly increasing timestamp-based sequence number.
Ensures that even if multiple PeerRecords are generated in the same nanosecond, their seq values will still be strictly increasing by using a lock to track the last value.
- Returns:
A strictly increasing integer timestamp.
- libp2p.peer.peer_record.unmarshal_record(data: bytes) PeerRecord
Deserialize a PeerRecord from its serialized byte representation.
Typically used when receiveing a PeerRecord inside a signed routing Envelope.
- Parameters:
data – Serialized protobuf-encoded bytes.
- Raises:
ValueError – if parsing or conversion fails.
- Reurn:
A valid PeerRecord instance.
libp2p.peer.peerdata module
- class libp2p.peer.peerdata.PeerData
Bases:
IPeerData- add_privkey(privkey: PrivateKey) None
- Parameters:
privkey
- first_supported_protocol(protocols: Sequence[str]) str
- Parameters:
protocols – protocols to check from
- Returns:
first supported protocol in the given list
- 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 | None
- put_metadata(key: str, val: Any) None
- Parameters:
key – key in KV pair
val – val to associate with key
- record_latency(new_latency: float) None
Records a new latency measurement for the given peer using Exponentially Weighted Moving Average (EWMA) :param new_latency: the new latency value
libp2p.peer.peerinfo module
- exception libp2p.peer.peerinfo.InvalidAddrError
Bases:
ValueError
libp2p.peer.peerstore module
- class libp2p.peer.peerstore.PeerStore(max_records: int = 10000)
Bases:
IPeerStore- add_addr(peer_id: ID, addr: Multiaddr, ttl: int = 0) 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 = 0) 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
- async addr_stream(peer_id: ID) AsyncIterable[Multiaddr]
Returns an async stream of newly added addresses for the given peer.
This function allows consumers to subscribe to address updates for a peer and receive each new address as it is added via add_addr or add_addrs.
- Parameters:
peer_id – The ID of the peer to monitor address updates for.
- Returns:
An async iterator yielding Multiaddr instances as they are added.
- addrs(peer_id: ID) list[Multiaddr]
- Parameters:
peer_id – peer ID to get addrs for
- Returns:
list of addrs of a valid peer.
- Raises:
PeerStoreError – if peer ID not found
- 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).
- Returns:
True if the record was accepted and stored; False if it was rejected.
- consume_peer_records(envelopes: list[Envelope], ttl: int) list[bool]
Consume multiple peer records in a single operation.
- 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.
- 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_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_id – The peer to look up.
- Returns:
The signed Envelope if the peer is known and has valid addresses; None otherwise.
- 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
- latency_EWMA(peer_id: ID) float
- Parameters:
peer_id – peer ID to get private key for
- Returns:
The latency EWMA value for that peer
- 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_id – The peer whose record we may delete/
- 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
- put(peer_id: ID, key: str, val: Any) None
- Parameters:
peer_id – peer ID to put peer data for
key
value
- record_latency(peer_id: ID, RTT: float) None
Records a new latency measurement for the given peer using Exponentially Weighted Moving Average (EWMA)
- Parameters:
peer_id – peer ID to get private key for
RTT – the new latency value (round trip time)
- remove_protocols(peer_id: ID, protocols: Sequence[str]) None
- Parameters:
peer_id – peer ID to get info for
protocols – unsupported protocols to remove
- set_protocols(peer_id: ID, protocols: Sequence[str]) None
- Parameters:
peer_id – peer ID to set protocols for
protocols – protocols to set
- async start_cleanup_task(cleanup_interval: int = 3600) None
Start periodic cleanup of expired peer records and addresses.
- exception libp2p.peer.peerstore.PeerStoreError
Bases:
KeyErrorRaised when peer ID is not found in peer store.
- libp2p.peer.peerstore.create_signed_peer_record(peer_id: ID, addrs: list[Multiaddr], pvt_key: PrivateKey) Envelope
Creates a signed_peer_record wrapped in an Envelope
- libp2p.peer.peerstore.env_to_send_in_RPC(host: IHost) tuple[bytes, bool]
Return the signed peer record (Envelope) to be sent in an RPC.
This function checks whether the host already has a cached signed peer record (SPR). If one exists and its addresses match the host’s current listen addresses, the cached envelope is reused. Otherwise, a new signed peer record is created, cached, and returned.
Parameters
- hostIHost
The local host instance, providing access to peer ID, listen addresses, private key, and the peerstore.
Returns
- tuple[bytes, bool]
A 2-tuple where the first element is the serialized envelope (bytes) for the signed peer record, and the second element is a boolean flag indicating whether a new record was created (True) or an existing cached one was reused (False).
- libp2p.peer.peerstore.issue_and_cache_local_record(host: IHost) bytes
Create and cache a new signed peer record (Envelope) for the host.
This function generates a new signed peer record from the host’s peer ID, listen addresses, and private key. The resulting envelope is stored in the peerstore as the local record for future reuse.
Parameters
- hostIHost
The local host instance, providing access to peer ID, listen addresses, private key, and the peerstore.
Returns
- bytes
The serialized envelope (bytes) representing the newly created signed peer record.