Skip to content

Conversation

@NumberFour8 NumberFour8 added this to the 3.0.0 milestone Jan 30, 2025
@NumberFour8 NumberFour8 requested a review from a team January 30, 2025 11:28
@NumberFour8 NumberFour8 self-assigned this Jan 30, 2025
@NumberFour8 NumberFour8 marked this pull request as ready for review January 30, 2025 11:29
Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

📝 Walkthrough

Walkthrough

This pull request introduces comprehensive changes across multiple components of the HOPR project, focusing on enhancing network configuration, metrics, and protocol operations. The modifications include adding new methods for retrieving network parameters like minimum ticket prices and winning probabilities, updating configuration handling for ticket pricing, introducing new metrics for indexer synchronization, and refining error handling and validation processes.

Changes

File Change Summary
METRICS.md Added new metric hopr_indexer_data_source to track Indexer data source
README.md Added new environment variable HOPR_TEST_DISABLE_CHECKS
chain/api/Cargo.toml Updated package name to "chain-api" and version to "0.4.0"
chain/api/src/lib.rs Added methods get_minimum_winning_probability and get_minimum_ticket_price
chain/indexer/src/block.rs Added new metric METRIC_INDEXER_SYNC_SOURCE, enhanced fast sync logic
chain/rpc/Cargo.toml Updated version to "0.4.0" and added hopr-internal-types dependency
chain/rpc/src/lib.rs Added methods get_minimum_network_winning_probability and get_minimum_network_ticket_price
db/api/src/protocol.rs Added methods for retrieving network winning probability and ticket price
db/sql/src/protocol.rs Added methods for retrieving network winning probability and ticket price
hopr/hopr-lib/src/lib.rs Added configuration validation for ticket price and winning probability
hoprd/hoprd/src/main.rs Added logging for HOPR_TEST_DISABLE_CHECKS environment variable
transport/protocol/src/config.rs Modified ProtocolConfig to support optional ticket pricing parameters
transport/protocol/src/msg/processor.rs Enhanced packet processing with dynamic ticket pricing and winning probability determination

Sequence Diagram

sequenceDiagram
    participant Node
    participant ChainAPI
    participant RPCOperations
    participant Indexer
    participant NetworkOracle

    Node->>ChainAPI: Get Minimum Winning Probability
    ChainAPI->>RPCOperations: Request Network Parameters
    RPCOperations->>NetworkOracle: Fetch Current Values
    NetworkOracle-->>RPCOperations: Return Minimum Ticket Price & Winning Probability
    RPCOperations-->>ChainAPI: Provide Network Parameters
    ChainAPI-->>Node: Validate Configuration
Loading

Possibly related PRs

Suggested Labels

status:in-review, crate:chain-api, crate:chain-rpc, crate:hoprd-api, crate:core-network

Suggested Reviewers

  • Teebor-Choka
  • tolbrino

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.

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: 5

🧹 Nitpick comments (15)
transport/protocol/src/msg/processor.rs (3)

199-210: Potentially add caching or concurrency safeguards for network ticket price retrieval.
This method is straightforward but each call queries the DB. If called frequently, performance might degrade. Consider caching the result briefly, or ensure it’s not called repeatedly in tight loops.


324-326: Check if mixer usage is relevant for tickets.
We see mixer: MixerConfig is placed between the new fields for ticket handling. If it’s unrelated, consider grouping or reorganizing references for clarity.


330-335: PacketInteractionConfig::new readability.
Configuration struct builders are concise, but ensure that default/fallback values or disclaimers are well documented. Verify that the method usage is tested, especially for the scenario where outgoing_ticket_win_prob or outgoing_ticket_price is None.

Also applies to: 340-340

db/sql/src/protocol.rs (2)

359-359: Visibility of minimum_ticket_price in ticket validation.
Ensure an understandable error message is always raised to clarify how the minimum price is determined if validation fails.


380-383: Clarify potential path position mismatch.
The comment warns that the price might exceed the path-based minimum. Provide an explicit log statement when that scenario occurs to aid debugging.

chain/indexer/src/block.rs (4)

