Skip to content

Conversation

jeandemeusy
Copy link
Contributor

@jeandemeusy jeandemeusy commented Jan 14, 2025

The API endpoints GET aliases and GET aliases/:alias have been doubled in this PR, as GET aliases_addresses and GET aliases_addresses/:alias to be able to get peer ETH address from those endpoints.

@jeandemeusy jeandemeusy self-assigned this Jan 14, 2025
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This pull request updates the alias management functionality in the HOPR project by introducing new methods and structures across various components. The version of the hoprd-api package has been updated from "3.10.0" to "3.11.0". New asynchronous functions for retrieving alias addresses have been added to the REST API, along with new routes for these functionalities. Additionally, the Python SDK has been modified to support these changes, enhancing the API's capabilities for managing aliases.

Changes

File Change Summary
hoprd/rest-api/Cargo.toml Version bumped from "3.10.0" to "3.11.0"
hoprd/rest-api/src/alias.rs Added AddressResponse struct, new async functions aliases_addresses and get_alias_address for retrieving alias addresses
hoprd/rest-api/src/lib.rs Added two new API routes for alias address retrieval
sdk/python/api/hopr.py Updated aliases_get_alias method with return_address parameter, added aliases_get_aliases method
sdk/python/api/response_objects.py Added new AliasAddress class for handling address-related API responses
tests/test_integration.py Added TICKET_AGGREGATION_THRESHOLD, enhanced alias-related test assertions

Possibly related PRs

  • Allow PeerId and Address in API calls #6532: The changes in this PR involve modifications to the hoprd/rest-api/src/alias.rs file, which directly relates to the alias management functionality that is also impacted by the changes in the main PR.

Suggested labels

crate:hopr-lib, smart-contracts

Suggested reviewers

  • NumberFour8
  • Teebor-Choka

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jeandemeusy jeandemeusy requested a review from a team January 14, 2025 12:16
@github-actions github-actions bot added dependencies Pull requests that update a dependency file testing Related to tests crate:hoprd-api labels Jan 14, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 in get_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 None
tests/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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ce9f4b and 9e44b02.

⛔ 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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:

  1. Add return type annotation
  2. Remove unnecessary f-strings
  3. 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 as PeerIdResponse 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 on alias is unnecessary as it's being moved into the HashMap.

-                .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 using try_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

📥 Commits

Reviewing files that changed from the base of the PR and between 06fba90 and 5396f0d.

📒 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.

@jeandemeusy jeandemeusy modified the milestone: 2.2.0-rc.1 Jan 14, 2025
@ausias-armesto ausias-armesto added this to the 2.2.0-rc.2 milestone Jan 14, 2025
@Teebor-Choka Teebor-Choka removed this from the 2.2.0-rc.2 milestone Jan 15, 2025
Co-authored-by: Tibor <9529609+Teebor-Choka@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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:

  1. Using try_join_all instead of join_all would provide better error handling for concurrent operations
  2. 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 (returns AliasNotFound) and the HoprIdentifier::new_with error (returns PeerNotFound). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 03057e8 and 36e24a7.

📒 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.

@jeandemeusy jeandemeusy changed the base branch from master to release/singapore January 16, 2025 08:11
@jeandemeusy jeandemeusy merged commit c9bb870 into release/singapore Jan 16, 2025
28 checks passed
@jeandemeusy jeandemeusy deleted the jean/extend-alias-endpoints-to-addresses branch January 16, 2025 15:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
crate:hoprd-api dependencies Pull requests that update a dependency file testing Related to tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

New extra Aliases endpoint should work with Eth address (all: GET, POST and DELETE)
4 participants