Skip to content
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

Implement new rpc calls to get anonymity sets #1507

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

levonpetrosyan93
Copy link
Contributor

Introducing two new RPC calls.

  • getsparkanonymitysetmeta returns all metadata related to anonymity set. set size, latest block hash and anonymity set hash
  • getsparkanonymitysetsector returns a sector of anonymity set based on provided range, set id and latest block hash

Copy link

coderabbitai bot commented Dec 14, 2024

Walkthrough

The changes introduce two new RPC methods, getsparkanonymitysetmeta and getsparkanonymitysetsector, in the src/rpc/misc.cpp file, allowing retrieval of anonymity set metadata and specific sectors, respectively. These methods are registered in the RPC command table in src/rpc/server.cpp and declared in src/rpc/server.h. Additionally, enhancements to the CSparkState class in src/spark/state.cpp and src/spark/state.h provide new functionality for managing anonymity set metadata and coin recovery, including improved error handling and data retrieval mechanisms.

Changes

File Change Summary
src/rpc/misc.cpp Added methods: getsparkanonymitysetmeta and getsparkanonymitysetsector for RPC functionality.
src/rpc/server.cpp Added RPC commands for getsparkanonymitysetmeta and getsparkanonymitysetsector in the command array.
src/rpc/server.h Declared external functions: getsparkanonymitysetmeta and getsparkanonymitysetsector.
src/spark/state.cpp Added methods: GetAnonSetMetaData and GetCoinsForRecovery for managing Spark coins and metadata.
src/spark/state.h Declared new method GetAnonSetMetaData and updated GetCoinsForRecovery method signature.

Possibly related PRs

🐇 In the meadow, we hop and play,
New RPCs brighten the day!
Anonymity sets, oh what a treat,
With data and coins, our work's complete!
Hopping with joy, we code away,
Sparkling features, hip-hip-hooray! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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: 3

🧹 Outside diff range and nitpick comments (3)
src/rpc/server.cpp (1)

343-344: Consider future API versioning strategy.

While categorizing these endpoints under "mobile" makes sense for now, consider implementing a more formal API versioning strategy if you plan to add more mobile-specific endpoints in the future. This would help manage API evolution and backward compatibility more effectively.

src/spark/state.cpp (1)

1333-1366: LGTM! Consider adding documentation.

The implementation correctly retrieves anonymity set metadata with proper error handling and thread safety (called within LOCK(cs_main)). The logic follows established patterns in the codebase.

Consider adding documentation to describe:

  • The purpose and usage of this method
  • Parameter requirements/constraints
  • Return value semantics
  • Thread safety requirements