196-196: Reset index DB under fast sync scenario.
Double-check no leftover partial data that might cause conflicts down the line (like in a separate table).


271-271: Dynamic sync progress updates.
Use of .then(...) for each block is neat. If block volume is large, confirm that it doesn’t degrade performance. Possibly batch.

Also applies to: 276-276, 278-278


506-506: calculate_sync_process method signature update.
Replacing next_block_to_process with start_block clarifies the reference baseline. Ensure that call sites have updated logic for partial sync.

Also applies to: 514-514, 518-518, 519-519, 520-520


530-546: Sync progress logging and completeness check.
• The approach for computing progress is readable.
• Consider specifying a maximum threshold for progress to avoid floating inaccuracies, e.g. 1.01 if head changes quickly.
• Confirm that the final notification (via tx.try_send(())) is indeed consumed.

Also applies to: 563-566

chain/rpc/src/lib.rs (2)

374-380: LGTM! Consider adding more detailed documentation.

The new methods for retrieving network parameters are well-structured. Consider enhancing the documentation with:

  • Expected value ranges
  • Error conditions
  • Usage examples
 /// Retrieves the minimum incoming ticket winning probability by directly
 /// calling the network's winning probability oracle.
+///
+/// # Returns
+/// A floating-point value between 0.0 and 1.0 representing the probability.
+///
+/// # Errors
+/// Returns a `ContractError` if the call to the oracle fails.
+///
+/// # Example
+/// ```rust
+/// let min_prob = rpc.get_minimum_network_winning_probability().await?;
+/// assert!(min_prob >= 0.0 && min_prob <= 1.0);
+/// ```
 async fn get_minimum_network_winning_probability(&self) -> Result<f64>;

 /// Retrieves the minimum ticket prices by directly calling the network's
 /// ticket price oracle.
+///
+/// # Returns
+/// A `Balance` representing the minimum ticket price in HOPR tokens.
+///
+/// # Errors
+/// Returns a `ContractError` if the call to the oracle fails.
+///
+/// # Example
+/// ```rust
+/// let min_price = rpc.get_minimum_network_ticket_price().await?;
+/// ```
 async fn get_minimum_network_ticket_price(&self) -> Result<Balance>;

385-385: Documentation improvements: Clarify method descriptions.

The method descriptions have been updated to be more precise, but they could be even clearer.

-/// Retrieves information of the given node module's target.
+/// Retrieves information about the target configuration for the specified node module.

-/// Retrieves the safe address of the given node address from the registry.
+/// Retrieves the associated safe address for the specified node address from the registry.

-/// Retrieves the target address of the node module.
+/// Retrieves the current target address configured for the node module.

Also applies to: 388-388, 391-391

sdk/python/api/hopr.py (1)

559-559: Make the sleep delay configurable.

The hardcoded 0.5-second delay should be configurable to allow for different rate-limiting requirements in various environments.

+# At the beginning of the file
+DEFAULT_URL_CHECK_DELAY = 0.5  # seconds
+
+class HoprdAPI:
+    def __init__(self, url: str, token: str, url_check_delay: float = DEFAULT_URL_CHECK_DELAY):
+        self.host = url
+        self.headers = {"Authorization": f"Bearer {token}"}
+        self.prefix = "/api/v3/"
+        self.url_check_delay = url_check_delay

     @classmethod
     async def is_url_returning_200(cls, url, timeout):
         async def check_url(""):
             ready = False
             async with aiohttp.ClientSession() as s:
                 while not ready:
                     try:
                         ready = (await s.get(url, timeout=0.3)).status == 200
-                        await asyncio.sleep(0.5)
+                        await asyncio.sleep(cls.url_check_delay)
                     except Exception:
                         await asyncio.sleep(0.2)
hoprd/hoprd/src/main.rs (1)

151-153: LGTM! Consider documenting the affected safety checks.

The implementation is clean and follows Rust idioms. The warning message clearly indicates the test-only nature of this feature.

Consider adding a code comment to document which specific safety checks are disabled when this environment variable is set (e.g., minimum winning probability check).

