From f3d8cbf9689f233d269918c225e84cebfcba1494 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Sun, 1 Jun 2025 23:02:41 +0530 Subject: [PATCH 01/11] feat: Matching go-libp2p PeerStore implementation --- libp2p/abc.py | 610 +++++++++++++-------- libp2p/peer/peerdata.py | 82 ++- libp2p/peer/peerstore.py | 62 ++- libp2p/tools/async_service/base.py | 3 +- libp2p/tools/async_service/trio_service.py | 3 +- 5 files changed, 535 insertions(+), 225 deletions(-) diff --git a/libp2p/abc.py b/libp2p/abc.py index dc941c43..0b63ed04 100644 --- a/libp2p/abc.py +++ b/libp2p/abc.py @@ -385,6 +385,10 @@ class IPeerMetadata(ABC): :raises Exception: If the operation is unsuccessful. """ + @abstractmethod + def clear_metadata(self, peer_id: ID) -> None: + """Clears the metadata""" + # -------------------------- addrbook interface.py -------------------------- @@ -475,11 +479,114 @@ class IAddrBook(ABC): """ + @abstractmethod + def set_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: + """Set addr""" + + @abstractmethod + def set_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: + """Set addrs""" + + @abstractmethod + def update_addrs(self, peer_id: ID, oldTTL: int, newTTL: int) -> None: + """Update addrs""" + + @abstractmethod + def addr_stream(self, peer_id: ID) -> None: + """Addr stream""" + + +# -------------------------- keybook interface.py -------------------------- + + +class IKeyBook(ABC): + """IKeyBook""" + + @abstractmethod + def pubkey(self, peer_id: ID) -> PublicKey: + """Pubkey""" + + @abstractmethod + def privkey(self, peer_id: ID) -> PrivateKey: + """Privkey""" + + @abstractmethod + def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: + """add_pubkey""" + + @abstractmethod + def add_privkey(self, peer_id: ID, privkey: PrivateKey) -> None: + """add_privkey""" + + @abstractmethod + def add_key_pair(self, peer_id: ID, key_pair: KeyPair) -> None: + """add_key_pair""" + + @abstractmethod + def peer_with_keys(self) -> list[ID]: + """peer_with_keys""" + + @abstractmethod + def clear_keydata(self, peer_id: ID) -> PublicKey: + """clear_keydata""" + + +# -------------------------- metrics interface.py -------------------------- + + +class IMetrics(ABC): + """IMetrics""" + + @abstractmethod + def record_latency(self, peer_id: ID, RTT: float) -> None: + """record_latency""" + + @abstractmethod + def latency_EWMA(self, peer_id: ID) -> float: + """latency_EWMA""" + + @abstractmethod + def clear_metrics(self, peer_id: ID) -> None: + """clear_metrics""" + + +# -------------------------- protobook interface.py -------------------------- + + +class IProtoBook(ABC): + @abstractmethod + def get_protocols(self, peer_id: ID) -> list[str]: + """get_protocols""" + + @abstractmethod + def add_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: + """add_protocols""" + + @abstractmethod + def set_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: + """set_protocols""" + + @abstractmethod + def remove_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: + """remove_protocols""" + + @abstractmethod + def supports_protocols(self, peer_id: ID, protocols: Sequence[str]) -> list[str]: + """supports_protocols""" + + @abstractmethod + def first_supported_protocol(self, peer_id: ID, protocols: Sequence[str]) -> str: + """first_supported_protocol""" + + @abstractmethod + def clear_protocol_data(self, peer_id: ID) -> None: + """clear_protocol_data""" + # -------------------------- peerstore interface.py -------------------------- -class IPeerStore(IAddrBook, IPeerMetadata): +class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): """ Interface for a peer store. @@ -488,9 +595,98 @@ class IPeerStore(IAddrBook, IPeerMetadata): """ @abstractmethod - def peer_info(self, peer_id: ID) -> PeerInfo: + def get(self, peer_id: ID, key: str) -> Any: """ - Retrieve the peer information for the specified peer. + Retrieve the value associated with a key for a specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + key : str + The key to look up. + + Returns + ------- + Any + The value corresponding to the specified key. + + Raises + ------ + PeerStoreError + If the peer ID or value is not found. + + """ + + @abstractmethod + def put(self, peer_id: ID, key: str, val: Any) -> None: + """ + Store a key-value pair for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + key : str + The key for the data. + val : Any + The value to store. + + """ + + @abstractmethod + def clear_metadata(self, peer_id: ID) -> None: + """clear_metadata""" + + ## + @abstractmethod + def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: + """ + Add an address for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + addr : Multiaddr + The multiaddress to add. + ttl : int + The time-to-live for the record. + + """ + + @abstractmethod + def add_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: + """ + Add multiple addresses for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + addrs : Sequence[Multiaddr] + A sequence of multiaddresses to add. + ttl : int + The time-to-live for the record. + + """ + + @abstractmethod + def set_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: + """set_addr""" + + @abstractmethod + def set_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: + """set_addrs""" + + @abstractmethod + def update_addrs(self, peer_id: ID, oldTTL: int, newTTL: int) -> None: + """update_addrs""" + + @abstractmethod + def addrs(self, peer_id: ID) -> list[Multiaddr]: + """ + Retrieve the addresses for the specified peer. Parameters ---------- @@ -499,11 +695,163 @@ class IPeerStore(IAddrBook, IPeerMetadata): Returns ------- - PeerInfo - The peer information object for the given peer. + list[Multiaddr] + A list of multiaddresses. """ + @abstractmethod + def clear_addrs(self, peer_id: ID) -> None: + """ + Clear all addresses for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + + """ + + @abstractmethod + def peers_with_addrs(self) -> list[ID]: + """ + Retrieve all peer identifiers with stored addresses. + + Returns + ------- + list[ID] + A list of peer IDs. + + """ + + @abstractmethod + def addr_stream(self, peer_id: ID) -> None: + """addr_stream""" + + ## + @abstractmethod + def pubkey(self, peer_id: ID) -> PublicKey: + """ + Retrieve the public key for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + + Returns + ------- + PublicKey + The public key of the peer. + + Raises + ------ + PeerStoreError + If the peer ID is not found. + + """ + + @abstractmethod + def privkey(self, peer_id: ID) -> PrivateKey: + """ + Retrieve the private key for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + + Returns + ------- + PrivateKey + The private key of the peer. + + Raises + ------ + PeerStoreError + If the peer ID is not found. + + """ + + @abstractmethod + def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: + """ + Add a public key for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + pubkey : PublicKey + The public key to add. + + Raises + ------ + PeerStoreError + If the peer already has a public key set. + + """ + + @abstractmethod + def add_privkey(self, peer_id: ID, privkey: PrivateKey) -> None: + """ + Add a private key for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + privkey : PrivateKey + The private key to add. + + Raises + ------ + PeerStoreError + If the peer already has a private key set. + + """ + + @abstractmethod + def add_key_pair(self, peer_id: ID, key_pair: KeyPair) -> None: + """ + Add a key pair for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + key_pair : KeyPair + The key pair to add. + + Raises + ------ + PeerStoreError + If the peer already has a public or private key set. + + """ + + @abstractmethod + def peer_with_keys(self) -> list[ID]: + """peer_with_keys""" + + @abstractmethod + def clear_keydata(self, peer_id: ID) -> PublicKey: + """clear_keydata""" + + ## + @abstractmethod + def record_latency(self, peer_id: ID, RTT: float) -> None: + """record_latency""" + + @abstractmethod + def latency_EWMA(self, peer_id: ID) -> float: + """latency_EWMA""" + + @abstractmethod + def clear_metrics(self, peer_id: ID) -> None: + """clear_metrics""" + + ## @abstractmethod def get_protocols(self, peer_id: ID) -> list[str]: """ @@ -554,6 +902,40 @@ class IPeerStore(IAddrBook, IPeerMetadata): """ + @abstractmethod + def remove_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: + """remove_protocols""" + + @abstractmethod + def supports_protocols(self, peer_id: ID, protocols: Sequence[str]) -> list[str]: + """supports_protocols""" + + @abstractmethod + def first_supported_protocol(self, peer_id: ID, protocols: Sequence[str]) -> str: + """first_supported_protocol""" + + @abstractmethod + def clear_protocol_data(self, peer_id: ID) -> None: + """clear_protocol_data""" + + ## + @abstractmethod + def peer_info(self, peer_id: ID) -> PeerInfo: + """ + Retrieve the peer information for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer. + + Returns + ------- + PeerInfo + The peer information object for the given peer. + + """ + @abstractmethod def peer_ids(self) -> list[ID]: """ @@ -567,218 +949,8 @@ class IPeerStore(IAddrBook, IPeerMetadata): """ @abstractmethod - def get(self, peer_id: ID, key: str) -> Any: - """ - Retrieve the value associated with a key for a specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - key : str - The key to look up. - - Returns - ------- - Any - The value corresponding to the specified key. - - Raises - ------ - PeerStoreError - If the peer ID or value is not found. - - """ - - @abstractmethod - def put(self, peer_id: ID, key: str, val: Any) -> None: - """ - Store a key-value pair for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - key : str - The key for the data. - val : Any - The value to store. - - """ - - @abstractmethod - def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: - """ - Add an address for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - addr : Multiaddr - The multiaddress to add. - ttl : int - The time-to-live for the record. - - """ - - @abstractmethod - def add_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: - """ - Add multiple addresses for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - addrs : Sequence[Multiaddr] - A sequence of multiaddresses to add. - ttl : int - The time-to-live for the record. - - """ - - @abstractmethod - def addrs(self, peer_id: ID) -> list[Multiaddr]: - """ - Retrieve the addresses for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - - Returns - ------- - list[Multiaddr] - A list of multiaddresses. - - """ - - @abstractmethod - def clear_addrs(self, peer_id: ID) -> None: - """ - Clear all addresses for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - - """ - - @abstractmethod - def peers_with_addrs(self) -> list[ID]: - """ - Retrieve all peer identifiers with stored addresses. - - Returns - ------- - list[ID] - A list of peer IDs. - - """ - - @abstractmethod - def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: - """ - Add a public key for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - pubkey : PublicKey - The public key to add. - - Raises - ------ - PeerStoreError - If the peer already has a public key set. - - """ - - @abstractmethod - def pubkey(self, peer_id: ID) -> PublicKey: - """ - Retrieve the public key for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - - Returns - ------- - PublicKey - The public key of the peer. - - Raises - ------ - PeerStoreError - If the peer ID is not found. - - """ - - @abstractmethod - def add_privkey(self, peer_id: ID, privkey: PrivateKey) -> None: - """ - Add a private key for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - privkey : PrivateKey - The private key to add. - - Raises - ------ - PeerStoreError - If the peer already has a private key set. - - """ - - @abstractmethod - def privkey(self, peer_id: ID) -> PrivateKey: - """ - Retrieve the private key for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - - Returns - ------- - PrivateKey - The private key of the peer. - - Raises - ------ - PeerStoreError - If the peer ID is not found. - - """ - - @abstractmethod - def add_key_pair(self, peer_id: ID, key_pair: KeyPair) -> None: - """ - Add a key pair for the specified peer. - - Parameters - ---------- - peer_id : ID - The identifier of the peer. - key_pair : KeyPair - The key pair to add. - - Raises - ------ - PeerStoreError - If the peer already has a public or private key set. - - """ + def clear_peerdata(self, peer_id: ID) -> None: + """clear_peerdata""" # -------------------------- listener interface.py -------------------------- @@ -1316,7 +1488,7 @@ class IPeerData(ABC): """ @abstractmethod - def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: + def add_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: """ Add multiple multiaddresses to the peer's data. @@ -1324,6 +1496,8 @@ class IPeerData(ABC): ---------- addrs : Sequence[Multiaddr] A sequence of multiaddresses to add. + ttl: inr + Time to live for the peer record """ diff --git a/libp2p/peer/peerdata.py b/libp2p/peer/peerdata.py index 386e31ef..bd0c4d0b 100644 --- a/libp2p/peer/peerdata.py +++ b/libp2p/peer/peerdata.py @@ -18,6 +18,13 @@ from libp2p.crypto.keys import ( PublicKey, ) +""" +Latency EWMA Smoothing governs the deacy of the EWMA (the speed at which +is changes). This must be a normalized (0-1) value. +1 is 100% change, 0 is no change. +""" +LATENCY_EWMA_SMOOTHING = 0.1 + class PeerData(IPeerData): pubkey: PublicKey | None @@ -55,13 +62,82 @@ class PeerData(IPeerData): """ self.protocols = list(protocols) - def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: + def remove_protocols(self, protocols: Sequence[str]) -> None: + """ + :param protocols: protocols to remove + """ + for protocol in protocols: + if protocol in self.protocols: + self.protocols.remove(protocol) + + def supports_protocols(self, protocols: Sequence[str]) -> list[str]: + """ + :param protocols: protocols to check from + :return: all supported protocols in the given list + """ + return [proto for proto in protocols if proto in self.protocols] + + def first_supported_protocol(self, protocols: Sequence[str]) -> str: + """ + :param protocols: protocols to check from + :return: first supported protocol in the given list + """ + for protocol in protocols: + if protocol in self.protocols: + return protocol + + return "None supported" + + def clear_protocol_data(self) -> None: + """Clear all protocols""" + self.protocols = [] + + def add_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: """ :param addrs: multiaddresses to add """ + expiry = time.time() + ttl if ttl is not None else float("inf") for addr in addrs: if addr not in self.addrs: self.addrs.append(addr) + current_expiry = self.addrs_ttl.get(addr, 0) + if expiry > current_expiry: + self.addrs_ttl[addr] = expiry + + def set_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: + """ + :param addrs: multiaddresses to update + :param ttl: new ttl + """ + now = time.time() + + if ttl <= 0: + # Put the TTL value to -1 + for addr in addrs: + # TODO! if addr in self.addrs, remove them? + if addr in self.addrs_ttl: + del self.addrs_ttl[addr] + return + + expiry = now + ttl + for addr in addrs: + # TODO! if addr not in self.addrs, add them? + self.addrs_ttl[addr] = expiry + + def update_addrs(self, oldTTL: int, newTTL: int) -> None: + """ + :param oldTTL: old ttl + :param newTTL: new ttl + """ + now = time.time() + + new_expiry = now + newTTL + old_expiry = now + oldTTL + + for addr, expiry in list(self.addrs_ttl.items()): + # Approximate match by expiry time + if abs(expiry - old_expiry) < 1: + self.addrs_ttl[addr] = new_expiry def get_addrs(self) -> list[Multiaddr]: """ @@ -90,6 +166,10 @@ class PeerData(IPeerData): return self.metadata[key] raise PeerDataError("key not found") + def clear_metadata(self) -> None: + """Clears metadata.""" + self.metadata = {} + def add_pubkey(self, pubkey: PublicKey) -> None: """ :param pubkey: diff --git a/libp2p/peer/peerstore.py b/libp2p/peer/peerstore.py index 3bb729d2..ada56f47 100644 --- a/libp2p/peer/peerstore.py +++ b/libp2p/peer/peerstore.py @@ -53,6 +53,15 @@ class PeerStore(IPeerStore): return PeerInfo(peer_id, peer_data.get_addrs()) raise PeerStoreError("peer ID not found") + def peer_ids(self) -> list[ID]: + """ + :return: all of the peer IDs stored in peer store + """ + return list(self.peer_data_map.keys()) + + def clear_peerdata(self, peer_id: ID) -> None: + """Clears the peer data of the peer""" + def get_protocols(self, peer_id: ID) -> list[str]: """ :param peer_id: peer ID to get protocols for @@ -79,7 +88,15 @@ class PeerStore(IPeerStore): peer_data = self.peer_data_map[peer_id] peer_data.set_protocols(list(protocols)) - def peer_ids(self) -> list[ID]: + def remove_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: + """ + :param peer_id: peer ID to get info for + :param protocols: unsupported protocols to remove + """ + peer_data = self.peer_data_map[peer_id] + peer_data.remove_protocols(protocols) + + def supports_protocols(self, peer_id: ID, protocols: Sequence[str]) -> list[str]: """ :return: all of the peer IDs stored in peer store """ @@ -165,7 +182,7 @@ class PeerStore(IPeerStore): def peers_with_addrs(self) -> list[ID]: """ - :return: all of the peer IDs which has addrs stored in peer store + :return: all of the peer IDs which has addrsfloat stored in peer store """ # Add all peers with addrs at least 1 to output output: list[ID] = [] @@ -179,6 +196,10 @@ class PeerStore(IPeerStore): peer_data.clear_addrs() return output + def addr_stream(self, peer_id: ID) -> None: + """addr_stream""" + # TODO! + def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: """ :param peer_id: peer ID to add public key for @@ -239,6 +260,43 @@ class PeerStore(IPeerStore): self.add_pubkey(peer_id, key_pair.public_key) self.add_privkey(peer_id, key_pair.private_key) + def peer_with_keys(self) -> list[ID]: + """Returns the peer_ids for which keys are stored""" + return [ + peer_id + for peer_id, pdata in self.peer_data_map.items() + if pdata.pubkey is not None + ] + + def clear_keydata(self, peer_id: ID) -> None: + """Clears all the keys of the peer""" + peer_data = self.peer_data_map[peer_id] + peer_data.clear_keydata() + + def record_latency(self, peer_id: ID, RTT: float) -> None: + """ + Records a new latency measurement for the given peer + using Exponentially Weighted Moving Average (EWMA) + + :param peer_id: peer ID to get private key for + :param RTT: the new latency value (round trip time) + """ + peer_data = self.peer_data_map[peer_id] + peer_data.record_latency(RTT) + + def latency_EWMA(self, peer_id: ID) -> float: + """ + :param peer_id: peer ID to get private key for + :return: The latency EWMA value for that peer + """ + peer_data = self.peer_data_map[peer_id] + return peer_data.latency_EWMA() + + def clear_metrics(self, peer_id: ID) -> None: + """Clear the latency metrics""" + peer_data = self.peer_data_map[peer_id] + peer_data.clear_metrics() + class PeerStoreError(KeyError): """Raised when peer ID is not found in peer store.""" diff --git a/libp2p/tools/async_service/base.py b/libp2p/tools/async_service/base.py index a23f0e75..bd6c3ef0 100644 --- a/libp2p/tools/async_service/base.py +++ b/libp2p/tools/async_service/base.py @@ -18,7 +18,6 @@ import sys from typing import ( Any, TypeVar, - cast, ) import uuid @@ -361,7 +360,7 @@ class BaseManager(InternalManagerAPI): # Only show stacktrace if this is **not** a DaemonTaskExit error exc_info=not isinstance(err, DaemonTaskExit), ) - self._errors.append(cast(EXC_INFO, sys.exc_info())) + self._errors.append(sys.exc_info()) self.cancel() else: if task.parent is None: diff --git a/libp2p/tools/async_service/trio_service.py b/libp2p/tools/async_service/trio_service.py index 3fdddb81..61b5cb7a 100644 --- a/libp2p/tools/async_service/trio_service.py +++ b/libp2p/tools/async_service/trio_service.py @@ -52,7 +52,6 @@ from .exceptions import ( LifecycleError, ) from .typing import ( - EXC_INFO, AsyncFn, ) @@ -232,7 +231,7 @@ class TrioManager(BaseManager): # Exceptions from any tasks spawned by our service will be # caught by trio and raised here, so we store them to report # together with any others we have already captured. - self._errors.append(cast(EXC_INFO, sys.exc_info())) + self._errors.append(sys.exc_info()) finally: system_nursery.cancel_scope.cancel() From 5de458482c2676830d93c0dbbd43a928baa2af25 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 14:22:21 +0530 Subject: [PATCH 02/11] refactor after rebase --- libp2p/abc.py | 30 +-------- libp2p/peer/peerdata.py | 73 ++++++++++------------ libp2p/peer/peerstore.py | 17 ++++- libp2p/tools/async_service/base.py | 3 +- libp2p/tools/async_service/trio_service.py | 3 +- 5 files changed, 56 insertions(+), 70 deletions(-) diff --git a/libp2p/abc.py b/libp2p/abc.py index 0b63ed04..343ae0a7 100644 --- a/libp2p/abc.py +++ b/libp2p/abc.py @@ -479,18 +479,6 @@ class IAddrBook(ABC): """ - @abstractmethod - def set_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: - """Set addr""" - - @abstractmethod - def set_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: - """Set addrs""" - - @abstractmethod - def update_addrs(self, peer_id: ID, oldTTL: int, newTTL: int) -> None: - """Update addrs""" - @abstractmethod def addr_stream(self, peer_id: ID) -> None: """Addr stream""" @@ -527,7 +515,7 @@ class IKeyBook(ABC): """peer_with_keys""" @abstractmethod - def clear_keydata(self, peer_id: ID) -> PublicKey: + def clear_keydata(self, peer_id: ID) -> None: """clear_keydata""" @@ -671,18 +659,6 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): """ - @abstractmethod - def set_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: - """set_addr""" - - @abstractmethod - def set_addrs(self, peer_id: ID, addrs: Sequence[Multiaddr], ttl: int) -> None: - """set_addrs""" - - @abstractmethod - def update_addrs(self, peer_id: ID, oldTTL: int, newTTL: int) -> None: - """update_addrs""" - @abstractmethod def addrs(self, peer_id: ID) -> list[Multiaddr]: """ @@ -835,7 +811,7 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): """peer_with_keys""" @abstractmethod - def clear_keydata(self, peer_id: ID) -> PublicKey: + def clear_keydata(self, peer_id: ID) -> None: """clear_keydata""" ## @@ -1488,7 +1464,7 @@ class IPeerData(ABC): """ @abstractmethod - def add_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: + def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: """ Add multiple multiaddresses to the peer's data. diff --git a/libp2p/peer/peerdata.py b/libp2p/peer/peerdata.py index bd0c4d0b..bf54a494 100644 --- a/libp2p/peer/peerdata.py +++ b/libp2p/peer/peerdata.py @@ -34,6 +34,7 @@ class PeerData(IPeerData): addrs: list[Multiaddr] last_identified: int ttl: int # Keep ttl=0 by default for always valid + latmap: float def __init__(self) -> None: self.pubkey = None @@ -43,6 +44,7 @@ class PeerData(IPeerData): self.addrs = [] self.last_identified = int(time.time()) self.ttl = 0 + self.latmap = 0 def get_protocols(self) -> list[str]: """ @@ -92,52 +94,13 @@ class PeerData(IPeerData): """Clear all protocols""" self.protocols = [] - def add_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: + def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: """ :param addrs: multiaddresses to add """ - expiry = time.time() + ttl if ttl is not None else float("inf") for addr in addrs: if addr not in self.addrs: self.addrs.append(addr) - current_expiry = self.addrs_ttl.get(addr, 0) - if expiry > current_expiry: - self.addrs_ttl[addr] = expiry - - def set_addrs(self, addrs: Sequence[Multiaddr], ttl: int) -> None: - """ - :param addrs: multiaddresses to update - :param ttl: new ttl - """ - now = time.time() - - if ttl <= 0: - # Put the TTL value to -1 - for addr in addrs: - # TODO! if addr in self.addrs, remove them? - if addr in self.addrs_ttl: - del self.addrs_ttl[addr] - return - - expiry = now + ttl - for addr in addrs: - # TODO! if addr not in self.addrs, add them? - self.addrs_ttl[addr] = expiry - - def update_addrs(self, oldTTL: int, newTTL: int) -> None: - """ - :param oldTTL: old ttl - :param newTTL: new ttl - """ - now = time.time() - - new_expiry = now + newTTL - old_expiry = now + oldTTL - - for addr, expiry in list(self.addrs_ttl.items()): - # Approximate match by expiry time - if abs(expiry - old_expiry) < 1: - self.addrs_ttl[addr] = new_expiry def get_addrs(self) -> list[Multiaddr]: """ @@ -200,6 +163,36 @@ class PeerData(IPeerData): raise PeerDataError("private key not found") return self.privkey + def clear_keydata(self) -> None: + """Clears keydata""" + self.pubkey = None + self.privkey = None + + def record_latency(self, 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 + """ + s = LATENCY_EWMA_SMOOTHING + if s > 1 or s < 0: + s = 0.1 + + if self.latmap is None: + self.latmap = new_latency + else: + prev = self.latmap + updated = ((1.0 - s) * prev) + (s * new_latency) + self.latmap = updated + + def latency_EWMA(self) -> float: + """Returns the latency EWMA value""" + return self.latmap + + def clear_metrics(self) -> None: + """Clear the latency metrics""" + self.latmap = 0 + def update_last_identified(self) -> None: self.last_identified = int(time.time()) diff --git a/libp2p/peer/peerstore.py b/libp2p/peer/peerstore.py index ada56f47..4539fc87 100644 --- a/libp2p/peer/peerstore.py +++ b/libp2p/peer/peerstore.py @@ -100,7 +100,17 @@ class PeerStore(IPeerStore): """ :return: all of the peer IDs stored in peer store """ - return list(self.peer_data_map.keys()) + peer_data = self.peer_data_map[peer_id] + return peer_data.supports_protocols(protocols) + + def first_supported_protocol(self, peer_id: ID, protocols: Sequence[str]) -> str: + peer_data = self.peer_data_map[peer_id] + return peer_data.first_supported_protocol(protocols) + + def clear_protocol_data(self, peer_id: ID) -> None: + """Clears prtocoldata""" + peer_data = self.peer_data_map[peer_id] + peer_data.clear_protocol_data() def valid_peer_ids(self) -> list[ID]: """ @@ -138,6 +148,11 @@ class PeerStore(IPeerStore): peer_data = self.peer_data_map[peer_id] peer_data.put_metadata(key, val) + def clear_metadata(self, peer_id: ID) -> None: + """Clears metadata""" + peer_data = self.peer_data_map[peer_id] + peer_data.clear_metadata() + def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int = 0) -> None: """ :param peer_id: peer ID to add address for diff --git a/libp2p/tools/async_service/base.py b/libp2p/tools/async_service/base.py index bd6c3ef0..a23f0e75 100644 --- a/libp2p/tools/async_service/base.py +++ b/libp2p/tools/async_service/base.py @@ -18,6 +18,7 @@ import sys from typing import ( Any, TypeVar, + cast, ) import uuid @@ -360,7 +361,7 @@ class BaseManager(InternalManagerAPI): # Only show stacktrace if this is **not** a DaemonTaskExit error exc_info=not isinstance(err, DaemonTaskExit), ) - self._errors.append(sys.exc_info()) + self._errors.append(cast(EXC_INFO, sys.exc_info())) self.cancel() else: if task.parent is None: diff --git a/libp2p/tools/async_service/trio_service.py b/libp2p/tools/async_service/trio_service.py index 61b5cb7a..3fdddb81 100644 --- a/libp2p/tools/async_service/trio_service.py +++ b/libp2p/tools/async_service/trio_service.py @@ -52,6 +52,7 @@ from .exceptions import ( LifecycleError, ) from .typing import ( + EXC_INFO, AsyncFn, ) @@ -231,7 +232,7 @@ class TrioManager(BaseManager): # Exceptions from any tasks spawned by our service will be # caught by trio and raised here, so we store them to report # together with any others we have already captured. - self._errors.append(sys.exc_info()) + self._errors.append(cast(EXC_INFO, sys.exc_info())) finally: system_nursery.cancel_scope.cancel() From 3d369bc142ac3a0117dfd8426163a47ecdd2515e Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 16:47:31 +0530 Subject: [PATCH 03/11] Proto-Book: added tests --- libp2p/peer/peerdata.py | 9 ++++++ libp2p/peer/peerstore.py | 32 +++++++++++++------- tests/core/peer/test_peerdata.py | 50 ++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 11 deletions(-) diff --git a/libp2p/peer/peerdata.py b/libp2p/peer/peerdata.py index bf54a494..725ca5a3 100644 --- a/libp2p/peer/peerdata.py +++ b/libp2p/peer/peerdata.py @@ -46,6 +46,8 @@ class PeerData(IPeerData): self.ttl = 0 self.latmap = 0 + # --------PROTO-BOOK-------- + def get_protocols(self) -> list[str]: """ :return: all protocols associated with given peer @@ -94,6 +96,7 @@ class PeerData(IPeerData): """Clear all protocols""" self.protocols = [] + # -------ADDR-BOOK--------- def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: """ :param addrs: multiaddresses to add @@ -112,6 +115,9 @@ class PeerData(IPeerData): """Clear all addresses.""" self.addrs = [] + # TODO! ADDRS_STREAM + + # -------METADATA----------- def put_metadata(self, key: str, val: Any) -> None: """ :param key: key in KV pair @@ -133,6 +139,7 @@ class PeerData(IPeerData): """Clears metadata.""" self.metadata = {} + # -------KEY-BOOK--------------- def add_pubkey(self, pubkey: PublicKey) -> None: """ :param pubkey: @@ -168,6 +175,7 @@ class PeerData(IPeerData): self.pubkey = None self.privkey = None + # ----------METRICS-------------- def record_latency(self, new_latency: float) -> None: """ Records a new latency measurement for the given peer @@ -196,6 +204,7 @@ class PeerData(IPeerData): def update_last_identified(self) -> None: self.last_identified = int(time.time()) + # ----------TTL------------------ def get_last_identified(self) -> int: """ :return: last identified timestamp diff --git a/libp2p/peer/peerstore.py b/libp2p/peer/peerstore.py index 4539fc87..da18a5f0 100644 --- a/libp2p/peer/peerstore.py +++ b/libp2p/peer/peerstore.py @@ -62,6 +62,20 @@ class PeerStore(IPeerStore): def clear_peerdata(self, peer_id: ID) -> None: """Clears the peer data of the peer""" + def valid_peer_ids(self) -> list[ID]: + """ + :return: all of the valid peer IDs stored in peer store + """ + valid_peer_ids: list[ID] = [] + for peer_id, peer_data in self.peer_data_map.items(): + if not peer_data.is_expired(): + valid_peer_ids.append(peer_id) + else: + peer_data.clear_addrs() + return valid_peer_ids + + # --------PROTO-BOOK-------- + def get_protocols(self, peer_id: ID) -> list[str]: """ :param peer_id: peer ID to get protocols for @@ -112,17 +126,7 @@ class PeerStore(IPeerStore): peer_data = self.peer_data_map[peer_id] peer_data.clear_protocol_data() - def valid_peer_ids(self) -> list[ID]: - """ - :return: all of the valid peer IDs stored in peer store - """ - valid_peer_ids: list[ID] = [] - for peer_id, peer_data in self.peer_data_map.items(): - if not peer_data.is_expired(): - valid_peer_ids.append(peer_id) - else: - peer_data.clear_addrs() - return valid_peer_ids + # ------METADATA--------- def get(self, peer_id: ID, key: str) -> Any: """ @@ -153,6 +157,8 @@ class PeerStore(IPeerStore): peer_data = self.peer_data_map[peer_id] peer_data.clear_metadata() + # -------ADDR-BOOK-------- + def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int = 0) -> None: """ :param peer_id: peer ID to add address for @@ -215,6 +221,8 @@ class PeerStore(IPeerStore): """addr_stream""" # TODO! + # -------KEY-BOOK--------- + def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: """ :param peer_id: peer ID to add public key for @@ -288,6 +296,8 @@ class PeerStore(IPeerStore): peer_data = self.peer_data_map[peer_id] peer_data.clear_keydata() + # --------METRICS-------- + def record_latency(self, peer_id: ID, RTT: float) -> None: """ Records a new latency measurement for the given peer diff --git a/tests/core/peer/test_peerdata.py b/tests/core/peer/test_peerdata.py index 65e98959..500e19d4 100644 --- a/tests/core/peer/test_peerdata.py +++ b/tests/core/peer/test_peerdata.py @@ -39,6 +39,56 @@ def test_set_protocols(): assert peer_data.get_protocols() == protocols +# Test case when removing protocols: +def test_remove_protocols(): + peer_data = PeerData() + protocols: Sequence[str] = ["protocol1", "protocol2"] + peer_data.set_protocols(protocols) + + peer_data.remove_protocols(["protocol1"]) + assert peer_data.get_protocols() == ["protocol2"] + + +# Test case when supports protocols: +def test_supports_protocols(): + peer_data = PeerData() + peer_data.set_protocols(["protocol1", "protocol2", "protocol3"]) + + input_protocols = ["protocol1", "protocol4", "protocol2"] + supported = peer_data.supports_protocols(input_protocols) + + assert supported == ["protocol1", "protocol2"] + + +def test_first_supported_protocol_found(): + peer_data = PeerData() + peer_data.set_protocols(["protocolA", "protocolB"]) + + input_protocols = ["protocolC", "protocolB", "protocolA"] + first = peer_data.first_supported_protocol(input_protocols) + + assert first == "protocolB" + + +def test_first_supported_protocol_none(): + peer_data = PeerData() + peer_data.set_protocols(["protocolX", "protocolY"]) + + input_protocols = ["protocolA", "protocolB"] + first = peer_data.first_supported_protocol(input_protocols) + + assert first == "None supported" + + +def test_clear_protocol_data(): + peer_data = PeerData() + peer_data.set_protocols(["proto1", "proto2"]) + + peer_data.clear_protocol_data() + + assert peer_data.get_protocols() == [] + + # Test case when adding addresses def test_add_addrs(): peer_data = PeerData() From 4e533270793e8dc7b4c3e3120eb27129d7d74b55 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 17:05:38 +0530 Subject: [PATCH 04/11] Metrics: added tests --- libp2p/peer/peerdata.py | 2 +- tests/core/peer/test_peerdata.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/libp2p/peer/peerdata.py b/libp2p/peer/peerdata.py index 725ca5a3..bf45ca23 100644 --- a/libp2p/peer/peerdata.py +++ b/libp2p/peer/peerdata.py @@ -186,7 +186,7 @@ class PeerData(IPeerData): if s > 1 or s < 0: s = 0.1 - if self.latmap is None: + if self.latmap == 0: self.latmap = new_latency else: prev = self.latmap diff --git a/tests/core/peer/test_peerdata.py b/tests/core/peer/test_peerdata.py index 500e19d4..f2d76643 100644 --- a/tests/core/peer/test_peerdata.py +++ b/tests/core/peer/test_peerdata.py @@ -157,3 +157,35 @@ def test_get_privkey_not_found(): peer_data = PeerData() with pytest.raises(PeerDataError): peer_data.get_privkey() + + +# Test case for recording latency for the first time +def test_record_latency_initial(): + peer_data = PeerData() + assert peer_data.latency_EWMA() == 0 + + peer_data.record_latency(100.0) + assert peer_data.latency_EWMA() == 100.0 + + +# Test case for updating latency +def test_record_latency_updates_ewma(): + peer_data = PeerData() + peer_data.record_latency(100.0) # first measurement + first = peer_data.latency_EWMA() + + peer_data.record_latency(50.0) # second measurement + second = peer_data.latency_EWMA() + + assert second < first # EWMA should have smoothed downward + assert second > 50.0 # Not as low as the new latency + assert second != first + + +def test_clear_metrics(): + peer_data = PeerData() + peer_data.record_latency(200.0) + assert peer_data.latency_EWMA() == 200.0 + + peer_data.clear_metrics() + assert peer_data.latency_EWMA() == 0 From 1b025e552c81187f37971fe59016a72dc15428f9 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 17:19:07 +0530 Subject: [PATCH 05/11] Key-Book: added tests --- tests/core/peer/test_peerdata.py | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/core/peer/test_peerdata.py b/tests/core/peer/test_peerdata.py index f2d76643..24730844 100644 --- a/tests/core/peer/test_peerdata.py +++ b/tests/core/peer/test_peerdata.py @@ -6,10 +6,12 @@ from multiaddr import Multiaddr from libp2p.crypto.secp256k1 import ( create_new_key_pair, ) +from libp2p.peer.id import ID from libp2p.peer.peerdata import ( PeerData, PeerDataError, ) +from libp2p.peer.peerstore import PeerStore MOCK_ADDR = Multiaddr("/ip4/127.0.0.1/tcp/4001") MOCK_KEYPAIR = create_new_key_pair() @@ -60,6 +62,7 @@ def test_supports_protocols(): assert supported == ["protocol1", "protocol2"] +# Test case for first supported protocol is found def test_first_supported_protocol_found(): peer_data = PeerData() peer_data.set_protocols(["protocolA", "protocolB"]) @@ -70,6 +73,7 @@ def test_first_supported_protocol_found(): assert first == "protocolB" +# Test case for first supported protocol not found def test_first_supported_protocol_none(): peer_data = PeerData() peer_data.set_protocols(["protocolX", "protocolY"]) @@ -80,6 +84,7 @@ def test_first_supported_protocol_none(): assert first == "None supported" +# Test case for clearing protocol data def test_clear_protocol_data(): peer_data = PeerData() peer_data.set_protocols(["proto1", "proto2"]) @@ -159,6 +164,42 @@ def test_get_privkey_not_found(): peer_data.get_privkey() +# Test case for returning all the peers with stored keys +def test_peer_with_keys(): + peer_store = PeerStore() + peer_id_1 = ID(b"peer1") + peer_id_2 = ID(b"peer2") + + peer_data_1 = PeerData() + peer_data_2 = PeerData() + + peer_data_1.pubkey = MOCK_PUBKEY + peer_data_2.pubkey = None + + peer_store.peer_data_map = { + peer_id_1: peer_data_1, + peer_id_2: peer_data_2, + } + + assert peer_store.peer_with_keys() == [peer_id_1] + + +# Test case for clearing the key book +def test_clear_keydata(): + peer_store = PeerStore() + peer_id = ID(b"peer123") + peer_data = PeerData() + + peer_data.pubkey = MOCK_PUBKEY + peer_data.privkey = MOCK_PRIVKEY + peer_store.peer_data_map = {peer_id: peer_data} + + peer_store.clear_keydata(peer_id) + + assert peer_data.pubkey is None + assert peer_data.privkey is None + + # Test case for recording latency for the first time def test_record_latency_initial(): peer_data = PeerData() From ff966bbfa027805f4801cb797180213aae3524fb Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 17:24:10 +0530 Subject: [PATCH 06/11] Metadata: added test --- tests/core/peer/test_peerdata.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/core/peer/test_peerdata.py b/tests/core/peer/test_peerdata.py index 24730844..46f9ed5a 100644 --- a/tests/core/peer/test_peerdata.py +++ b/tests/core/peer/test_peerdata.py @@ -136,6 +136,15 @@ def test_get_metadata_key_not_found(): peer_data.get_metadata("nonexistent_key") +# Test case for clearing metadata +def test_clear_metadata(): + peer_data = PeerData() + peer_data.metadata = {"key1": "value1", "key2": "value2"} + + peer_data.clear_metadata() + assert peer_data.metadata == {} + + # Test case for adding public key def test_add_pubkey(): peer_data = PeerData() From 994369705473fe38a8c8bae92d098ff0e0524eac Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 18:52:34 +0530 Subject: [PATCH 07/11] Added docstrings --- libp2p/abc.py | 454 ++++++++++++++++++++++++++++++++++++---- libp2p/peer/peerdata.py | 2 - 2 files changed, 411 insertions(+), 45 deletions(-) diff --git a/libp2p/abc.py b/libp2p/abc.py index 343ae0a7..70c4ab71 100644 --- a/libp2p/abc.py +++ b/libp2p/abc.py @@ -387,7 +387,15 @@ class IPeerMetadata(ABC): @abstractmethod def clear_metadata(self, peer_id: ID) -> None: - """Clears the metadata""" + """ + Remove all stored metadata for the specified peer. + + Parameters + ---------- + peer_id : ID + The peer identifier whose metadata are to be removed. + + """ # -------------------------- addrbook interface.py -------------------------- @@ -479,96 +487,267 @@ class IAddrBook(ABC): """ - @abstractmethod - def addr_stream(self, peer_id: ID) -> None: - """Addr stream""" - # -------------------------- keybook interface.py -------------------------- class IKeyBook(ABC): - """IKeyBook""" + """ + Interface for an key book. + + Provides methods for managing cryptographic keys. + """ @abstractmethod def pubkey(self, peer_id: ID) -> PublicKey: - """Pubkey""" + """ + Returns the public key of the specified peer + + Parameters + ---------- + peer_id : ID + The peer identifier whose public key is to be returned. + + """ @abstractmethod def privkey(self, peer_id: ID) -> PrivateKey: - """Privkey""" + """ + Returns the private key of the specified peer + + Parameters + ---------- + peer_id : ID + The peer identifier whose private key is to be returned. + + """ @abstractmethod def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: - """add_pubkey""" + """ + Adds the public key for a specified peer + + Parameters + ---------- + peer_id : ID + The peer identifier whose public key is to be added + pubkey: PublicKey + The public key of the peer + + """ @abstractmethod def add_privkey(self, peer_id: ID, privkey: PrivateKey) -> None: - """add_privkey""" + """ + Adds the private key for a specified peer + + Parameters + ---------- + peer_id : ID + The peer identifier whose private key is to be added + privkey: PrivateKey + The private key of the peer + + """ @abstractmethod def add_key_pair(self, peer_id: ID, key_pair: KeyPair) -> None: - """add_key_pair""" + """ + Adds the key pair for a specified peer + + Parameters + ---------- + peer_id : ID + The peer identifier whose key pair is to be added + key_pair: KeyPair + The key pair of the peer + + """ @abstractmethod def peer_with_keys(self) -> list[ID]: - """peer_with_keys""" + """Returns all the peer IDs stored in the AddrBook""" @abstractmethod def clear_keydata(self, peer_id: ID) -> None: - """clear_keydata""" + """ + Remove all stored keydata for the specified peer. + + Parameters + ---------- + peer_id : ID + The peer identifier whose keys are to be removed. + + """ # -------------------------- metrics interface.py -------------------------- class IMetrics(ABC): - """IMetrics""" + """ + Interface for metrics of peer interaction. + + Provides methods for managing the metrics. + """ @abstractmethod def record_latency(self, peer_id: ID, RTT: float) -> None: - """record_latency""" + """ + Records a new round-trip time (RTT) latency value for the specified peer + using Exponentially Weighted Moving Average (EWMA). + + Parameters + ---------- + peer_id : ID + The identifier of the peer for which latency is being recorded. + + RTT : float + The round-trip time latency value to record. + + """ @abstractmethod def latency_EWMA(self, peer_id: ID) -> float: - """latency_EWMA""" + """ + Returns the current latency value for the specified peer using + Exponentially Weighted Moving Average (EWMA). + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose latency EWMA is to be returned. + + """ @abstractmethod def clear_metrics(self, peer_id: ID) -> None: - """clear_metrics""" + """ + Clears the stored latency metrics for the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose latency metrics are to be cleared. + + """ # -------------------------- protobook interface.py -------------------------- class IProtoBook(ABC): + """ + Interface for a protocol book. + + Provides methods for managing the list of supported protocols. + """ + @abstractmethod def get_protocols(self, peer_id: ID) -> list[str]: - """get_protocols""" + """ + Returns the list of protocols associated with the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose supported protocols are to be returned. + + """ @abstractmethod def add_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: - """add_protocols""" + """ + Adds the given protocols to the specified peer's protocol list. + + Parameters + ---------- + peer_id : ID + The identifier of the peer to which protocols will be added. + + protocols : Sequence[str] + A sequence of protocol strings to add. + + """ @abstractmethod def set_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: - """set_protocols""" + """ + Replaces the existing protocols of the specified peer with the given list. + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose protocols are to be set. + + protocols : Sequence[str] + A sequence of protocol strings to assign. + + """ @abstractmethod def remove_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: - """remove_protocols""" + """ + Removes the specified protocols from the peer's protocol list. + + Parameters + ---------- + peer_id : ID + The identifier of the peer from which protocols will be removed. + + protocols : Sequence[str] + A sequence of protocol strings to remove. + + """ @abstractmethod def supports_protocols(self, peer_id: ID, protocols: Sequence[str]) -> list[str]: - """supports_protocols""" + """ + Returns the list of protocols from the input sequence that the peer supports. + + Parameters + ---------- + peer_id : ID + The identifier of the peer to check for protocol support. + + protocols : Sequence[str] + A sequence of protocol strings to check against the peer's + supported protocols. + + """ @abstractmethod def first_supported_protocol(self, peer_id: ID, protocols: Sequence[str]) -> str: - """first_supported_protocol""" + """ + Returns the first protocol from the input list that the peer supports. + + Parameters + ---------- + peer_id : ID + The identifier of the peer to check for supported protocols. + + protocols : Sequence[str] + A sequence of protocol strings to check. + + Returns + ------- + str + The first matching protocol string, or an empty string + if none are supported. + + """ @abstractmethod def clear_protocol_data(self, peer_id: ID) -> None: - """clear_protocol_data""" + """ + Clears all protocol data associated with the specified peer. + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose protocol data will be cleared. + + """ # -------------------------- peerstore interface.py -------------------------- @@ -582,6 +761,7 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): management, protocol handling, and key storage. """ + # -------METADATA--------- @abstractmethod def get(self, peer_id: ID, key: str) -> Any: """ @@ -624,9 +804,17 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): @abstractmethod def clear_metadata(self, peer_id: ID) -> None: - """clear_metadata""" + """ + Clears the stored latency metrics for the specified peer. - ## + Parameters + ---------- + peer_id : ID + The identifier of the peer whose latency metrics are to be cleared. + + """ + + # --------ADDR-BOOK--------- @abstractmethod def add_addr(self, peer_id: ID, addr: Multiaddr, ttl: int) -> None: """ @@ -700,11 +888,7 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): """ - @abstractmethod - def addr_stream(self, peer_id: ID) -> None: - """addr_stream""" - - ## + # --------KEY-BOOK---------- @abstractmethod def pubkey(self, peer_id: ID) -> PublicKey: """ @@ -808,26 +992,63 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): @abstractmethod def peer_with_keys(self) -> list[ID]: - """peer_with_keys""" + """Returns all the peer IDs stored in the AddrBook""" @abstractmethod def clear_keydata(self, peer_id: ID) -> None: - """clear_keydata""" + """ + Remove all stored keydata for the specified peer. - ## + Parameters + ---------- + peer_id : ID + The peer identifier whose keys are to be removed. + + """ + + # -------METRICS--------- @abstractmethod def record_latency(self, peer_id: ID, RTT: float) -> None: - """record_latency""" + """ + Records a new round-trip time (RTT) latency value for the specified peer + using Exponentially Weighted Moving Average (EWMA). + + Parameters + ---------- + peer_id : ID + The identifier of the peer for which latency is being recorded. + + RTT : float + The round-trip time latency value to record. + + """ @abstractmethod def latency_EWMA(self, peer_id: ID) -> float: - """latency_EWMA""" + """ + Returns the current latency value for the specified peer using + Exponentially Weighted Moving Average (EWMA). + + Parameters + ---------- + peer_id : ID + The identifier of the peer whose latency EWMA is to be returned. + + """ @abstractmethod def clear_metrics(self, peer_id: ID) -> None: - """clear_metrics""" + """ + Clears the stored latency metrics for the specified peer. - ## + Parameters + ---------- + peer_id : ID + The identifier of the peer whose latency metrics are to be cleared. + + """ + + # --------PROTO-BOOK---------- @abstractmethod def get_protocols(self, peer_id: ID) -> list[str]: """ @@ -880,21 +1101,69 @@ class IPeerStore(IPeerMetadata, IAddrBook, IKeyBook, IMetrics, IProtoBook): @abstractmethod def remove_protocols(self, peer_id: ID, protocols: Sequence[str]) -> None: - """remove_protocols""" + """ + Removes the specified protocols from the peer's protocol list. + + Parameters + ---------- + peer_id : ID + The identifier of the peer from which protocols will be removed. + + protocols : Sequence[str] + A sequence of protocol strings to remove. + + """ @abstractmethod def supports_protocols(self, peer_id: ID, protocols: Sequence[str]) -> list[str]: - """supports_protocols""" + """ + Returns the list of protocols from the input sequence that the peer supports. + + Parameters + ---------- + peer_id : ID + The identifier of the peer to check for protocol support. + + protocols : Sequence[str] + A sequence of protocol strings to check against the peer's + supported protocols. + + """ @abstractmethod def first_supported_protocol(self, peer_id: ID, protocols: Sequence[str]) -> str: - """first_supported_protocol""" + """ + Returns the first protocol from the input list that the peer supports. + + Parameters + ---------- + peer_id : ID + The identifier of the peer to check for supported protocols. + + protocols : Sequence[str] + A sequence of protocol strings to check. + + Returns + ------- + str + The first matching protocol string, or an empty string + if none are supported. + + """ @abstractmethod def clear_protocol_data(self, peer_id: ID) -> None: - """clear_protocol_data""" + """ + Clears all protocol data associated with the specified peer. - ## + Parameters + ---------- + peer_id : ID + The identifier of the peer whose protocol data will be cleared. + + """ + + # --------PEER-STORE-------- @abstractmethod def peer_info(self, peer_id: ID) -> PeerInfo: """ @@ -1463,6 +1732,60 @@ class IPeerData(ABC): """ + @abstractmethod + def remove_protocols(self, protocols: Sequence[str]) -> None: + """ + Removes the specified protocols from this peer's list of supported protocols. + + Parameters + ---------- + protocols : Sequence[str] + A sequence of protocol strings to be removed. + + """ + + @abstractmethod + def supports_protocols(self, protocols: Sequence[str]) -> list[str]: + """ + Returns the list of protocols from the input sequence that are supported + by this peer. + + Parameters + ---------- + protocols : Sequence[str] + A sequence of protocol strings to check against this peer's supported + protocols. + + Returns + ------- + list[str] + A list of protocol strings that are supported. + + """ + + @abstractmethod + def first_supported_protocol(self, protocols: Sequence[str]) -> str: + """ + Returns the first protocol from the input list that this peer supports. + + Parameters + ---------- + protocols : Sequence[str] + A sequence of protocol strings to check for support. + + Returns + ------- + str + The first matching protocol, or an empty string if none are supported. + + """ + + @abstractmethod + def clear_protocol_data(self) -> None: + """ + Clears all protocol data associated with this peer. + """ + @abstractmethod def add_addrs(self, addrs: Sequence[Multiaddr]) -> None: """ @@ -1532,6 +1855,12 @@ class IPeerData(ABC): """ + @abstractmethod + def clear_metadata(self) -> None: + """ + Clears all metadata entries associated with this peer. + """ + @abstractmethod def add_pubkey(self, pubkey: PublicKey) -> None: """ @@ -1590,6 +1919,45 @@ class IPeerData(ABC): """ + @abstractmethod + def clear_keydata(self) -> None: + """ + Clears all cryptographic key data associated with this peer, + including both public and private keys. + """ + + @abstractmethod + def record_latency(self, new_latency: float) -> None: + """ + Records a new latency measurement using + Exponentially Weighted Moving Average (EWMA). + + Parameters + ---------- + new_latency : float + The new round-trip time (RTT) latency value to incorporate + into the EWMA calculation. + + """ + + @abstractmethod + def latency_EWMA(self) -> float: + """ + Returns the current EWMA value of the recorded latency. + + Returns + ------- + float + The current latency estimate based on EWMA. + + """ + + @abstractmethod + def clear_metrics(self) -> None: + """ + Clears all latency-related metrics and resets the internal state. + """ + @abstractmethod def update_last_identified(self) -> None: """ diff --git a/libp2p/peer/peerdata.py b/libp2p/peer/peerdata.py index bf45ca23..0d1a2f35 100644 --- a/libp2p/peer/peerdata.py +++ b/libp2p/peer/peerdata.py @@ -115,8 +115,6 @@ class PeerData(IPeerData): """Clear all addresses.""" self.addrs = [] - # TODO! ADDRS_STREAM - # -------METADATA----------- def put_metadata(self, key: str, val: Any) -> None: """ From faeacf686a99bd8a40ed838bc281350d632aabb1 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Wed, 18 Jun 2025 19:34:40 +0530 Subject: [PATCH 08/11] fix typos --- libp2p/peer/peerstore.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/libp2p/peer/peerstore.py b/libp2p/peer/peerstore.py index da18a5f0..e23e014a 100644 --- a/libp2p/peer/peerstore.py +++ b/libp2p/peer/peerstore.py @@ -217,10 +217,6 @@ class PeerStore(IPeerStore): peer_data.clear_addrs() return output - def addr_stream(self, peer_id: ID) -> None: - """addr_stream""" - # TODO! - # -------KEY-BOOK--------- def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: @@ -292,7 +288,7 @@ class PeerStore(IPeerStore): ] def clear_keydata(self, peer_id: ID) -> None: - """Clears all the keys of the peer""" + """Clears the keys of the peer""" peer_data = self.peer_data_map[peer_id] peer_data.clear_keydata() From 51c08de1bce4ae2262002bf0c90d8b0bb8e065c7 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Thu, 3 Jul 2025 18:13:26 +0530 Subject: [PATCH 09/11] test added: clear protocol data --- tests/core/peer/test_peerdata.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/core/peer/test_peerdata.py b/tests/core/peer/test_peerdata.py index 46f9ed5a..49825915 100644 --- a/tests/core/peer/test_peerdata.py +++ b/tests/core/peer/test_peerdata.py @@ -51,6 +51,16 @@ def test_remove_protocols(): assert peer_data.get_protocols() == ["protocol2"] +# Test case when clearing the protocol list: +def test_clear_protocol_data(): + peer_data = PeerData() + protocols: Sequence[str] = ["protocol1", "protocol2"] + peer_data.set_protocols(protocols) + + peer_data.clear_protocol_data() + assert peer_data.get_protocols() == [] + + # Test case when supports protocols: def test_supports_protocols(): peer_data = PeerData() @@ -84,16 +94,6 @@ def test_first_supported_protocol_none(): assert first == "None supported" -# Test case for clearing protocol data -def test_clear_protocol_data(): - peer_data = PeerData() - peer_data.set_protocols(["proto1", "proto2"]) - - peer_data.clear_protocol_data() - - assert peer_data.get_protocols() == [] - - # Test case when adding addresses def test_add_addrs(): peer_data = PeerData() From d1c31483bd02445266396e808035be6d8afc4c7a Mon Sep 17 00:00:00 2001 From: lla-dane Date: Fri, 4 Jul 2025 14:53:44 +0530 Subject: [PATCH 10/11] Implemented addr_stream in the peerstore --- libp2p/peer/peerstore.py | 30 +++++++++++++++++++++++++++ tests/core/peer/test_peerstore.py | 34 +++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/libp2p/peer/peerstore.py b/libp2p/peer/peerstore.py index e23e014a..40cb7893 100644 --- a/libp2p/peer/peerstore.py +++ b/libp2p/peer/peerstore.py @@ -2,6 +2,7 @@ from collections import ( defaultdict, ) from collections.abc import ( + AsyncIterable, Sequence, ) from typing import ( @@ -11,6 +12,8 @@ from typing import ( from multiaddr import ( Multiaddr, ) +import trio +from trio import MemoryReceiveChannel, MemorySendChannel from libp2p.abc import ( IPeerStore, @@ -40,6 +43,7 @@ class PeerStore(IPeerStore): def __init__(self) -> None: self.peer_data_map = defaultdict(PeerData) + self.addr_update_channels: dict[ID, MemorySendChannel[Multiaddr]] = {} def peer_info(self, peer_id: ID) -> PeerInfo: """ @@ -178,6 +182,13 @@ class PeerStore(IPeerStore): peer_data.set_ttl(ttl) peer_data.update_last_identified() + if peer_id in self.addr_update_channels: + for addr in addrs: + try: + self.addr_update_channels[peer_id].send_nowait(addr) + except trio.WouldBlock: + pass # Or consider logging / dropping / replacing stream + def addrs(self, peer_id: ID) -> list[Multiaddr]: """ :param peer_id: peer ID to get addrs for @@ -217,6 +228,25 @@ class PeerStore(IPeerStore): peer_data.clear_addrs() return output + async def addr_stream(self, 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`. + + :param peer_id: The ID of the peer to monitor address updates for. + :return: An async iterator yielding Multiaddr instances as they are added. + """ + send: MemorySendChannel[Multiaddr] + receive: MemoryReceiveChannel[Multiaddr] + + send, receive = trio.open_memory_channel(0) + self.addr_update_channels[peer_id] = send + + async for addr in receive: + yield addr + # -------KEY-BOOK--------- def add_pubkey(self, peer_id: ID, pubkey: PublicKey) -> None: diff --git a/tests/core/peer/test_peerstore.py b/tests/core/peer/test_peerstore.py index b0d8ed81..85fc1863 100644 --- a/tests/core/peer/test_peerstore.py +++ b/tests/core/peer/test_peerstore.py @@ -2,6 +2,7 @@ import time import pytest from multiaddr import Multiaddr +import trio from libp2p.peer.id import ID from libp2p.peer.peerstore import ( @@ -89,3 +90,36 @@ def test_peers(): store.add_addr(ID(b"peer3"), Multiaddr("/ip4/127.0.0.1/tcp/4001"), 10) assert set(store.peer_ids()) == {ID(b"peer1"), ID(b"peer2"), ID(b"peer3")} + + +@pytest.mark.trio +async def test_addr_stream_yields_new_addrs(): + store = PeerStore() + peer_id = ID(b"peer1") + addr1 = Multiaddr("/ip4/127.0.0.1/tcp/4001") + addr2 = Multiaddr("/ip4/127.0.0.1/tcp/4002") + + # 🔧 Pre-initialize peer in peer_data_map + # store.add_addr(peer_id, Multiaddr("/ip4/127.0.0.1/tcp/0"), ttl=1) + + collected = [] + + async def consume_addrs(): + async for addr in store.addr_stream(peer_id): + collected.append(addr) + if len(collected) == 2: + break + + async with trio.open_nursery() as nursery: + nursery.start_soon(consume_addrs) + await trio.sleep(2) # Give time for the stream to start + + store.add_addr(peer_id, addr1, ttl=10) + await trio.sleep(0.2) + store.add_addr(peer_id, addr2, ttl=10) + await trio.sleep(0.2) + + # After collecting expected addresses, cancel the stream + nursery.cancel_scope.cancel() + + assert collected == [addr1, addr2] From b21591f8d591a2563c706139669f176ed9f6b9f5 Mon Sep 17 00:00:00 2001 From: lla-dane Date: Fri, 4 Jul 2025 15:07:12 +0530 Subject: [PATCH 11/11] remove redundants --- tests/core/peer/test_peerstore.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/core/peer/test_peerstore.py b/tests/core/peer/test_peerstore.py index 85fc1863..c5f31767 100644 --- a/tests/core/peer/test_peerstore.py +++ b/tests/core/peer/test_peerstore.py @@ -99,9 +99,6 @@ async def test_addr_stream_yields_new_addrs(): addr1 = Multiaddr("/ip4/127.0.0.1/tcp/4001") addr2 = Multiaddr("/ip4/127.0.0.1/tcp/4002") - # 🔧 Pre-initialize peer in peer_data_map - # store.add_addr(peer_id, Multiaddr("/ip4/127.0.0.1/tcp/0"), ttl=1) - collected = [] async def consume_addrs():