-
Notifications
You must be signed in to change notification settings - Fork 98
Extension alias endpoints to return ETH addresses in addition to PeerIds #6767
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
Extension alias endpoints to return ETH addresses in addition to PeerIds #6767
Conversation
Important Review skippedReview was skipped due to path filters ⛔ Files ignored due to path filters (1)
CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including You can disable this status message by setting the 📝 WalkthroughWalkthroughThis pull request updates the alias management functionality in the HOPR project by introducing new methods and structures across various components. The version of the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (3)
hoprd/rest-api/src/alias.rs (1)
253-306
: Simplify error handling inget_alias_address
.The function has multiple unwrap operations that could be simplified using the
?
operator.Consider this refactor:
- let alias = urlencoding::decode(&alias); - - if alias.is_err() { - return (StatusCode::BAD_REQUEST, ApiErrorStatus::InvalidInput).into_response(); - } - - let alias = alias.unwrap().into_owned(); + let alias = urlencoding::decode(&alias) + .map_err(|_| (StatusCode::BAD_REQUEST, ApiErrorStatus::InvalidInput))? + .into_owned();sdk/python/api/hopr.py (1)
160-172
: Consider simplifying the conditional logic.The function could be more concise while maintaining readability.
Consider using a ternary operator:
- if return_address: - is_ok, response = await self.__call_api(HTTPMethod.GET, "aliases_addresses") - return response if is_ok else None - else: - is_ok, response = await self.__call_api(HTTPMethod.GET, "aliases") - return response if is_ok else None + endpoint = "aliases_addresses" if return_address else "aliases" + is_ok, response = await self.__call_api(HTTPMethod.GET, endpoint) + return response if is_ok else Nonetests/test_integration.py (1)
95-98
: LGTM! Consider adding a docstring to clarify the test's extended scope.The new assertions correctly verify the address retrieval functionality for both individual alias and aliases list endpoints. The lowercase address validation is a good practice for Ethereum address handling.
Consider adding a docstring to document that this test now verifies both PeerId and ETH address retrieval:
async def test_hoprd_should_be_able_to_remove_existing_aliases(peer: str, swarm7: dict[str, Node]): + """ + Test alias management functionality including: + - Setting and removing aliases + - Retrieving PeerIds for aliases + - Retrieving ETH addresses for aliases (in lowercase) + """
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
Cargo.lock
is excluded by!**/*.lock
📒 Files selected for processing (6)
hoprd/rest-api/Cargo.toml
(1 hunks)hoprd/rest-api/src/alias.rs
(4 hunks)hoprd/rest-api/src/lib.rs
(2 hunks)sdk/python/api/hopr.py
(3 hunks)sdk/python/api/response_objects.py
(1 hunks)tests/test_integration.py
(2 hunks)
✅ Files skipped from review due to trivial changes (1)
- hoprd/rest-api/Cargo.toml
🔇 Additional comments (5)
sdk/python/api/response_objects.py (1)
69-70
: LGTM!The
AliasAddress
class follows the established pattern of response objects in this file and correctly maps the address field.hoprd/rest-api/src/alias.rs (1)
30-40
: LGTM!The
AddressResponse
struct is well-defined with proper serialization attributes and documentation.hoprd/rest-api/src/lib.rs (1)
284-284
: LGTM!The new routes are properly integrated into the router configuration and follow the existing pattern.
Also applies to: 288-288
sdk/python/api/hopr.py (1)
33-33
: LGTM!The import follows the alphabetical order of the existing imports.
tests/test_integration.py (1)
23-23
: LGTM!The addition of
TICKET_AGGREGATION_THRESHOLD
to the imports is correct and properly grouped with other imports from utils.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (6)
sdk/python/api/hopr.py (2)
160-168
: Enhance type safety and optimize string usage.A few improvements can be made to this method:
- Add return type annotation
- Remove unnecessary f-strings
- Enhance docstring with return type information
- async def aliases_get_aliases(self, return_address: bool = False): + async def aliases_get_aliases(self, return_address: bool = False) -> Optional[list[Union[Alias, AliasAddress]]]: """ Returns all aliases. :param: return_address: bool. If true, returns addresses instead of peer_ids - :return: aliases: list + :return: List of Alias or AliasAddress objects, or None if the request fails """ - endpoint = f"aliases_addresses" if return_address else f"aliases" + endpoint = "aliases_addresses" if return_address else "aliases" is_ok, response = await self.__call_api(HTTPMethod.GET, endpoint) return response if is_ok else None🧰 Tools
🪛 Ruff (0.8.2)
166-166: f-string without any placeholders
Remove extraneous
f
prefix(F541)
166-166: f-string without any placeholders
Remove extraneous
f
prefix(F541)
170-179
: Update docstring to reflect all parameters and return types.The implementation looks good, but the docstring needs to be updated to include the
return_address
parameter and clarify the return types.async def aliases_get_alias(self, alias: str, return_address: bool = False) -> Optional[Union[Alias, AliasAddress]]: """ - Returns the peer id recognized by the node. - :return: alias: Alias + Returns the peer id or ETH address recognized by the node. + :param alias: The alias to look up + :param return_address: If True, returns ETH address instead of peer id + :return: Alias or AliasAddress object, or None if not found """hoprd/rest-api/src/alias.rs (4)
31-41
: Struct definition looks good but consider improving documentation.The
AddressResponse
struct follows the same pattern asPeerIdResponse
and uses proper serialization attributes. However, consider adding documentation comments to describe the purpose and usage of this struct.Add documentation comments:
+/// Response struct for endpoints returning ETH addresses. +/// Contains a single field representing the ETH address in the HOPR network. #[serde_as] #[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
117-120
: Optimize memory usage by avoiding unnecessary clone.The
clone()
operation onalias
is unnecessary as it's being moved into theHashMap
.- .map(|alias| (alias.alias.clone(), alias.peer_id.clone())) + .map(|alias| (alias.alias, alias.peer_id))
137-141
: Improve error handling in parallel operations.Using
join_all
means errors in individual futures are silently converted to error strings. Consider usingtry_join_all
to handle errors more gracefully.- let aliases_addresses = futures::future::join_all(aliases_addresses_futures) + let aliases_addresses = futures::future::try_join_all(aliases_addresses_futures) .await + .unwrap_or_else(|e| vec![]) // Handle errors appropriately .into_iter() .collect::<HashMap<_, _>>();
286-303
: Consider reducing nesting and extracting common logic.The nested match expressions make the code harder to follow. Consider extracting the peer resolution logic into a separate function since it's used in multiple places.
Extract the peer resolution logic:
async fn resolve_peer_address( entry: String, hopr: Arc<Hopr>, ) -> Result<Address, (StatusCode, ApiErrorStatus)> { let peer_or_address = PeerOrAddress::from_str(entry.as_str()) .map_err(|_| (StatusCode::NOT_FOUND, ApiErrorStatus::AliasNotFound))?; let destination = HoprIdentifier::new_with(peer_or_address, hopr.peer_resolver()) .await .map_err(|_| (StatusCode::BAD_REQUEST, ApiErrorStatus::PeerNotFound))?; Ok(destination.address) }Then simplify the main function:
match state.hoprd_db.resolve_alias(alias.clone()).await { Ok(Some(entry)) => { - let peer_or_address = match PeerOrAddress::from_str(entry.as_str()) { - Ok(destination) => destination, - Err(_) => return (StatusCode::NOT_FOUND, ApiErrorStatus::AliasNotFound).into_response(), - }; - - match HoprIdentifier::new_with(peer_or_address, hopr.peer_resolver()).await { - Ok(destination) => ( - StatusCode::OK, - Json(AddressResponse { - address: destination.address, - }), - ) - .into_response(), - Err(_) => (StatusCode::BAD_REQUEST, ApiErrorStatus::PeerNotFound).into_response(), - } + match resolve_peer_address(entry, hopr).await { + Ok(address) => ( + StatusCode::OK, + Json(AddressResponse { address }), + ).into_response(), + Err(response) => response.into_response(), + } }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
hoprd/rest-api/src/alias.rs
(4 hunks)sdk/python/api/hopr.py
(3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
sdk/python/api/hopr.py
166-166: f-string without any placeholders
Remove extraneous f
prefix
(F541)
166-166: f-string without any placeholders
Remove extraneous f
prefix
(F541)
⏰ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: hoprd / docker
- GitHub Check: hopli / docker
- GitHub Check: tests-smoke-websocket
- GitHub Check: Docs / Rust docs
- GitHub Check: tests-smart-contracts
- GitHub Check: tests-unit
- GitHub Check: tests-unit-nightly
- GitHub Check: Linter
🔇 Additional comments (1)
sdk/python/api/hopr.py (1)
33-33
: LGTM! Clean import addition.The
AliasAddress
import is correctly placed and follows the alphabetical ordering convention.
Co-authored-by: Tibor <9529609+Teebor-Choka@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
hoprd/rest-api/src/alias.rs (4)
94-147
: Consider improving error handling and concurrency.The implementation could be enhanced in several ways:
- Using
try_join_all
instead ofjoin_all
would provide better error handling for concurrent operations- Error messages could be more structured instead of using string conversions
Consider applying these improvements:
- let aliases_addresses = futures::future::join_all(aliases_addresses_futures) + let aliases_addresses = futures::future::try_join_all(aliases_addresses_futures) .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, ApiErrorStatus::from(e)))? .into_iter() .collect::<HashMap<_, _>>();- Err(_) => return (alias, ApiErrorStatus::PeerNotFound.to_string()), + Err(e) => return Err(ApiErrorStatus::from(e)),
117-121
: Consider optimizing database operations.The code duplicates the alias retrieval logic from the
aliases
function. Consider extracting this common functionality into a shared helper function to improve maintainability.Example refactor:
async fn get_alias_map(db: &impl HoprdDbAliasesOperations) -> Result<HashMap<String, String>, DbError> { let aliases = db.get_aliases().await?; Ok(aliases .into_iter() .map(|alias| (alias.alias.clone(), alias.peer_id.clone())) .collect()) }
288-291
: Improve error handling consistency.The error handling differs between the
PeerOrAddress::from_str
error (returnsAliasNotFound
) and theHoprIdentifier::new_with
error (returnsPeerNotFound
). Consider using consistent error types for similar failure cases.- Err(_) => return (StatusCode::NOT_FOUND, ApiErrorStatus::AliasNotFound).into_response(), + Err(_) => return (StatusCode::BAD_REQUEST, ApiErrorStatus::PeerNotFound).into_response(),Also applies to: 293-302
94-94
: Maintain consistent TODO comment format.The deprecation comments should follow a consistent format. Consider using the same format as the existing functions:
-// TODO(deprecated, will be removed in v3.0) Get each previously set alias and its corresponding ETH address as a hashmap. +/// (deprecated, will be removed in v3.0) Get each previously set alias and its corresponding ETH address as a hashmap.Also applies to: 254-254
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
hoprd/rest-api/src/alias.rs
(4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: hoprd / docker
- GitHub Check: hopli / docker
- GitHub Check: Docs / Rust docs
- GitHub Check: tests-unit-nightly
- GitHub Check: tests-unit
- GitHub Check: tests-smart-contracts
- GitHub Check: tests-smoke-websocket
- GitHub Check: Linter
🔇 Additional comments (1)
hoprd/rest-api/src/alias.rs (1)
31-41
: LGTM! Well-structured response type.The
AddressResponse
struct is well-defined with appropriate serialization attributes and documentation.
The API endpoints
GET aliases
andGET aliases/:alias
have been doubled in this PR, asGET aliases_addresses
andGET aliases_addresses/:alias
to be able to get peer ETH address from those endpoints.