hopr/hopr-lib/src/lib.rs (2)

647-656: LGTM! Consider adding a debug log for successful validation.

The ticket price validation logic is correct and the error message is descriptive. Consider adding a debug log when validation passes to help with troubleshooting.

Add a debug log after successful validation:

 if configured_ticket_price.is_some_and(|c| c < network_min_ticket_price) {
     return Err(HoprLibError::ChainApi(HoprChainError::Api(format!(
         "configured outgoing ticket price is lower than the network minimum ticket price: {configured_ticket_price:?} < {network_min_ticket_price}"
     ))));
 }
+debug!(?configured_ticket_price, ?network_min_ticket_price, "Ticket price validation passed");

658-668: Extract environment variable check into a constant.

The winning probability validation logic is correct, but the environment variable handling could be improved for better maintainability.

Consider these improvements:

  1. Define the environment variable name as a constant:
const DISABLE_CHECKS_ENV_VAR: &str = "HOPR_TEST_DISABLE_CHECKS";
  1. Extract the check into a function:
fn are_checks_disabled() -> bool {
    std::env::var(DISABLE_CHECKS_ENV_VAR).is_ok_and(|v| v.to_lowercase() == "true")
}

Then update the validation:

-if !std::env::var("HOPR_TEST_DISABLE_CHECKS").is_ok_and(|v| v.to_lowercase() == "true")
+if !are_checks_disabled()
     && configured_win_prob.is_some_and(|c| c < network_min_win_prob)
 {
     return Err(HoprLibError::ChainApi(HoprChainError::Api(format!(
         "configured outgoing ticket winning probability is lower than the network minimum winning probability: {configured_win_prob:?} < {network_min_win_prob}"
     ))));
 }
+debug!(?configured_win_prob, ?network_min_win_prob, "Winning probability validation passed");
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9e01312 and d8224f0.

📒 Files selected for processing (21)
  • METRICS.md (1 hunks)
  • README.md (1 hunks)
  • chain/api/Cargo.toml (1 hunks)
  • chain/api/src/lib.rs (1 hunks)
  • chain/indexer/src/block.rs (9 hunks)
  • chain/rpc/Cargo.toml (2 hunks)
  • chain/rpc/src/lib.rs (1 hunks)
  • chain/rpc/src/rpc.rs (2 hunks)
  • crypto/packet/src/validation.rs (5 hunks)
  • db/api/src/protocol.rs (3 hunks)
  • db/sql/src/protocol.rs (10 hunks)
  • hopr/hopr-lib/src/lib.rs (2 hunks)
  • hoprd/hoprd/src/main.rs (1 hunks)
  • sdk/barebone.cfg.yaml (1 hunks)
  • sdk/python/api/hopr.py (1 hunks)
  • sdk/python/localcluster/node.py (1 hunks)
  • transport/api/src/lib.rs (2 hunks)
  • transport/network/src/config.rs (4 hunks)
  • transport/protocol/Cargo.toml (0 hunks)
  • transport/protocol/src/config.rs (1 hunks)
  • transport/protocol/src/msg/processor.rs (4 hunks)
💤 Files with no reviewable changes (1)
  • transport/protocol/Cargo.toml
✅ Files skipped from review due to trivial changes (3)
  • sdk/barebone.cfg.yaml
  • chain/api/Cargo.toml
  • sdk/python/localcluster/node.py
🧰 Additional context used
🪛 LanguageTool
METRICS.md

[uncategorized] ~68-~68: Loose punctuation mark.
Context: ...r checksum. - hopr_indexer_data_source: Current data source of the Indexer, key...

(UNLIKELY_OPENING_PUNCTUATION)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: tests-smoke-websocket
  • GitHub Check: tests-smart-contracts
  • GitHub Check: Linter
🔇 Additional comments (38)
transport/protocol/src/msg/processor.rs (3)

85-86: Ensure robust error propagation in send method [outgoing ticket parameters].
Both the outgoing win probability and ticket price are determined dynamically here. While this approach is flexible, consider:
• Logging or capturing context in case determine_actual_outgoing_ticket_price() fails.
• Handling edge cases (e.g. zero or negative ticket price, though presumably disallowed) more explicitly.