+/**
+ * Retrieves metadata about an anonymity set for a given coin group ID.
+ * Must be called within LOCK(cs_main).
+ * @param chain The blockchain
+ * @param maxHeight Maximum block height to consider
+ * @param coinGroupID The coin group ID to query
+ * @param blockHash_out The latest block hash for the anonymity set
+ * @param setHash_out The hash of the anonymity set
+ * @param size The size of the anonymity set
+ */
 void CSparkState::GetAnonSetMetaData(
src/rpc/misc.cpp (1)

1310-1363: LGTM! Consider improving error messages.

The RPC implementation is well-structured with proper parameter validation, thread safety, and security checks.

Consider improving error messages to be more user-friendly and descriptive:

-        throw std::runtime_error(std::string("An exception occurred while parsing parameters: ") + e.what());
+        throw std::runtime_error(std::string("Invalid coinGroupId parameter. Must be a valid integer: ") + e.what());

-        throw std::runtime_error(std::string("Please rerun Firo with -mobile "));
+        throw std::runtime_error("This RPC call requires the -mobile option to be enabled when starting the node");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6da96d8 and abc7a95.

📒 Files selected for processing (5)
  • src/rpc/misc.cpp (2 hunks)
  • src/rpc/server.cpp (1 hunks)
  • src/rpc/server.h (1 hunks)
  • src/spark/state.cpp (1 hunks)
  • src/spark/state.h (1 hunks)
🔇 Additional comments (4)
src/spark/state.h (1)

216-223: LGTM: Well-structured method declaration for retrieving anonymity set metadata.

The parameter types and naming convention are appropriate, and the use of reference parameters for outputs follows good C++ practices.

src/rpc/server.h (1)

217-218: LGTM: RPC function declarations follow established patterns.

The new function declarations are consistent with existing RPC patterns and have clear, descriptive names.

src/rpc/server.cpp (1)

343-344: LGTM: RPC commands properly registered with appropriate settings.

The commands are correctly categorized under "mobile" and have appropriate security settings with okSafe=false.

src/rpc/misc.cpp (1)

2059-2060: LGTM! RPC commands properly registered.

The new RPC methods are correctly registered in the commands array under the "mobile" category with appropriate access flags.

src/spark/state.h Outdated Show resolved Hide resolved
src/spark/state.cpp Outdated Show resolved Hide resolved
src/rpc/misc.cpp Outdated Show resolved Hide resolved
Copy link

@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

🧹 Outside diff range and nitpick comments (2)
src/spark/state.h (2)

216-222: LGTM! Consider adding documentation.

The new method declaration follows good practices but would benefit from documentation explaining the parameters and return values.

Add documentation like:

/**
 * Retrieves metadata about an anonymity set.
 * @param chain The blockchain
 * @param maxHeight Maximum block height to consider
 * @param coinGroupID The coin group ID
 * @param blockHash_out Latest block hash for the set
 * @param setHash_out Hash of the anonymity set
 * @param size Size of the anonymity set
 */
void GetAnonSetMetaData(...);

224-230: LGTM! Consider adding documentation.

The modified method signature is appropriate but would benefit from documentation.

Add documentation like:

/**
 * Retrieves coins for recovery based on block hash.
 * @param chain The blockchain
 * @param maxHeight Maximum block height to consider
 * @param coinGroupID The coin group ID
 * @param blockHash Block hash to start recovery from
 * @param coins Output vector of recovered coins with transaction context
 */
void GetCoinsForRecovery(...);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between abc7a95 and fe5f6c6.

📒 Files selected for processing (5)
  • src/rpc/misc.cpp (2 hunks)
  • src/rpc/server.cpp (1 hunks)
  • src/rpc/server.h (1 hunks)
  • src/spark/state.cpp (1 hunks)
  • src/spark/state.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/rpc/server.h
  • src/rpc/server.cpp
🔇 Additional comments (5)
src/spark/state.cpp (2)

1333-1366: LGTM! Implementation follows established patterns.

The implementation correctly:

  • Handles error cases for non-existent coin groups
  • Traverses blocks to gather metadata
  • Updates output parameters appropriately

1368-1411: LGTM! Implementation follows established patterns.

The implementation correctly:

  • Handles error cases for non-existent coin groups
  • Uses block hash parameter to find starting point
  • Gathers coins and transaction context
src/rpc/misc.cpp (3)

1310-1363: LGTM! Implementation follows RPC conventions.

The RPC method correctly:

  • Validates parameters
  • Checks for -mobile flag
  • Uses proper locking
  • Returns data in expected format

2065-2066: LGTM! RPC registration follows conventions.

The new RPC methods are properly registered in the command table.


1365-1449: 🛠️ Refactor suggestion

Add index range validation and consider performance optimization.

While the implementation is functionally correct, it needs additional validation and could benefit from performance improvements.

  1. Add validation for index ranges:
    try {
        coinGroupId = std::stol(request.params[0].get_str());
        latestBlock = request.params[1].get_str();
        startIndex = std::stol(request.params[2].get_str());
        endIndex = std::stol(request.params[3].get_str());
+        
+        if (startIndex < 0) {
+            throw std::runtime_error("startIndex must be non-negative");
+        }
+        if (endIndex < startIndex) {
+            throw std::runtime_error("endIndex must be greater than or equal to startIndex");
+        }
+        if (endIndex - startIndex > 1000) {
+            throw std::runtime_error("Range too large. Maximum range is 1000");
+        }
    }
  1. Consider performance optimization:
    std::vector<std::pair<spark::Coin, std::pair<uint256, std::vector<unsigned char>>>> coins;
+    // Pre-allocate vector with estimated size to avoid reallocations
+    coins.reserve(endIndex - startIndex + 1);

Likely invalid or redundant comment.

Copy link

@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 (3)
src/spark/state.cpp (2)

1333-1366: Add parameter validation for GetAnonSetMetaData.

The implementation looks good but should validate input parameters for robustness.

Add validation at the start of the method:

void CSparkState::GetAnonSetMetaData(
        CChain *chain,
        int maxHeight,
        int coinGroupID,
        uint256& blockHash_out,
        std::vector<unsigned char>& setHash_out,
        int& size) {
+    if (!chain) {
+        throw std::invalid_argument("Chain parameter cannot be null");
+    }
+    if (maxHeight < 0) {
+        throw std::invalid_argument("maxHeight must be non-negative");
+    }
    if (coinGroups.count(coinGroupID) == 0) {
        return;
    }
    // ... rest of the implementation

1368-1415: Improve error handling and parameter validation.

The implementation looks good but could benefit from improved error handling and validation.

  1. Add parameter validation:
void CSparkState::GetCoinsForRecovery(
        CChain *chain,
        int maxHeight,
        int coinGroupID,
        uint256& blockHash,
        std::vector<std::pair<spark::Coin, std::pair<uint256, std::vector<unsigned char>>>>& coins) {
+    if (!chain) {
+        throw std::invalid_argument("Chain parameter cannot be null");
+    }
+    if (maxHeight < 0) {
+        throw std::invalid_argument("maxHeight must be non-negative");
+    }
    coins.clear();
    if (coinGroups.count(coinGroupID) == 0) {
-        throw std::runtime_error(std::string("There is no anonymity set with this id: " + coinGroupID));
+        throw std::runtime_error(std::string("No anonymity set found with ID: ") + std::to_string(coinGroupID));
    }
    // ... rest of the implementation
src/rpc/misc.cpp (1)

1310-1363: Add range validation for coinGroupId parameter.

The implementation looks good but should validate the coinGroupId parameter range.

Add validation after parsing the parameter:

    try {
        coinGroupId = std::stol(request.params[0].get_str());
+        if (coinGroupId <= 0) {
+            throw std::runtime_error("coinGroupId must be positive");
+        }
    } catch (std::logic_error const & e) {
        throw std::runtime_error(std::string("An exception occurred while parsing parameters: ") + e.what());
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe5f6c6 and b50f94b.

📒 Files selected for processing (2)
  • src/rpc/misc.cpp (2 hunks)
  • src/spark/state.cpp (1 hunks)
🔇 Additional comments (2)
src/rpc/misc.cpp (2)

2075-2076: LGTM! RPC command registration is correct.

The new RPC commands are properly registered in the commands array with appropriate category and safe mode settings.


1365-1459: 🛠️ Refactor suggestion

Add comprehensive parameter validation.

The implementation needs additional validation for the parameters.

Add validation after parsing parameters:

    try {
        coinGroupId = std::stol(request.params[0].get_str());
        latestBlock = request.params[1].get_str();
        startIndex = std::stol(request.params[2].get_str());
        endIndex = std::stol(request.params[3].get_str());

+        if (coinGroupId <= 0) {
+            throw std::runtime_error("coinGroupId must be positive");
+        }
+        if (startIndex < 0) {
+            throw std::runtime_error("startIndex must be non-negative");
+        }
+        if (endIndex <= startIndex) {
+            throw std::runtime_error("endIndex must be greater than startIndex");
+        }
+        if (endIndex - startIndex > 1000) {
+            throw std::runtime_error("Range too large. Maximum range is 1000");
+        }
    } catch (std::logic_error const & e) {
        throw std::runtime_error(std::string("An exception occurred while parsing parameters: ") + e.what());
    }

Additionally, consider pre-allocating the coins vector to avoid reallocations:

    std::vector<std::pair<spark::Coin, std::pair<uint256, std::vector<unsigned char>>>> coins;
+    coins.reserve(endIndex - startIndex + 1);

Likely invalid or redundant comment.

Copy link

@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)
src/spark/state.h (2)

216-223: LGTM! Consider adding parameter documentation.

The new GetAnonSetMetaData method signature looks good. Consider adding documentation comments to describe the parameters and their valid ranges.

+    /**
+     * Gets metadata about an anonymity set
+     * @param chain The blockchain
+     * @param maxHeight Maximum block height to consider
+     * @param coinGroupID The coin group ID
+     * @param blockHash_out Latest block hash for the set
+     * @param setHash_out Hash of the anonymity set
+     * @param size Size of the anonymity set
+     */
     void GetAnonSetMetaData(
             CChain *chain,
             int maxHeight,
             int coinGroupID,
             uint256& blockHash_out,
             std::vector<unsigned char>& setHash_out,
             int& size);

224-232: LGTM! Consider adding parameter documentation.

The new GetCoinsForRecovery method signature looks good. Consider adding documentation comments to describe the parameters and their valid ranges.

+    /**
+     * Gets coins from an anonymity set with index-based pagination
+     * @param chain The blockchain
+     * @param maxHeight Maximum block height to consider
+     * @param coinGroupID The coin group ID
+     * @param startIndex Start index for pagination (inclusive)
+     * @param endIndex End index for pagination (exclusive)
+     * @param blockHash Block hash to retrieve coins from
+     * @param coins Retrieved coins with their transaction context
+     */
     void GetCoinsForRecovery(
             CChain *chain,
             int maxHeight,
             int coinGroupID,
             int startIndex,
             int endIndex,
             uint256& blockHash,
             std::vector<std::pair<spark::Coin, std::pair<uint256, std::vector<unsigned char>>>>& coins);
src/spark/state.cpp (1)

1368-1425: Consider additional input validation and performance optimization.

The GetCoinsForRecovery implementation looks good but could benefit from:

  1. Input validation for index ranges
  2. Vector pre-allocation for better performance
 void CSparkState::GetCoinsForRecovery(
         CChain *chain,
         int maxHeight,
         int coinGroupID,
         int startIndex,
         int endIndex,
         uint256& blockHash,
         std::vector<std::pair<spark::Coin, std::pair<uint256, std::vector<unsigned char>>>>& coins) {
     coins.clear();
+    if (startIndex < 0) {
+        throw std::runtime_error("startIndex must be non-negative");
+    }
+    if (endIndex < startIndex) {
+        throw std::runtime_error("endIndex must be greater than or equal to startIndex");
+    }
+    if (endIndex - startIndex > 1000) {
+        throw std::runtime_error("Range too large. Maximum range is 1000");
+    }
     if (coinGroups.count(coinGroupID) == 0) {
         throw std::runtime_error(std::string("There is no anonymity set with this id: " + coinGroupID));
     }
     SparkCoinGroupInfo &coinGroup = coinGroups[coinGroupID];
+    // Pre-allocate vector with estimated size to avoid reallocations
+    coins.reserve(endIndex - startIndex + 1);
src/rpc/misc.cpp (1)

1365-1452: Consider additional error handling for base64 decoding.

The getsparkanonymitysetsector implementation looks good but could benefit from additional error handling around base64 decoding.

     std::string  strHash = DecodeBase64(latestBlock);
+    if (strHash.empty()) {
+        throw std::runtime_error("Failed to decode blockHash from base64");
+    }
     std::vector<unsigned char> vec(strHash.begin(), strHash.end());
     if (vec.size() != 32)
         throw std::runtime_error(std::string("Provided blockHash data is not correct."));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b50f94b and 600da33.

📒 Files selected for processing (3)
  • src/rpc/misc.cpp (2 hunks)
  • src/spark/state.cpp (1 hunks)
  • src/spark/state.h (1 hunks)
🔇 Additional comments (3)
src/spark/state.cpp (1)

1333-1366: LGTM! Implementation handles edge cases properly.

The GetAnonSetMetaData implementation:

  • Validates coin group existence
  • Properly initializes output parameters
  • Efficiently calculates set size
src/rpc/misc.cpp (2)

1310-1363: LGTM! Clear error handling and response format.

The getsparkanonymitysetmeta implementation:

  • Validates input parameters
  • Checks for -mobile flag
  • Returns well-structured response with blockHash, setHash and size

2068-2069: LGTM! RPC commands properly registered.

The new RPC commands are correctly registered in the command table under the "mobile" category.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants