-
Notifications
You must be signed in to change notification settings - Fork 23
Expose API for PublicAddresses
#212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 28 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
8502645
identify: Expose API to inject listen addresses
lexnv e452745
tests: Check identify public addresses are propagated
lexnv 0e42027
listen-addr: Add listen address struct to a separate module
lexnv 890df79
listen-addr/tests: Check listen addr interface functionality
lexnv 59668c9
listen-addr: Use a lock guard for custom iteration over the addresses
lexnv 56ed02a
litep2p: Store shared listenAddresses on Litep2p object
lexnv a4bbf06
identify: Use the new interface of public addresses
lexnv f2a1c51
listen-addr: Check listen address contains p2p protocol
lexnv 67b617d
Polish up the API
lexnv 38d8ca3
listen-addr: Register lsiten addresses with adding the local peerID
lexnv 2a45422
Adjust testing to the new interface
lexnv fc0c700
Use ListenAddresses everywhere
lexnv 7f07e9d
listen-addr: Add better documentation
lexnv 794eba5
listen-addr: Add contains and remove partial methods
lexnv 5e9930a
Merge remote-tracking branch 'origin/master' into lexnv/indentify-con…
lexnv e11a996
Rename to ExternalAddresses for clarity
lexnv 09b6fee
Refactor and adjust testing
lexnv c11f468
Merge remote-tracking branch 'origin/master' into lexnv/indentify-con…
lexnv 68c76d2
Apply fmt
lexnv 6161233
Fix cargo doc and clippy
lexnv dacd665
pub-addr: Rename API methods
lexnv 1194a29
Introduce ListenAddresses object
lexnv ba6e198
Use listenAddresses added interface
lexnv e7a7d80
identify: Use user-provided, listen and public addresses
lexnv 9ad762b
manager: Remove transport_manager::register_listen_address
lexnv d0ebcd2
Adjust testing
lexnv 41c1e23
Fix documentation
lexnv fd23d15
address: Introduce insertion error for better reporting
lexnv be8d663
Remove ListenAddresses
lexnv af8fe60
Adjust testing
lexnv 39153f1
Adjust testing
lexnv 6b7b7b1
identify: Remove public addr from list config
lexnv a633b68
Merge branch 'master' into lexnv/indentify-confirmed-addresses
lexnv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| // Copyright 2024 litep2p developers | ||
| // | ||
| // Permission is hereby granted, free of charge, to any person obtaining a | ||
| // copy of this software and associated documentation files (the "Software"), | ||
| // to deal in the Software without restriction, including without limitation | ||
| // the rights to use, copy, modify, merge, publish, distribute, sublicense, | ||
| // and/or sell copies of the Software, and to permit persons to whom the | ||
| // Software is furnished to do so, subject to the following conditions: | ||
| // | ||
| // The above copyright notice and this permission notice shall be included in | ||
| // all copies or substantial portions of the Software. | ||
| // | ||
| // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
| // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | ||
| // DEALINGS IN THE SOFTWARE. | ||
|
|
||
| use std::{collections::HashSet, sync::Arc}; | ||
|
|
||
| use multiaddr::{Multiaddr, Protocol}; | ||
| use parking_lot::RwLock; | ||
|
|
||
| use crate::PeerId; | ||
|
|
||
| /// Set of the public addresses of the local node. | ||
| /// | ||
| /// The format of the addresses stored in the set contain the local peer ID. | ||
| /// This requirement is enforced by the [`PublicAddresses::add_address`] method, | ||
| /// that will add the local peer ID to the address if it is missing. | ||
| /// | ||
| /// # Note | ||
| /// | ||
| /// - The addresses are reported to the identify protocol and are used by other nodes | ||
| /// to establish a connection with the local node. | ||
| /// | ||
| /// - Users must ensure that the addresses are reachable from the network. | ||
| #[derive(Debug, Clone)] | ||
| pub struct PublicAddresses { | ||
| pub(crate) inner: Arc<RwLock<HashSet<Multiaddr>>>, | ||
| local_peer_id: PeerId, | ||
| } | ||
|
|
||
| impl PublicAddresses { | ||
| /// Creates new [`PublicAddresses`] from the given peer ID. | ||
| pub(crate) fn new(local_peer_id: PeerId) -> Self { | ||
| Self { | ||
| inner: Arc::new(RwLock::new(HashSet::new())), | ||
| local_peer_id, | ||
| } | ||
| } | ||
|
|
||
| /// Add a public address to the list of addresses. | ||
| /// | ||
| /// The address must contain the local peer ID, otherwise an error is returned. | ||
| /// In case the address does not contain any peer ID, it will be added. | ||
| /// | ||
| /// Returns true if the address was added, false if it was already present. | ||
| pub fn add_address(&self, address: Multiaddr) -> Result<bool, InsertionError> { | ||
| let address = ensure_local_peer(address, self.local_peer_id)?; | ||
| Ok(self.inner.write().insert(address)) | ||
| } | ||
|
|
||
| /// Remove the exact public address. | ||
| /// | ||
| /// The provided address must contain the local peer ID. | ||
| pub fn remove_address(&self, address: &Multiaddr) -> bool { | ||
| self.inner.write().remove(address) | ||
| } | ||
|
|
||
| /// Returns a vector of the available listen addresses. | ||
| pub fn get_addresses(&self) -> Vec<Multiaddr> { | ||
| self.inner.read().iter().cloned().collect() | ||
| } | ||
| } | ||
|
|
||
| /// Set of the addresses the local node listens on. | ||
| /// | ||
| /// The format of the addresses stored in the set contain the local peer ID. | ||
| /// This requirement is enforced by the [`ListenAddresses::add_address`] method. | ||
| /// | ||
| /// The listen addresses are populated during the construction of the Litep2p object. | ||
| #[derive(Debug, Clone)] | ||
| pub struct ListenAddresses { | ||
| pub(crate) inner: Arc<RwLock<HashSet<Multiaddr>>>, | ||
| local_peer_id: PeerId, | ||
| } | ||
|
|
||
| impl ListenAddresses { | ||
| /// Creates new [`ListenAddresses`] from the given peer ID. | ||
| pub(crate) fn new(local_peer_id: PeerId) -> Self { | ||
| Self { | ||
| inner: Arc::new(RwLock::new(HashSet::new())), | ||
| local_peer_id, | ||
| } | ||
| } | ||
| /// Add a listen address to the list of addresses. | ||
| /// | ||
| /// Returns true if the address was added, false if it was already present. | ||
| pub fn add_address(&self, address: Multiaddr) -> Result<bool, InsertionError> { | ||
| let address = ensure_local_peer(address, self.local_peer_id)?; | ||
| Ok(self.inner.write().insert(address)) | ||
| } | ||
|
|
||
| /// Remove the listen address. | ||
| pub fn remove_address(&self, address: &Multiaddr) -> bool { | ||
| self.inner.write().remove(address) | ||
| } | ||
|
|
||
| /// Returns a vector of the available listen addresses. | ||
| pub fn get_addresses(&self) -> Vec<Multiaddr> { | ||
| self.inner.read().iter().cloned().collect() | ||
| } | ||
| } | ||
|
|
||
| /// Check if the address contains the local peer ID. | ||
| /// | ||
| /// If the address does not contain any peer ID, it will be added. | ||
| fn ensure_local_peer( | ||
| mut address: Multiaddr, | ||
| local_peer_id: PeerId, | ||
| ) -> Result<Multiaddr, InsertionError> { | ||
| if address.is_empty() { | ||
| return Err(InsertionError::EmptyAddress); | ||
| } | ||
|
|
||
| // Verify the peer ID from the address corresponds to the local peer ID. | ||
| if let Some(peer_id) = PeerId::try_from_multiaddr(&address) { | ||
| if peer_id != local_peer_id { | ||
| return Err(InsertionError::DifferentPeerId); | ||
| } | ||
| } else { | ||
| address.push(Protocol::P2p(local_peer_id.into())); | ||
| } | ||
|
|
||
| Ok(address) | ||
| } | ||
|
|
||
| /// The error returned when an address cannot be inserted. | ||
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| pub enum InsertionError { | ||
| /// The address is empty. | ||
| EmptyAddress, | ||
| /// The address contains a different peer ID than the local peer ID. | ||
| DifferentPeerId, | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use std::str::FromStr; | ||
|
|
||
| #[test] | ||
| fn add_remove_contains() { | ||
| let peer_id = PeerId::random(); | ||
| let addresses = PublicAddresses::new(peer_id); | ||
| let address = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); | ||
| let peer_address = Multiaddr::from_str("/dns/domain1.com/tcp/30333") | ||
| .unwrap() | ||
| .with(Protocol::P2p(peer_id.into())); | ||
|
|
||
| assert!(!addresses.get_addresses().contains(&address)); | ||
|
|
||
| assert!(addresses.add_address(address.clone()).unwrap()); | ||
| // Adding the address a second time returns Ok(false). | ||
| assert!(!addresses.add_address(address.clone()).unwrap()); | ||
|
|
||
| assert!(!addresses.get_addresses().contains(&address)); | ||
| assert!(addresses.get_addresses().contains(&peer_address)); | ||
|
|
||
| addresses.remove_address(&peer_address); | ||
| assert!(!addresses.get_addresses().contains(&peer_address)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn get_addresses() { | ||
| let peer_id = PeerId::random(); | ||
| let addresses = PublicAddresses::new(peer_id); | ||
| let address1 = Multiaddr::from_str("/dns/domain1.com/tcp/30333").unwrap(); | ||
| let address2 = Multiaddr::from_str("/dns/domain2.com/tcp/30333").unwrap(); | ||
| // Addresses different than the local peer ID are ignored. | ||
| let address3 = Multiaddr::from_str( | ||
| "/dns/domain2.com/tcp/30333/p2p/12D3KooWSueCPH3puP2PcvqPJdNaDNF3jMZjtJtDiSy35pWrbt5h", | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| assert!(addresses.add_address(address1.clone()).unwrap()); | ||
| assert!(addresses.add_address(address2.clone()).unwrap()); | ||
| addresses.add_address(address3.clone()).unwrap_err(); | ||
|
|
||
| let addresses = addresses.get_addresses(); | ||
| assert_eq!(addresses.len(), 2); | ||
| assert!(addresses.contains(&address1.with(Protocol::P2p(peer_id.into())))); | ||
| assert!(addresses.contains(&address2.with(Protocol::P2p(peer_id.into())))); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.