118-119: Symmetrical logic in recv method [outgoing ticket parameters].
The same dynamic retrieval from determine_actual_outgoing_win_prob() and determine_actual_outgoing_ticket_price() is used here. Verify that the logic matches the intended behavior for forwarding or finalizing tickets.


212-229: Fallback logic for network winning probability.
The fallback to DEFAULT_OUTGOING_TICKET_WIN_PROB is convenient but can mask configuration errors if the network probability is expected. Ensure that this silent defaulting aligns with the product requirements.

db/sql/src/protocol.rs (8)

12-12: Check necessity of Mul and Sub imports.
These traits seem required for the new arithmetic logic but confirm no redundancy or overshadowing.


149-155: Error handling in get_network_winning_probability.
Currently returning a direct Ok(...) wrapping the DB fetch, which might throw an error for missing data. Confirm if the DB error context is sufficient for debugging.


170-170: Added parameter outgoing_ticket_price.
The signature expansion looks consistent with the updated design. Double-check that all call sites of to_send(...) now provide a valid Balance.


190-190: Ticket creation decision comment.
The comment clarifies the transition from zero-hop to multi-hop logic. This is good for maintainability.


201-201: Passing outgoing_ticket_price to create_multihop_ticket.
Confirm that each multi-hop scenario uses the same price logic. If different segments of the route have distinct prices, consider clarifying or offering a per-hop approach.


386-386: Zero-hop vs multi-hop logic consistency.
Confirm that the zero-hop logic never inadvertently uses an outdated or stale price. If zero-hop tickets can still rely on outgoing_ticket_price, consider a uniform code path to minimize duplication.


471-473: Parameter naming consistency.
current_path_pos and winning_prob read clearly, but ensure naming in invocation sites is consistent and not reversed or confused with final path pos.


475-476: Check concurrency in channel retrieval.
get_channel_by_parties is presumably thread-safe or properly synchronized. If multiple tasks run this method concurrently, confirm the DB handles it gracefully.

chain/indexer/src/block.rs (7)

1-1: FutureExt usage.
The import of FutureExt is valid for chaining combinators like .then(), .map(), etc. Confirm no overshadowing with older crates.


23-44: New or revised metrics declarations.
All metrics appear well-labeled with proper descriptions. Confirm that the new multi-gauge (METRIC_INDEXER_SYNC_SOURCE) is updated consistently if fallback or manual DB corrections occur.


150-157: Chain head update upon startup.
Log statements are good. Confirm if the block number might be unavailable or behind a rate-limited RPC. Possibly handle partial failures gracefully.


167-174: Introduce FastSyncMode enum.
Solid approach for clarifying the fast-sync states. The partial equality check in if FastSyncMode::None != ... is easy to read.


179-179: Continuation scenario log line.
Resuming fast sync on a partially indexed DB is a corner case. Perhaps add a check to ensure no conflict arises from older logs.


233-234: Building RPC indexer background process.
The toggle between fast-sync and RPC indexing is clear. Good use of concurrency to handle logs.


255-264: Switching sync source metrics after fast sync.
This ensures the METRIC_INDEXER_SYNC_SOURCE gauge transitions from fast-sync to RPC. Great approach for providing clarity in telemetry.

transport/protocol/src/config.rs (2)

12-14: LGTM! Clear documentation for the optional winning probability.

The comment clearly explains that the network value will be used if not set.


15-17: LGTM! Well-structured ticket price configuration.

The new field is properly configured with:

  • Optional type to allow fallback to network value
  • Correct serialization handling using serde_as
  • Clear documentation
db/api/src/protocol.rs (3)

21-22: LGTM! Clear method for network winning probability.

The method signature and return type are appropriate for the operation.


24-25: LGTM! Well-defined method for network ticket price.

The method signature and return type align with the configuration changes.


33-34: Verify error handling for the new ticket price parameter.

The ticket price parameter has been added to both to_send and from_recv methods. Ensure proper error handling is implemented for invalid ticket prices in the implementations.

Also applies to: 45-46

✅ Verification successful

Proper error handling confirmed for ticket price parameter

The implementation includes comprehensive validation and error handling for ticket prices:

  • Validates against missing ticket prices in chain data
  • Enforces minimum acceptable prices based on node position
  • Includes proper error handling for arithmetic operations
  • Validates within channel operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for implementations to verify error handling
ast-grep --pattern 'impl$$$HoprDbProtocolOperations$$$for$$$where$$$
{
  $$$
  async fn to_send($$$) -> Result<$$$, $$$> {
    $$$
  }
  $$$
}'

Length of output: 145


Script:

#!/bin/bash
# First, try to find implementations with a simpler pattern
ast-grep --pattern 'impl $$$HoprDbProtocolOperations for $$$'

# If ast-grep doesn't work, use ripgrep to find implementations
echo "=== Searching with ripgrep ==="
rg "impl.*HoprDbProtocolOperations.*for" -A 30

Length of output: 2347


Script:

#!/bin/bash
# Search for to_send and from_recv implementations
echo "=== Searching for to_send method ==="
rg "async fn to_send" -A 20 db/sql/src/protocol.rs

echo "=== Searching for from_recv method ==="
rg "async fn from_recv" -A 20 db/sql/src/protocol.rs

# Also search for any validation related to ticket price
echo "=== Searching for ticket price validation ==="
rg "ticket_price" -B 2 -A 5 db/sql/src/protocol.rs

Length of output: 5474

transport/network/src/config.rs (3)

17-17: LGTM! Well-chosen default threshold value.

The default value of 0.95 for auto path quality is reasonable and aligns with high-quality path selection.


44-46: LGTM! Properly configured quality threshold field.

The field is correctly configured with:

  • Default value from the constant
  • Serialization handling
  • SmartDefault implementation

93-98: LGTM! Comprehensive validation logic.

The validation ensures the threshold is within the valid range of 0.0 to 1.0, consistent with other quality thresholds.

chain/api/src/lib.rs (2)

349-351: LGTM! Clear method for minimum winning probability.

The method properly delegates to RPC operations and handles errors consistently.


353-355: LGTM! Well-implemented minimum ticket price retrieval.

The method follows the established pattern and properly handles errors.

chain/rpc/src/rpc.rs (2)

190-203: LGTM! Robust implementation of winning probability retrieval.

The implementation correctly:

  • Retrieves the encoded probability from the oracle
  • Handles byte manipulation for decoding
  • Provides appropriate error handling

205-214: LGTM! Clean implementation of ticket price retrieval.

The implementation correctly:

  • Retrieves the ticket price from the oracle
  • Converts it to the appropriate Balance type
  • Provides appropriate error handling
transport/api/src/lib.rs (2)

228-228: LGTM! Updated quality threshold parameter.

The change from quality_bad_threshold to quality_auto_path_threshold better reflects its purpose in automatic path selection.


520-525: LGTM! Enhanced packet configuration with ticket price.

The PacketInteractionConfig::new call now includes the outgoing ticket price parameter, completing the ticket pricing functionality.

hopr/hopr-lib/src/lib.rs (2)

647-656: LGTM: Ticket price validation is correctly implemented.

The code properly validates that the configured ticket price meets the network minimum requirement before starting the node.


658-668: Verify test environment handling.

The code correctly validates the winning probability against network minimum, with a test mode override. However, let's verify the environment variable handling:

  1. The test mode check could be extracted into a constant or helper function for reusability
  2. Consider documenting the test mode in code comments
+// Environment variable to disable certain checks in test mode
+const TEST_MODE_ENV_VAR: &str = "HOPR_TEST_DISABLE_CHECKS";
+
+fn is_test_mode() -> bool {
+    std::env::var(TEST_MODE_ENV_VAR).is_ok_and(|v| v.to_lowercase() == "true")
+}

-if !std::env::var("HOPR_TEST_DISABLE_CHECKS").is_ok_and(|v| v.to_lowercase() == "true")
+// Skip winning probability validation in test mode
+if !is_test_mode()
    && configured_win_prob.is_some_and(|c| c < network_min_win_prob)
✅ Verification successful

Test environment handling is well-documented and correctly implemented.

The environment variable HOPR_TEST_DISABLE_CHECKS is properly documented in README.md, has consistent usage across the codebase, and includes appropriate warning logs when enabled. While extracting the check into a constant and helper function would improve maintainability, the current implementation is correct and safe.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for the specific environment variable
echo "=== Searching for HOPR_TEST_DISABLE_CHECKS ==="
rg "HOPR_TEST_DISABLE_CHECKS" -B 2 -A 2

echo -e "\n=== Searching for test-related environment variables ==="
rg "HOPR_TEST|TEST_" --type rust

echo -e "\n=== Checking documentation ==="
fd README.md --exec cat {}

Length of output: 80340

chain/rpc/Cargo.toml (1)

3-3: Version bump and dependency addition look correct.

  • Version bump from 0.3.2 to 0.4.0 follows semantic versioning for breaking changes
  • New dependency hopr-internal-types is properly added as a workspace dependency

Also applies to: 64-64

METRICS.md (1)

68-68: LGTM: New metric documentation is clear and consistent.

The new metric hopr_indexer_data_source is properly documented following the existing format.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~68-~68: Loose punctuation mark.
Context: ...r checksum. - hopr_indexer_data_source: Current data source of the Indexer, key...

(UNLIKELY_OPENING_PUNCTUATION)

crypto/packet/src/validation.rs (1)

21-21: LGTM: Documentation improvements enhance readability.

The comment improvements make the validation requirements clearer and more consistent by:

  • Adding "The" at the start of each validation rule
  • Maintaining consistent capitalization and punctuation

Also applies to: 31-31, 42-42, 58-58, 66-66, 79-79

README.md (1)

206-208: LGTM! Documentation is clear and accurate.

The environment variables are well-documented with their purposes clearly stated. The formatting improvements enhance readability.

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)
hopr/hopr-lib/src/lib.rs (1)

658-668: Consider extracting the environment variable to a constant.

The winning probability validation is well implemented, but the environment variable handling could be improved:

  1. Extract HOPR_TEST_DISABLE_CHECKS to a constant at the top of the file.
  2. Add documentation explaining its purpose and impact.

Apply this diff to improve maintainability:

 // At the top of the file with other constants
+/// Environment variable to disable winning probability checks in test mode.
+/// When set to "true", allows the node to run with winning probabilities below the network minimum.
+const ENV_DISABLE_CHECKS: &str = "HOPR_TEST_DISABLE_CHECKS";

 // In the validation code
-if !std::env::var("HOPR_TEST_DISABLE_CHECKS").is_ok_and(|v| v.to_lowercase() == "true")
+if !std::env::var(ENV_DISABLE_CHECKS).is_ok_and(|v| v.to_lowercase() == "true")
transport/protocol/src/msg/processor.rs (2)

85-86: Consider caching the network values.

The dynamic determination of win probability and ticket price on every packet send could impact performance. Consider caching these values with a reasonable TTL to reduce database calls.


212-229: Consider consistent error handling between price and probability methods.

While the ticket price method properly propagates errors, the win probability method silently handles errors with inspect_err. Consider using consistent error handling between both methods.

-            .inspect_err(|error| error!(%error, "failed to determine current network winning probability"))
-            .ok();
+            .map_err(|e| {
+                PacketError::LogicError(format!("failed to determine current network winning probability: {e}"))
+            })?;
transport/protocol/tests/common/mod.rs (1)

211-212: Consider adding test cases for network-determined values.

The test currently uses fixed values for win probability and ticket price. Consider adding test cases where these values are not provided in the config and are determined from the network.

 let packet_cfg = PacketInteractionConfig {
     packet_keypair: opk.clone(),
     chain_keypair: ock.clone(),
-    outgoing_ticket_win_prob: Some(1.0),
-    outgoing_ticket_price: Some(BalanceType::HOPR.balance(100)),
+    outgoing_ticket_win_prob: None, // Test network-determined value
+    outgoing_ticket_price: None, // Test network-determined value
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8224f0 and 77dfdde.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • chain/api/Cargo.toml (1 hunks)
  • hopr/hopr-lib/src/lib.rs (2 hunks)
  • transport/api/src/lib.rs (2 hunks)
  • transport/protocol/src/msg/processor.rs (4 hunks)
  • transport/protocol/tests/common/mod.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • transport/api/src/lib.rs
⏰ 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-smoke-websocket
  • GitHub Check: tests-smart-contracts
  • GitHub Check: tests-unit
  • GitHub Check: Linter
🔇 Additional comments (5)
hopr/hopr-lib/src/lib.rs (1)

647-656: LGTM! Ticket price validation is well implemented.

The validation correctly ensures that the configured ticket price meets the network's minimum requirements. The error message is clear and helpful, including both the configured and minimum values for easy debugging.

transport/protocol/src/msg/processor.rs (3)

118-119: LGTM! Consistent approach with send() method.

The implementation maintains consistency with the send() method by using the same dynamic determination approach.


200-210: LGTM! Good error handling.

The method properly propagates errors and includes clear error messages. The comment about cache behavior is helpful.


324-325: LGTM! Good flexibility with optional configuration.

The change to make configuration fields optional allows for better flexibility in handling network-determined values.

Also applies to: 329-334

chain/api/Cargo.toml (1)

3-3: Verify version alignment across workspace packages.

The version bump from 0.3.1 to 0.4.0 represents a minor version change. Let's verify that related workspace packages are properly aligned.

✅ Verification successful

Version 0.4.0 is correctly aligned with related components

The version bump to 0.4.0 is properly aligned with the hopr-chain-rpc package which is also at 0.4.0. Other chain components have different versions as they can evolve independently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check version alignment across workspace packages
# Expected: All related packages should have matching versions

# Find all Cargo.toml files and check their versions
fd Cargo.toml | while read -r file; do
  echo "=== $file ==="
  # Extract package name and version
  awk -F' = ' '/^name|^version/ {gsub(/["]/,"",$2); print $1 ": " $2}' "$file"
done

Length of output: 119007


Script:

#!/bin/bash
# Find all Cargo.toml files in the chain directory
fd Cargo.toml chain/ | while read -r file; do
  echo "=== $file ==="
  # Extract package name and version
  awk -F' = ' '/^name|^version/ {gsub(/["]/,"",$2); print $1 ": " $2}' "$file"
done

Length of output: 1127

@Teebor-Choka
Copy link
Contributor

Are these all changes from 2.2.1? Or is something missing?

@NumberFour8
Copy link
Contributor Author

Are these all changes from 2.2.1? Or is something missing?

These are only my changes from 2.2.1

@Teebor-Choka
Copy link
Contributor

Could you port everything though?

Co-authored-by: Tibor <9529609+Teebor-Choka@users.noreply.github.com>
@NumberFour8 NumberFour8 changed the title Forward port 2.2.1 changes: #6789, #6807, #6818, #6823, #6828 Forward port 2.2.1 changes: #6789, #6807, #6812, #6818, #6823, #6828 Jan 31, 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: 0

🧹 Nitpick comments (1)
hoprd/rest-api/src/checks.rs (1)

Line range hint 73-73: Update comment to reflect both error cases.

The comment only mentions "division by zero" but the code now handles both division and modulo errors.

-            // The "division by zero" error is caused by the self-registration,
+            // The "division or modulo by zero" error is caused by the self-registration,
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 77dfdde and 18d1590.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • hoprd/rest-api/src/checks.rs (1 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: Linter
  • GitHub Check: tests-smoke-websocket
🔇 Additional comments (1)
hoprd/rest-api/src/checks.rs (1)

77-77: LGTM! Error handling improvement.

The change improves robustness by handling both division and modulo errors while maintaining the intended behavior.

@NumberFour8 NumberFour8 merged commit 5f71374 into master Jan 31, 2025
28 of 29 checks passed
@NumberFour8 NumberFour8 deleted the lukas/forward-ports branch January 31, 2025 13:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants