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

feat(platform): get current quorum info #2168

Merged
merged 6 commits into from
Sep 26, 2024

Conversation

QuantumExplorer
Copy link
Member

@QuantumExplorer QuantumExplorer commented Sep 26, 2024

Issue being fixed or feature implemented

We wanted to be able to get the current quorum info from the state.

What was done?

Added a new RPC.
Moved Validator Set and Validator Types to DPP.
Added the ability to get unproved data through sdk.

How Has This Been Tested?

Main tests.

Breaking Changes

None

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new RPC method for querying current quorum information.
    • Enhanced the feature set with additional capabilities for managing core types and serialization.
    • Implemented new structs for representing validators and validator sets, complete with serialization support.
    • Added a trait for structured handling of unproved requests and responses.
  • Bug Fixes

    • Streamlined the logic for handling validator set updates and improved error handling.
  • Documentation

    • Updated module structure to better organize current quorums functionality.
  • Chores

    • Enhanced dependency features for improved serialization capabilities.

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a new RPC method getCurrentQuorumsInfo to the Platform service, along with associated request and response message structures. Updates include the addition of new modules for managing validators and validator sets, enhancements to serialization capabilities, and improvements in querying current quorum information. The overall structure of the codebase has been refined to streamline interactions with validator and quorum data, ensuring better organization and modularity.

Changes

File Path Change Summary
packages/dapi-grpc/protos/platform/v0/platform.proto Added getCurrentQuorumsInfo RPC method, along with GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse message structures.
packages/rs-dpp/Cargo.toml Added features core-types, core-types-serialization, and core-types-serde-conversion.
packages/rs-dpp/src/core_types/validator/v0/mod.rs Introduced ValidatorV0 struct with fields for validator properties and serialization capabilities.
packages/rs-dpp/src/core_types/validator_set/v0/mod.rs Introduced ValidatorSetV0 struct with quorum-related fields and serialization support.
packages/rs-dpp/src/lib.rs Added new public module core_types.
packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs Removed ValidatorSetV0 struct and introduced ValidatorSetMethodsV0 trait for managing validator set updates.
packages/rs-drive-proof-verifier/src/unproved.rs Added FromUnproved trait for parsing unproved server responses.
packages/rs-drive-proof-verifier/src/types.rs Introduced CurrentQuorumsInfo struct to encapsulate quorum state information.
packages/rs-sdk/src/platform/fetch_unproved.rs Introduced FetchUnproved trait for fetching unproved data.
packages/rs-platform-version/src/version/*.rs Added current_quorums_info field to PlatformVersion structure across multiple version files.

Possibly related PRs

  • feat(platform): get current quorum info  #2168: This PR directly relates to the main PR as it also introduces the getCurrentQuorumsInfo RPC method in the platform.proto file, which is the same method added in the main PR. Both PRs involve changes to the same request and response message structures for querying current quorum information.

Suggested reviewers

  • shumkov
  • lklimek

Poem

In the meadow, changes bloom,
Quorums dance, dispelling gloom.
Validators hop, sets align,
New methods spring, like sweet sunshine.
With every byte, a tale unfolds,
In rabbit hearts, the future holds! 🐇✨


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

🧹 Outside diff range and nitpick comments (19)
packages/rs-dpp/src/core_types/mod.rs (1)

1-2: Consider adding module-level documentation.

While the module names are self-explanatory, it would be beneficial to add brief documentation comments explaining the purpose and contents of each module. This can help developers quickly understand the role of these modules within the larger system.

Consider adding documentation like this:

/// Module containing types and functionality related to individual validators.
pub mod validator;

/// Module for managing sets of validators and related operations.
pub mod validator_set;
packages/rs-drive-proof-verifier/src/lib.rs (1)

17-17: LGTM! Consider adding documentation for the new module.

The addition of the unproved module aligns with the PR objectives and is correctly implemented. The module is properly declared as public, allowing it to be used by other parts of the codebase or external users of this library.

To improve code clarity and maintain consistency with other modules in this file, consider adding a brief documentation comment explaining the purpose of the unproved module. For example:

/// Module for handling unproved data retrieval and processing
pub mod unproved;
packages/rs-sdk/src/platform.rs (1)

Line range hint 3-7: Note the TODO for future SDK development.

There's an existing TODO comment at the beginning of the file that outlines plans for future SDK development. While not directly related to the current change, it's worth keeping in mind for future work:

  1. A proper user-facing API should be defined to hide transport and serialization details.
  2. The current re-exports of proto-generated types are temporary and may be replaced in the future.

Consider creating a GitHub issue to track this future work, ensuring it's not overlooked in subsequent development cycles.

packages/rs-dpp/src/lib.rs (1)

Line range hint 1-92: Consider grouping related modules for better organization

The file structure is generally well-organized, but there's an opportunity to improve readability and maintainability by grouping related modules together. For example:

  1. Core functionality modules (e.g., data_contract, document, identity)
  2. Utility and helper modules (e.g., util, serialization)
  3. Feature-specific modules (e.g., state_transition, dash_platform_protocol)
  4. Cryptography-related modules (e.g., signing, bls)

This grouping could be achieved through comments or by reordering the module declarations. It would make it easier for developers to navigate the codebase and understand the relationships between different modules.

packages/rs-dpp/Cargo.toml (1)

198-199: LGTM: New features added to abci and declared

The addition of core-types-serialization and core-types-serde-conversion to the abci list and their declaration as empty arrays at the end of the file is consistent with the project structure.

Consider adding a brief comment or documentation for these new features to explain their intended use and why they're currently empty. This will help other developers understand the purpose of these features and their future implementation plans.

Also applies to: 272-273

packages/rs-dapi-client/src/transport/grpc.rs (1)

379-387: LGTM! Consider adding a brief comment for clarity.

The implementation of get_current_quorums_info is consistent with other gRPC method implementations in the file and aligns with the PR objectives. It correctly uses the impl_transport_request_grpc! macro with appropriate request and response types.

Consider adding a brief comment above the implementation to describe the purpose of this method, similar to other implementations in the file. For example:

// Retrieves the current quorums information from the platform
impl_transport_request_grpc!(
    // ... (rest of the implementation)
);
packages/rs-drive-abci/src/query/service.rs (1)

601-611: LGTM: New method implemented correctly

The get_current_quorums_info method has been implemented consistently with other query methods in this service. It correctly uses the handle_blocking_query method to manage potentially time-consuming operations.

Consider updating the endpoint name in the handle_blocking_query call from "query_current_quorums_info" to "get_current_quorums_info" for consistency with the method name and other endpoint names in this file.

-            "query_current_quorums_info",
+            "get_current_quorums_info",
packages/rs-drive-abci/src/platform_types/platform_state/v0/mod.rs (2)

348-357: LGTM! Consider using sort_unstable_by for potential performance improvement.

The implementation correctly collects and sorts the validator sets by core height in descending order. It's well-structured and achieves its purpose effectively.

For a potential performance improvement, consider using sort_unstable_by instead of sort_by. sort_unstable_by is generally faster but doesn't preserve the order of equal elements. If the order of equal elements is not important in this context, you can apply this change:

-        validator_sets.sort_by(|a, b| b.core_height().cmp(&a.core_height()));
+        validator_sets.sort_unstable_by(|a, b| b.core_height().cmp(&a.core_height()));

Line range hint 359-372: LGTM! Consider adding a debug assertion for position overflow.

The implementation correctly uses the new sorting method and finds the position of the current validator set. It's well-structured and achieves its purpose effectively.

To enhance robustness, consider adding a debug assertion to check for potential overflow when converting from usize to u16. This won't affect release builds but can help catch issues during development:

         validator_sets
             .iter()
             .position(|&validator_set| validator_set.quorum_hash() == &current_quorum_hash)
-            .map(|position| position as u16) // Convert position to u16
+            .map(|position| {
+                debug_assert!(position <= u16::MAX as usize, "Validator set position overflow");
+                position as u16
+            })
packages/rs-drive-abci/src/platform_types/validator_set/mod.rs (4)

4-4: Consider more selective re-export to reduce namespace pollution

Using pub use dpp::core_types::validator_set::*; re-exports all items from the module, which may introduce unnecessary items into your module's public API. Consider re-exporting only the necessary types or functions to maintain a clean and intentional public interface.


6-7: Enhance module documentation for clarity

The comment /// v0 is minimal. Consider adding more detailed documentation to describe the purpose and functionality of the v0 module to improve code readability and maintainability.


9-12: Add documentation for trait and methods

Adding documentation comments to the ValidatorSetExt trait and its methods to_update and to_update_owned will enhance code clarity and help other developers understand their purpose and usage.


15-24: Consider adding documentation to trait implementations

Adding doc comments to the implementation of ValidatorSetExt for ValidatorSet and its methods to_update and to_update_owned can improve code clarity and assist other developers in understanding the functionality and usage of these methods.

packages/rs-sdk/src/platform/fetch_unproved.rs (2)

65-65: Avoid unnecessary cloning of the request

The request is cloned before execution, but since it's not used elsewhere after this point, cloning may be unnecessary. Removing the clone can improve performance by reducing overhead.

Proposed change:

-        let response = request.clone().execute(sdk, settings).await?;
+        let response = request.execute(sdk, settings).await?;

Ensure that the execute method does not consume or modify request in a way that affects subsequent code.


53-74: Add unit tests for fetch_unproved_with_settings

Including unit tests for the fetch_unproved_with_settings method will ensure that it behaves correctly under various conditions and will help catch regressions early.

Would you like assistance in creating unit tests for this method? I can help set up test scenarios and examples.

packages/rs-drive-abci/src/query/system/current_quorums_info/v0/mod.rs (1)

16-16: Clarify Unused Request Parameter

The request parameter GetCurrentQuorumsInfoRequestV0 {} is unused within the function body. For clarity and convention, consider renaming it to _request to indicate that it's intentionally unused.

Apply this diff to rename the parameter:

-            GetCurrentQuorumsInfoRequestV0 {}: GetCurrentQuorumsInfoRequestV0,
+            _request: GetCurrentQuorumsInfoRequestV0,
packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs (2)

Line range hint 157-202: Refactor to eliminate code duplication in to_update methods

The to_update and to_update_owned methods contain nearly identical logic, differing mainly in how they iterate over the members collection (iter() vs. into_values()). This duplication increases maintenance overhead and potential for inconsistencies.

Consider abstracting the shared logic into a generic function or helper method that can handle both references and owned values. This refactoring will improve code maintainability and reduce redundancy.

Also applies to: 204-248


Line range hint 269-289: Simplify error handling in try_from_quorum_info_result

The use of filter_map with mixed Option and Result types can make error handling confusing and less readable. Returning Some(Err(e)) within filter_map blends the two layers unnecessarily.

Refactor the closure to use map instead of filter_map, allowing for clearer separation of errors and option handling. Alternatively, collect the results into an intermediate Result<Vec<_>, Error> before constructing the BTreeMap, enhancing clarity and error propagation.

packages/rs-drive-proof-verifier/src/types.rs (1)

383-396: Simplify and Conciseness in Documentation Comments

The documentation for CurrentQuorumsInfo is extensive but may be overly verbose and include redundant information. Consider simplifying the comments to focus on key details, enhancing readability and maintainability.

For example, the struct-level comment can be condensed:

 /// Represents the current state of quorums in the platform.
-///
-/// This struct holds various information related to the current quorums,
-/// including the list of quorum hashes, the current active quorum hash,
-/// and details about the validators and their statuses.
 ///
-/// # Fields
-///
-/// - `quorum_hashes`: A list of 32-byte hashes representing the active quorums.
-/// - `current_quorum_hash`: A 32-byte hash identifying the currently active quorum.
-/// - `validator_sets`: A collection of [`ValidatorSet`] structs for different quorums.
-/// - `last_block_proposer`: The ProTxHash of the last block proposer.
-/// - `last_platform_block_height`: The height of the most recent platform block.
-/// - `last_core_block_height`: The height of the most recent core blockchain block.
+/// Contains information about active quorums and validator sets, including hashes, validator details,
+/// and the last block proposer information.

Similarly, ensure field comments are concise and consistently formatted.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1b975c5 and ff0eded.

📒 Files selected for processing (28)
  • packages/dapi-grpc/protos/platform/v0/platform.proto (2 hunks)
  • packages/rs-dapi-client/src/transport/grpc.rs (1 hunks)
  • packages/rs-dpp/Cargo.toml (5 hunks)
  • packages/rs-dpp/src/core_types/mod.rs (1 hunks)
  • packages/rs-dpp/src/core_types/validator/mod.rs (1 hunks)
  • packages/rs-dpp/src/core_types/validator/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/core_types/validator_set/mod.rs (1 hunks)
  • packages/rs-dpp/src/core_types/validator_set/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/lib.rs (1 hunks)
  • packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs (2 hunks)
  • packages/rs-drive-abci/src/execution/platform_events/block_end/validator_set_update/v0/mod.rs (4 hunks)
  • packages/rs-drive-abci/src/execution/platform_events/block_end/validator_set_update/v1/mod.rs (4 hunks)
  • packages/rs-drive-abci/src/execution/platform_events/core_based_updates/update_quorum_info/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/platform_state/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/validator/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/validator/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/validator_set/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs (9 hunks)
  • packages/rs-drive-abci/src/query/service.rs (2 hunks)
  • packages/rs-drive-abci/src/query/system/current_quorums_info/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/query/system/current_quorums_info/v0/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/query/system/mod.rs (1 hunks)
  • packages/rs-drive-proof-verifier/Cargo.toml (1 hunks)
  • packages/rs-drive-proof-verifier/src/lib.rs (1 hunks)
  • packages/rs-drive-proof-verifier/src/types.rs (2 hunks)
  • packages/rs-drive-proof-verifier/src/unproved.rs (1 hunks)
  • packages/rs-sdk/src/platform.rs (1 hunks)
  • packages/rs-sdk/src/platform/fetch_unproved.rs (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Rust packages (wasm-dpp) / Linting
packages/rs-dpp/src/core_types/validator/v0/mod.rs

[warning] 16-16: unused import: dashcore::hashes::Hash
warning: unused import: dashcore::hashes::Hash
--> packages/rs-dpp/src/core_types/validator/v0/mod.rs:16:5
|
16 | use dashcore::hashes::Hash;
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default

packages/rs-dpp/src/core_types/validator_set/v0/mod.rs

[failure] 105-105: cannot find trait BorrowDecode in this scope
error[E0405]: cannot find trait BorrowDecode in this scope
--> packages/rs-dpp/src/core_types/validator_set/v0/mod.rs:105:11
|
105 | impl<'de> BorrowDecode<'de> for ValidatorSetV0 {
| ^^^^^^^^^^^^ not found in this scope
|
help: consider importing one of these items
|
1 + use bincode::BorrowDecode;
|
1 + use crate::platform_serialization::BorrowDecode;
|
1 + use platform_serialization::BorrowDecode;
|


[failure] 106-106: cannot find trait Decoder in this scope
error[E0405]: cannot find trait Decoder in this scope
--> packages/rs-dpp/src/core_types/validator_set/v0/mod.rs:106:25
|
106 | fn borrow_decode<D: Decoder>(decoder: &mut D) -> Result<Self, bincode::error::DecodeError> {
| ^^^^^^^ not found in this scope
|
help: consider importing one of these items
|
1 + use bincode::de::Decoder;
|
1 + use crate::platform_serialization::de::Decoder;
|
1 + use platform_serialization::de::Decoder;
|

🪛 GitHub Check: Rust packages (drive) / Linting
packages/rs-dpp/src/core_types/validator/v0/mod.rs

[warning] 16-16: unused import: dashcore::hashes::Hash
warning: unused import: dashcore::hashes::Hash
--> packages/rs-dpp/src/core_types/validator/v0/mod.rs:16:5
|
16 | use dashcore::hashes::Hash;
| ^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default

packages/rs-dpp/src/core_types/validator_set/v0/mod.rs

[failure] 105-105: cannot find trait BorrowDecode in this scope
error[E0405]: cannot find trait BorrowDecode in this scope
--> packages/rs-dpp/src/core_types/validator_set/v0/mod.rs:105:11
|
105 | impl<'de> BorrowDecode<'de> for ValidatorSetV0 {
| ^^^^^^^^^^^^ not found in this scope
|
help: consider importing one of these items
|
1 + use bincode::BorrowDecode;
|
1 + use crate::platform_serialization::BorrowDecode;
|
1 + use platform_serialization::BorrowDecode;
|


[failure] 106-106: cannot find trait Decoder in this scope
error[E0405]: cannot find trait Decoder in this scope
--> packages/rs-dpp/src/core_types/validator_set/v0/mod.rs:106:25
|
106 | fn borrow_decode<D: Decoder>(decoder: &mut D) -> Result<Self, bincode::error::DecodeError> {
| ^^^^^^^ not found in this scope
|
help: consider importing one of these items
|
1 + use bincode::de::Decoder;
|
1 + use crate::platform_serialization::de::Decoder;
|
1 + use platform_serialization::de::Decoder;
|

🔇 Additional comments (31)
packages/rs-dpp/src/core_types/mod.rs (1)

1-2: LGTM! Changes align well with PR objectives.

The addition of validator and validator_set modules aligns perfectly with the PR objective of moving Validator Types and Validator Set to the Decentralized Payment Protocol (DPP). This structure promotes better organization and separation of concerns in the codebase.

packages/rs-drive-abci/src/platform_types/validator/mod.rs (1)

1-3: Consider the implications of restructuring validator types

The removal of the Validator enum and its associated implementations, coupled with the direct re-export from dpp::core_types::validator, represents a significant change in how validator types are handled. This simplification aligns with the PR objectives of moving Validator Types to DPP, but it has several implications:

  1. It removes the version-specific implementation layer, which might impact code that relied on the Validator enum.
  2. The direct re-export suggests a move towards using core types, which can improve consistency but may require updates in other parts of the codebase.
  3. The presence of the v0 module (line 1) seems inconsistent with the removal of version-specific implementations.

To ensure this change doesn't introduce breaking changes or leave unused code:

Please review the results of these checks and consider:

  1. Updating any code that might still be using the old Validator enum.
  2. Removing the v0 module if it's no longer necessary.
  3. Ensuring that all parts of the codebase are updated to use the new validator types from dpp::core_types::validator.
packages/rs-sdk/src/platform.rs (1)

14-14: LGTM! New module added as expected.

The addition of the fetch_unproved module aligns with the PR objectives to enhance the SDK's capability for obtaining unproved data. The placement is consistent with the existing structure.

Let's verify the usage of this new module and check if any documentation updates are needed:

Please review the results of this script to ensure proper usage and documentation of the new module.

packages/rs-drive-proof-verifier/Cargo.toml (1)

31-31: LGTM. Please verify the necessity and impact of the new feature.

The addition of the "core-types-serialization" feature to the dpp dependency aligns with the PR objectives, particularly the movement of Validator Set and Validator Types to DPP.

Could you please confirm:

  1. Is this feature necessary for handling the Validator Set and Validator Types in DPP?
  2. Are there any other modules in the project that might need this feature as well?

To help verify the impact, you can run the following script:

This will help ensure that the feature is appropriately added where needed and that we haven't missed any other modules that might benefit from it.

✅ Verification successful

Verified the addition of the "core-types-serialization" feature across relevant modules. No issues found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other potential usages of the new feature across the project

# Search for potential usages of core types serialization in Rust files
echo "Searching for potential usages of core types serialization:"
rg --type rust -i "core.*types.*serialization" -g '!target/'

# Check other Cargo.toml files for the dpp dependency
echo "Checking other Cargo.toml files for the dpp dependency:"
rg --type toml 'dpp.*=.*path.*=.*"../rs-dpp"' -g 'Cargo.toml'

Length of output: 2737

packages/rs-dpp/src/lib.rs (1)

56-56: New module core_types added

The addition of the core_types module aligns with the PR objectives of moving Validator Set and Validator Types to the Decentralized Payment Protocol (DPP). This new module likely contains these core types, which is a good step towards better organization and modularity.

To ensure the core_types module is properly implemented and contains the expected types, let's verify its contents:

packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs (3)

13-13: LGTM: New import for ValidatorSetExt

The addition of ValidatorSetExt import is appropriate and aligns with the changes in the init_chain_v0 method. This import likely provides extended functionality for working with validator sets.


109-109: LGTM: Simplified ValidatorSetUpdate creation

The change from ValidatorSetUpdate::new(validator_set_inner.1) to validator_set_inner.1.to_update() is a good improvement. It leverages the ValidatorSetExt trait to provide a more idiomatic and potentially more efficient way to create a ValidatorSetUpdate. This change:

  1. Simplifies the code, making it more readable.
  2. Standardizes the conversion process from a validator set to an update.
  3. Potentially improves performance by using a specialized method.

The functionality remains the same, but the implementation is more elegant.


13-13: Summary: Improved validator set handling

The changes in this file enhance the handling of validator sets in the initialization process:

  1. The addition of ValidatorSetExt import provides extended functionality for validator sets.
  2. The simplification of ValidatorSetUpdate creation in the init_chain_v0 method improves code readability and potentially performance.

These changes align well with the PR objectives of improving quorum information retrieval and streamlining validator set management. The modifications are minimal but impactful, contributing to better code organization and potentially more efficient quorum handling.

Also applies to: 109-109

packages/rs-dpp/Cargo.toml (4)

92-93: LGTM: New features added to all_features

The addition of core-types-serialization and core-types-serde-conversion to the all_features list is consistent with the project structure and appears to be a valid enhancement.


136-137: LGTM: New features added to dash-sdk-features

The addition of core-types-serialization and core-types-serde-conversion to the dash-sdk-features list is consistent with the project structure and appears to be a valid enhancement for the SDK.


159-160: LGTM: New features added to all_features_without_client

The addition of core-types-serialization and core-types-serde-conversion to the all_features_without_client list is consistent with the project structure and appears to be a valid enhancement for non-client features.


92-93: Summary: New serialization features added

The changes introduce two new features, core-types-serialization and core-types-serde-conversion, across multiple feature sets in the project. These additions are consistent and well-integrated into the existing structure.

Key points:

  1. The new features are added to all_features, dash-sdk-features, all_features_without_client, and abci.
  2. Empty arrays for these features are declared at the end of the file, allowing for future expansion.

These changes appear to be laying the groundwork for enhanced serialization capabilities in the project, which aligns with the PR objectives of improving data handling and streamlining integration within the platform.

To ensure these changes don't introduce any conflicts or issues, please run the following verification script:

Also applies to: 136-137, 159-160, 198-199, 272-273

✅ Verification successful

Verification Successful: New serialization features are correctly integrated

The executed verification scripts confirm that:

  1. Presence in All Locations: Both core-types-serialization and core-types-serde-conversion are present in all expected sections of Cargo.toml.
  2. Proper Declarations: The new features are correctly declared as empty arrays, allowing for future enhancements.
  3. No Conflicts or Duplicates: There are no duplicate entries or conflicts related to the new features.

These results indicate that the new serialization features have been seamlessly integrated without introducing any issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the new features are correctly added and don't conflict with existing ones

# Test 1: Check if the new features are present in all expected locations
echo "Checking for new features in all expected locations:"
grep -n "core-types-serialization" packages/rs-dpp/Cargo.toml
grep -n "core-types-serde-conversion" packages/rs-dpp/Cargo.toml

# Test 2: Verify that the new features are declared as empty arrays
echo "Verifying new feature declarations:"
tail -n 5 packages/rs-dpp/Cargo.toml | grep -E "core-types-(serialization|serde-conversion) = \[\]"

# Test 3: Check for any potential conflicts or duplicates
echo "Checking for potential conflicts or duplicates:"
grep -n "core-types-" packages/rs-dpp/Cargo.toml | sort | uniq -c

# Note: If any of these tests fail, it might indicate an issue with the changes.

Length of output: 1381

packages/rs-drive-abci/src/execution/platform_events/block_end/validator_set_update/v0/mod.rs (5)

14-14: LGTM: New import aligns with code changes.

The addition of ValidatorSetExt import is consistent with the usage of the to_update() method in the code changes below. This suggests a refactoring to use extension methods for ValidatorSet, which can improve code organization and reusability.


148-148: LGTM: Improved method naming for validator set update.

The change from (likely) into() to to_update() improves code readability and self-documentation. The new method name clearly indicates its purpose of creating a validator set update.


167-167: LGTM: Consistent use of new method across code paths.

The change to to_update() is consistently applied here, maintaining uniformity in how validator set updates are created across different scenarios in the code.


189-189: LGTM: Consistent refactoring in non-rotation scenario.

The change to to_update() is appropriately applied in the scenario where a validator set update occurs without rotation. This maintains consistency with the overall refactoring and improves code clarity.


Line range hint 24-199: Consider further refactoring and ensure comprehensive testing.

The changes consistently improve the code by using the more descriptive to_update() method. However, the validator_set_update_v0 function remains quite complex, handling multiple scenarios for validator set updates and rotations.

Consider the following suggestions:

  1. Break down the function into smaller, more focused functions to improve readability and maintainability.
  2. Add or update unit tests to ensure the new to_update() method works correctly in all scenarios, including edge cases.
  3. Consider adding debug logging for the to_update() method calls to aid in troubleshooting.

To verify the impact and coverage of these changes, you can run the following script:

packages/rs-drive-abci/src/execution/platform_events/block_end/validator_set_update/v1/mod.rs (5)

163-163: LGTM. Consider updating documentation if needed.

The change from new_validator_set.into() to new_validator_set.to_update() is an improvement in terms of explicitness and likely type safety. This is consistent with the newly imported ValidatorSetExt trait.

If there's any existing documentation for this method or the ValidatorSet type, consider updating it to reflect this change in the conversion method.


Line range hint 1-218: Summary: Consistent improvement in ValidatorSet conversion

The changes in this file consistently replace the use of .into() with .to_update() for ValidatorSet conversions. This modification, along with the addition of the ValidatorSetExt import, suggests a more explicit and potentially safer approach to converting ValidatorSet to ValidatorSetUpdate.

These changes align well with the PR objectives of enhancing the platform's functionality for retrieving quorum information. They appear to be part of a larger refactoring effort to improve the handling of validator sets.

Key points:

  1. The new to_update() method is likely more explicit about the conversion operation.
  2. The changes are applied consistently throughout the file.
  3. The modifications may improve code readability and type safety.

To ensure the changes have been applied correctly across the entire codebase and haven't introduced any issues, please run the verification scripts provided in the previous comments.


14-14: LGTM. Verify usage of the new import.

The addition of ValidatorSetExt import is appropriate given the changes in the conversion method. This likely introduces new functionality or extension methods for ValidatorSet.

To ensure this import is used correctly throughout the codebase, run the following script:

#!/bin/bash
# Description: Verify the usage of ValidatorSetExt in the codebase

# Test: Search for ValidatorSetExt usage
rg --type rust "ValidatorSetExt"

# Test: Check if there are any remaining .into() calls on ValidatorSet that should be replaced
rg --type rust "ValidatorSet.*\.into\(\)"

207-207: LGTM. Verify overall impact of the changes.

The change from current_validator_set.into() to current_validator_set.to_update() is consistent with the previous changes and completes the update throughout this file.

To ensure the changes have been applied correctly and to verify their impact, run the following script:

#!/bin/bash
# Description: Verify the impact of ValidatorSet conversion changes

# Test: Check for any remaining .into() calls on ValidatorSet
rg --type rust "ValidatorSet.*\.into\(\)"

# Test: Confirm usage of .to_update() method
rg --type rust "ValidatorSet.*\.to_update\(\)"

# Test: Check for any compiler errors or warnings related to these changes
cargo check --all-targets
cargo clippy --all-targets -- -D warnings

This script will help ensure that all instances have been updated, and that the changes haven't introduced any new compiler errors or warnings.


185-185: LGTM. Verify all instances are updated.

The change from new_validator_set.into() to new_validator_set.to_update() is consistent with the previous change and improves code clarity.

To ensure all instances of this conversion have been updated throughout the codebase, run the following script:

packages/rs-drive-abci/src/query/service.rs (2)

18-24: LGTM: Import statements updated correctly

The import statement has been appropriately updated to include GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse. This change is consistent with the new method being implemented and follows the existing import structure.


Line range hint 1-624: Summary: New query method added successfully

The changes in this file successfully introduce a new get_current_quorums_info method to the PlatformService implementation. The implementation follows the existing patterns in the file, using the handle_blocking_query method for consistent error handling and metrics tracking. The new method appears to be well-integrated into the existing service structure.

To ensure the new method is properly integrated, let's verify its usage across the codebase:

✅ Verification successful

To ensure the query_current_quorums_info function is properly implemented, let's perform additional checks:


Verification Successful: query_current_quorums_info is properly implemented

The query_current_quorums_info method and its versioned implementation query_current_quorums_info_v0 are correctly defined in the codebase. The integration aligns with existing patterns, and no missing implementations were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of the new get_current_quorums_info method

# Search for potential calls to the new method
rg --type rust 'get_current_quorums_info'

# Search for the implementation of the query_current_quorums_info function
ast-grep --lang rust --pattern 'fn query_current_quorums_info'

Length of output: 1763


Script:

# Description: Search for implementations of `query_current_quorums_info` with any variations

# Search for function implementations that might match `query_current_quorums_info` with different signatures or in different modules
rg --type rust 'fn\s+query_current_quorums_info' --glob '**/*.rs'

# Additionally, search for trait implementations that might include `query_current_quorums_info`
rg --type rust 'query_current_quorums_info' --context 3

# Check for any pending branches or commits that might contain the implementation
git branch --all
git log --all --grep='query_current_quorums_info'

Length of output: 3385

packages/rs-drive-abci/src/platform_types/platform_state/v0/mod.rs (1)

Line range hint 348-372: Overall, the changes look good and align with the PR objectives.

The introduction of the validator_sets_sorted_by_core_height_by_most_recent method and the update to current_validator_set_position_in_list_by_most_recent enhance the platform's ability to manage and retrieve quorum information efficiently. The implementations are correct, and the code is well-structured.

Minor suggestions for optimization and error handling have been provided, which could further improve the robustness and performance of the code. These changes contribute positively to the overall functionality of the platform state management.

packages/rs-drive-abci/src/platform_types/validator_set/mod.rs (1)

1-2: Imports are appropriate and necessary

The added imports bring in required traits and types for ValidatorSet operations.

packages/rs-sdk/src/platform/fetch_unproved.rs (2)

1-9: Imports are appropriate and necessary

All imported modules are utilized within the file, ensuring no redundant imports. This promotes maintainability and clarity.


10-47: Well-defined FetchUnproved trait with clear documentation

The FetchUnproved trait is properly defined with comprehensive documentation for each method. The use of async_trait effectively allows asynchronous methods within the trait, aligning with best practices.

packages/rs-dpp/src/core_types/validator_set/mod.rs (1)

1-111: Well-structured implementation of ValidatorSet with versioning support

The code introduces a ValidatorSet enum to manage different versions of validator sets, currently with a single variant V0. The implementation correctly delegates getter and setter methods to the underlying ValidatorSetV0 struct, ensuring that the code is extendable for future versions.

Conditional compilation features are appropriately used to include serialization and deserialization capabilities when the respective features are enabled. This approach maintains modularity and allows for flexibility based on the build configuration.

packages/rs-dpp/src/core_types/validator/v0/mod.rs (1)

44-78: Verify consistency between encode and decode implementations

Ensure that the order of fields and their serialization in the encode and decode methods match exactly. Any inconsistency can lead to serialization/deserialization errors that are hard to detect.

Also applies to: 81-128

packages/dapi-grpc/protos/platform/v0/platform.proto (1)

1190-1194: Empty 'GetCurrentQuorumsInfoRequestV0' Message

The GetCurrentQuorumsInfoRequestV0 message is currently empty. If no request parameters are needed at this time, this is acceptable and allows for future expansion. Ensure this aligns with the intended API design.

Comment on lines +10 to +12
use crate::platform_types::validator_set::v0::{
ValidatorSetMethodsV0, ValidatorSetV0, ValidatorSetV0Getters,
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Unnecessary Import: ValidatorSetMethodsV0 is not used in the file.

The imported ValidatorSetMethodsV0 in packages/rs-drive-abci/src/execution/platform_events/core_based_updates/update_quorum_info/v0/mod.rs is not utilized within the file. Consider removing it to clean up the codebase.

  • File: packages/rs-drive-abci/src/execution/platform_events/core_based_updates/update_quorum_info/v0/mod.rs
    • Lines: 10-12
🔗 Analysis chain

LGTM. Please clarify the usage of ValidatorSetMethodsV0.

The addition of ValidatorSetMethodsV0 to the import statement is in line with the PR objectives of moving Validator Set to DPP. However, I don't see any explicit use of this import in the current file. Could you please clarify where and how ValidatorSetMethodsV0 is being used, or if it's added preemptively for future use?

To verify the usage of ValidatorSetMethodsV0, please run the following command:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

rg "ValidatorSetMethodsV0" packages/rs-drive-abci/src/execution/platform_events/core_based_updates/update_quorum_info/v0/mod.rs

Length of output: 193

packages/rs-drive-proof-verifier/src/types.rs Show resolved Hide resolved
packages/rs-drive-proof-verifier/src/types.rs Outdated Show resolved Hide resolved
packages/dapi-grpc/protos/platform/v0/platform.proto Outdated Show resolved Hide resolved
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: 4

🧹 Outside diff range and nitpick comments (13)
packages/rs-drive-abci/src/query/system/path_elements/mod.rs (1)

23-23: Approve the error message update with a minor suggestion.

The change from "could not decode epoch info request" to "could not decode path elements" is an improvement as it more accurately reflects the context of the query_path_elements method. This update enhances error clarity without affecting functionality.

Consider further improving the error message to be more specific about the missing version:

- QueryError::DecodingError("could not decode path elements".to_string()),
+ QueryError::DecodingError("missing version in GetPathElementsRequest".to_string()),

This change would provide even more precise information about the nature of the decoding error.

packages/rs-drive-abci/src/query/system/total_credits_in_platform/mod.rs (1)

25-25: Approved: Error message update improves clarity

The change in the error message from "could not decode epoch info request" to "could not decode total credits in platform" is an improvement. It accurately reflects the context of the query_total_credits_in_platform method, enhancing clarity for developers.

Consider adding more specificity to the error message. For example:

QueryError::DecodingError(format!("Failed to decode version in GetTotalCreditsInPlatformRequest: {:?}", version))

This would provide even more context for debugging purposes.

packages/rs-drive-proof-verifier/src/unproved.rs (2)

143-150: Consider enhancing error handling for metadata extraction

While the current implementation is functional, consider providing more context in the error message when metadata is missing. This can help in debugging and troubleshooting.

Here's a suggested improvement:

 let metadata = match &response.version {
     Some(platform::get_current_quorums_info_response::Version::V0(ref v0)) => {
         v0.metadata.clone()
     }
     None => None,
 }
-.ok_or(Error::EmptyResponseMetadata)?;
+.ok_or(Error::EmptyResponseMetadata {
+    context: "Missing metadata in GetCurrentQuorumsInfoResponse".to_string(),
+})?;

This change assumes that you have an EmptyResponseMetadata variant in your Error enum that accepts a context string. If not, consider adding such a variant to provide more detailed error information.


227-232: Enhance error handling for BlsPublicKey parsing

The current error handling for BlsPublicKey parsing could be more informative. Consider including the actual error message from the parsing attempt in your ProtocolError.

Here's a suggested improvement:

 threshold_public_key: BlsPublicKey::from_bytes(
     &vs.threshold_public_key,
 )
-.map_err(|_| Error::ProtocolError {
-    error: "Invalid BlsPublicKey format".to_string(),
+.map_err(|e| Error::ProtocolError {
+    error: format!("Invalid BlsPublicKey format: {}", e),
 })?,

This change will provide more context about why the BlsPublicKey parsing failed, which can be helpful for debugging.

packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs (4)

18-29: LGTM: New trait improves abstraction. Consider adding documentation.

The introduction of the ValidatorSetMethodsV0 trait is a good design choice, encapsulating core functionality for validator set operations. This abstraction allows for potential implementation by different types, enhancing flexibility and maintainability.

Consider adding documentation comments for the trait and its methods to improve code clarity and maintainability. For example:

/// Trait defining core operations for validator sets.
pub(crate) trait ValidatorSetMethodsV0 {
    /// Computes the difference between two validator sets and returns a ValidatorSetUpdate.
    fn update_difference(&self, rhs: &ValidatorSetV0) -> Result<ValidatorSetUpdate, Error>;

    /// Converts the validator set to a ValidatorSetUpdate.
    fn to_update(&self) -> ValidatorSetUpdate;

    /// Converts the validator set to a ValidatorSetUpdate, consuming self.
    fn to_update_owned(self) -> ValidatorSetUpdate;

    /// Attempts to create a quorum from the given QuorumInfoResult and PlatformState.
    fn try_from_quorum_info_result(
        value: QuorumInfoResult,
        state: &PlatformState,
    ) -> Result<ValidatorSetV0, Error>;
}

Line range hint 35-154: LGTM: Improved validation and streamlined logic. Consider minor optimization.

The updated update_difference method provides more thorough validation of the validator sets being compared, which enhances the robustness of the code. The streamlined logic for generating ValidatorSetUpdate improves readability and maintainability.

Consider using Iterator::filter_map instead of filter followed by map to slightly optimize the code and improve readability. For example:

let validator_updates = self
    .members
    .iter()
    .filter_map(|(pro_tx_hash, old_validator_state)| {
        rhs.members.get(pro_tx_hash).and_then(|new_validator_state| {
            if new_validator_state != old_validator_state {
                // ... existing logic for creating ValidatorUpdate ...
            } else {
                None
            }
        })
    })
    .collect::<Vec<abci::ValidatorUpdate>>();

Ok(ValidatorSetUpdate {
    validator_updates,
    threshold_public_key: Some(crypto::PublicKey {
        sum: Some(Bls12381(self.threshold_public_key.to_bytes().to_vec())),
    }),
    quorum_hash: self.quorum_hash.to_byte_array().to_vec(),
})

This change would eliminate the need for the Result wrapping and unwrapping, simplifying the code structure.


Line range hint 204-249: LGTM: Efficient consuming update method added. Consider minor optimization.

The new to_update_owned method is a valuable addition, providing an efficient way to create a ValidatorSetUpdate by consuming self. This can be particularly useful in scenarios where the ValidatorSetV0 is no longer needed after creating the update.

Consider using Iterator::filter_map instead of filter_map followed by map to slightly optimize the code and improve readability. For example:

ValidatorSetUpdate {
    validator_updates: validator_set
        .into_values()
        .filter_map(|validator| {
            let ValidatorV0 {
                pro_tx_hash,
                public_key,
                node_ip,
                node_id,
                platform_p2p_port,
                is_banned,
                ..
            } = validator;

            if is_banned {
                return None;
            }

            let node_address = format!(
                "tcp://{}@{}:{}",
                hex::encode(node_id.to_byte_array()),
                node_ip,
                platform_p2p_port
            );

            Some(abci::ValidatorUpdate {
                pub_key: public_key.map(|public_key| crypto::PublicKey {
                    sum: Some(Bls12381(public_key.to_bytes().to_vec())),
                }),
                power: 100,
                pro_tx_hash: pro_tx_hash.to_byte_array().to_vec(),
                node_address,
            })
        })
        .collect(),
    threshold_public_key: Some(crypto::PublicKey {
        sum: Some(Bls12381(threshold_public_key.to_bytes().to_vec())),
    }),
    quorum_hash: quorum_hash.to_byte_array().to_vec(),
}

This change would eliminate the need for the separate if statement and return, simplifying the code structure.


Line range hint 253-308: LGTM: Correct implementation with good error handling. Consider minor improvement.

The try_from_quorum_info_result method correctly handles the conversion from QuorumInfoResult to ValidatorSetV0, with appropriate error handling using the ? operator for propagating errors.

Consider using map_err to provide more context to the error when converting the BlsPublicKey. This can help in debugging and error tracing. For example:

let threshold_public_key = BlsPublicKey::from_bytes(quorum_public_key.as_slice())
    .map_err(|e| ExecutionError::BlsErrorFromDashCoreResponse(e)
        .context("Failed to convert quorum public key"))?;

This change would provide more context about where the error occurred, which can be helpful in complex systems.

packages/rs-platform-version/src/version/v1.rs (1)

984-988: LGTM! Consider adding a comment for clarity.

The addition of current_quorums_info to the system query versions is consistent with the PR objectives and follows the existing structure. This new field will enable querying current quorum information, which is a valuable addition to the platform's capabilities.

Consider adding a brief comment above this field to explain its purpose and how it relates to the new RPC for retrieving current quorum information. This would enhance code readability and maintainability.

packages/rs-platform-version/src/version/v4.rs (1)

986-990: LGTM. Consider updating documentation.

The addition of the current_quorums_info field to DriveAbciQuerySystemVersions is well-structured and consistent with the existing code. This new field likely enables querying current quorum information, which aligns with the PR objectives.

Consider updating any relevant documentation to reflect this new querying capability for current quorum information.

packages/rs-platform-version/src/version/mocks/v2_test.rs (1)

985-989: LGTM! Consider minor formatting adjustment.

The addition of current_quorums_info is consistent with the PR objectives and follows the existing pattern for introducing new features. This change enables querying current quorum information, which is a valuable addition to the system's capabilities.

For consistency with the surrounding code, consider adjusting the indentation of the new field to match the others:

                 current_quorums_info: FeatureVersionBounds {
-                    min_version: 0,
-                    max_version: 0,
-                    default_current_version: 0,
-                },
+                     min_version: 0,
+                     max_version: 0,
+                     default_current_version: 0,
+                 },
packages/rs-platform-version/src/version/mocks/v3_test.rs (1)

985-989: LGTM! Consider grouping related fields.

The addition of current_quorums_info is consistent with the PR objectives and follows the existing structure. Good job!

Consider grouping this new field with other related quorum or system info fields if any exist in this struct. This could improve code readability and organization.

packages/rs-platform-version/src/version/v3.rs (1)

991-995: LGTM. Consider adding documentation for the new field.

The addition of the current_quorums_info field to DriveAbciQuerySystemVersions is appropriate and consistent with the structure's existing fields. This new field likely introduces the ability to query current quorum information, which aligns with the PR objectives.

Consider adding a brief comment above this field to explain its purpose and any specific behavior related to quorum information querying.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ff0eded and 5b5833b.

📒 Files selected for processing (20)
  • packages/dapi-grpc/protos/platform/v0/platform.proto (2 hunks)
  • packages/rs-dpp/Cargo.toml (5 hunks)
  • packages/rs-dpp/src/core_types/validator/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/core_types/validator_set/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/lib.rs (1 hunks)
  • packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs (8 hunks)
  • packages/rs-drive-abci/src/query/system/current_quorums_info/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/query/system/path_elements/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/query/system/total_credits_in_platform/mod.rs (1 hunks)
  • packages/rs-drive-proof-verifier/src/lib.rs (1 hunks)
  • packages/rs-drive-proof-verifier/src/types.rs (2 hunks)
  • packages/rs-drive-proof-verifier/src/unproved.rs (1 hunks)
  • packages/rs-platform-version/src/version/drive_abci_versions.rs (1 hunks)
  • packages/rs-platform-version/src/version/mocks/v2_test.rs (1 hunks)
  • packages/rs-platform-version/src/version/mocks/v3_test.rs (1 hunks)
  • packages/rs-platform-version/src/version/v1.rs (1 hunks)
  • packages/rs-platform-version/src/version/v2.rs (1 hunks)
  • packages/rs-platform-version/src/version/v3.rs (1 hunks)
  • packages/rs-platform-version/src/version/v4.rs (1 hunks)
  • packages/rs-sdk/src/platform/fetch_unproved.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (9)
  • packages/dapi-grpc/protos/platform/v0/platform.proto
  • packages/rs-dpp/Cargo.toml
  • packages/rs-dpp/src/core_types/validator/v0/mod.rs
  • packages/rs-dpp/src/core_types/validator_set/v0/mod.rs
  • packages/rs-dpp/src/lib.rs
  • packages/rs-drive-abci/src/query/system/current_quorums_info/mod.rs
  • packages/rs-drive-proof-verifier/src/lib.rs
  • packages/rs-drive-proof-verifier/src/types.rs
  • packages/rs-sdk/src/platform/fetch_unproved.rs
🔇 Additional comments (7)
packages/rs-drive-proof-verifier/src/unproved.rs (3)

1-124: LGTM: Well-structured trait definition with clear documentation

The imports and trait definition for FromUnproved are well-organized and properly documented. The trait provides a clear interface for parsing unproved responses, which enhances code readability and maintainability.


237-251: LGTM: Proper struct creation and return

The creation of the CurrentQuorumsInfo struct and its return along with metadata is implemented correctly. All required fields are properly populated with parsed values, and the use of metadata for certain fields is appropriate.


1-251: Overall assessment: Solid implementation with room for improvements

The unproved.rs file introduces a well-structured FromUnproved trait and its implementation for CurrentQuorumsInfo. The parsing logic for quorum information is comprehensive and handles complex nested structures effectively. However, there are a few areas where the code could be improved:

  1. Error handling could be more informative in some places, particularly for metadata extraction and BlsPublicKey parsing.
  2. There's some duplication in hash validation logic that could be refactored into a helper function.
  3. The use of a placeholder value for node_id should be reconsidered to avoid potential issues.

Addressing these points will enhance the robustness and maintainability of the code. Overall, the implementation is solid and provides a good foundation for handling unproved quorum information.

packages/rs-drive-abci/src/platform_types/validator_set/v0/mod.rs (2)

5-12: LGTM: Import changes align with new structure.

The changes in imports reflect the restructuring of the code, particularly the introduction of the new ValidatorSetMethodsV0 trait and the shift towards using types from the dpp crate. This aligns well with the new trait-based approach and suggests improved modularity.


Line range hint 157-202: LGTM: Efficient non-consuming update method added.

The new to_update method is a valuable addition, providing an efficient way to create a ValidatorSetUpdate without consuming self. This allows for more flexible usage in different contexts.

packages/rs-platform-version/src/version/v2.rs (1)

984-988: LGTM. Please provide more context about the current_quorums_info feature.

The addition of the current_quorums_info field to the PlatformVersion struct is implemented correctly. The FeatureVersionBounds are initialized appropriately with all versions set to 0, which is consistent with introducing a new feature.

Could you provide more information about the purpose and functionality of the current_quorums_info feature? This context would be helpful for understanding its role in the platform version configuration.

packages/rs-platform-version/src/version/mocks/v3_test.rs (1)

Line range hint 1-1089: Consider adding documentation and clarify version numbers.

While the changes look good, I have a couple of suggestions to improve the overall code quality:

  1. This large constant structure could benefit from some documentation explaining its purpose and how it's used in tests. Consider adding a doc comment at the beginning of the constant.

  2. Most version numbers, including the newly added current_quorums_info, are set to 0. While this might be intentional for a test mock, it would be helpful to confirm if this is the desired behavior or if some of these should have different values.

Example documentation:

/// TEST_PLATFORM_V3 represents a mock PlatformVersion used for testing.
/// It includes various feature versions and configuration settings.
/// Note: Most version numbers are set to 0 for testing purposes.
pub const TEST_PLATFORM_V3: PlatformVersion = ...

Could you clarify if setting all version numbers to 0 is intentional for this test mock? If not, which ones should have different values?

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

🧹 Outside diff range and nitpick comments (5)
packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbrpc.h (1)

528-534: New methods added to Platform protocol for backwards compatibility.

The addition of getCurrentQuorumsInfoWithRequest:handler: and RPCTogetCurrentQuorumsInfoWithRequest:handler: methods to the Platform protocol maintains consistency with other RPC methods in this deprecated API set. This ensures backwards compatibility while encouraging the use of the newer Platform2 protocol.

However, it's worth noting that these methods lack the deprecation warning comments present for some other methods in this protocol.

Consider adding deprecation warning comments to these new methods, similar to other methods in this protocol, to encourage users to adopt the newer Platform2 protocol. For example:

/**
 * This method belongs to a set of APIs that have been deprecated. Using the v2 API is recommended.
 */
- (void)getCurrentQuorumsInfoWithRequest:(GetCurrentQuorumsInfoRequest *)request handler:(void(^)(GetCurrentQuorumsInfoResponse *_Nullable response, NSError *_Nullable error))handler;

/**
 * This method belongs to a set of APIs that have been deprecated. Using the v2 API is recommended.
 */
- (GRPCProtoCall *)RPCTogetCurrentQuorumsInfoWithRequest:(GetCurrentQuorumsInfoRequest *)request handler:(void(^)(GetCurrentQuorumsInfoResponse *_Nullable response, NSError *_Nullable error))handler;
packages/dapi-grpc/clients/platform/v0/web/platform_pb_service.js (2)

292-299: LGTM! Consider adding a comment for consistency.

The addition of the getCurrentQuorumsInfo method to the Platform service is well-structured and follows the established pattern. It correctly defines a unary RPC with appropriate request and response types.

For consistency with other methods in this file, consider adding a brief comment describing the purpose of this method. For example:

// Get information about current quorums
Platform.getCurrentQuorumsInfo = {
  // ... (rest of the code remains the same)
};

1269-1298: LGTM! Consider refactoring for improved code reusability.

The implementation of getCurrentQuorumsInfo in the PlatformClient prototype is well-structured and consistent with other methods in the class. It correctly handles the gRPC unary call, manages callbacks, and provides error handling.

To improve code reusability and reduce duplication, consider extracting the common pattern of these methods into a higher-order function. This would make the code more maintainable and less prone to errors when adding new methods. Here's a suggested refactor:

function createUnaryMethod(methodName) {
  return function(requestMessage, metadata, callback) {
    if (arguments.length === 2) {
      callback = arguments[1];
    }
    var client = grpc.unary(Platform[methodName], {
      request: requestMessage,
      host: this.serviceHost,
      metadata: metadata,
      transport: this.options.transport,
      debug: this.options.debug,
      onEnd: function (response) {
        if (callback) {
          if (response.status !== grpc.Code.OK) {
            var err = new Error(response.statusMessage);
            err.code = response.status;
            err.metadata = response.trailers;
            callback(err, null);
          } else {
            callback(null, response.message);
          }
        }
      }
    });
    return {
      cancel: function () {
        callback = null;
        client.close();
      }
    };
  };
}

// Then, you can define methods like this:
PlatformClient.prototype.getCurrentQuorumsInfo = createUnaryMethod('getCurrentQuorumsInfo');

This refactoring would significantly reduce code duplication across all similar methods in the PlatformClient prototype.

packages/dapi-grpc/clients/platform/v0/python/platform_pb2_grpc.py (2)

373-377: Add a docstring to the getCurrentQuorumsInfo method.

While the implementation is correct, it's recommended to add a docstring to maintain consistency with other methods and improve code documentation.

Consider adding a docstring like this:

def getCurrentQuorumsInfo(self, request, context):
    """Get current quorums information.

    Args:
        request (GetCurrentQuorumsInfoRequest): The request object.
        context (grpc.ServicerContext): The gRPC service context.

    Raises:
        NotImplementedError: This method is not implemented.
    """
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

1079-1094: Add a docstring to the static getCurrentQuorumsInfo method.

The implementation of the static method is correct and consistent with other methods in the class. However, a docstring should be added to improve code documentation and maintain consistency.

Consider adding a docstring like this:

@staticmethod
def getCurrentQuorumsInfo(request,
        target,
        options=(),
        channel_credentials=None,
        call_credentials=None,
        insecure=False,
        compression=None,
        wait_for_ready=None,
        timeout=None,
        metadata=None):
    """
    Retrieve current quorums information.

    This method is used to make a unary-unary RPC call to get the current quorums information.

    Args:
        request (GetCurrentQuorumsInfoRequest): The request message.
        target (str): The target server address.
        options (tuple): Additional options for the call.
        channel_credentials (grpc.ChannelCredentials): The credentials to use for the channel.
        call_credentials (grpc.CallCredentials): The credentials to use for the call.
        insecure (bool): Whether to use an insecure channel.
        compression (grpc.Compression): The compression method to use.
        wait_for_ready (bool): Whether to wait for the server to be ready.
        timeout (float): The call timeout in seconds.
        metadata (tuple): Additional metadata for the call.

    Returns:
        A future that will eventually contain the response message.
    """
    # ... (existing implementation)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5b5833b and 19994b2.

📒 Files selected for processing (11)
  • packages/dapi-grpc/clients/platform/v0/java/org/dash/platform/dapi/v0/PlatformGrpc.java (9 hunks)
  • packages/dapi-grpc/clients/platform/v0/nodejs/platform_protoc.js (3 hunks)
  • packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbobjc.h (2 hunks)
  • packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbobjc.m (2 hunks)
  • packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbrpc.h (3 hunks)
  • packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbrpc.m (1 hunks)
  • packages/dapi-grpc/clients/platform/v0/python/platform_pb2_grpc.py (4 hunks)
  • packages/dapi-grpc/clients/platform/v0/web/platform_pb.d.ts (1 hunks)
  • packages/dapi-grpc/clients/platform/v0/web/platform_pb.js (3 hunks)
  • packages/dapi-grpc/clients/platform/v0/web/platform_pb_service.d.ts (3 hunks)
  • packages/dapi-grpc/clients/platform/v0/web/platform_pb_service.js (2 hunks)
🧰 Additional context used
🪛 Biome
packages/dapi-grpc/clients/platform/v0/web/platform_pb.d.ts

[error] 5853-5854: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (30)
packages/dapi-grpc/clients/platform/v0/web/platform_pb_service.d.ts (4)

286-293: New type definition looks good.

The new type PlatformgetCurrentQuorumsInfo is correctly defined and follows the existing pattern for other RPC methods in this file. It properly specifies the method name, service, request/response stream types, and request/response message types.


328-328: Addition to Platform class is correct.

The new static readonly property getCurrentQuorumsInfo has been added to the Platform class, following the same pattern as other RPC methods. This addition is consistent with the new type definition.


642-650: New method signatures in PlatformClient class are properly implemented.

Two new method signatures for getCurrentQuorumsInfo have been added to the PlatformClient class:

  1. One that accepts metadata as a parameter.
  2. One that doesn't require metadata.

Both signatures follow the existing pattern in the file and are correctly typed with the appropriate request and response message types.


286-293: Summary: New getCurrentQuorumsInfo RPC method successfully implemented.

The changes in this file successfully implement the new getCurrentQuorumsInfo RPC method as part of the feature to retrieve current quorum information. The additions include:

  1. A new type definition PlatformgetCurrentQuorumsInfo.
  2. An update to the Platform class with a new static readonly property.
  3. Two new method signatures in the PlatformClient class.

All changes follow the existing patterns in the file, maintaining consistency with other RPC methods. The implementation appears to be correct and complete, with no apparent issues or inconsistencies.

Also applies to: 328-328, 642-650

packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbrpc.h (3)

29-30: New class declarations added for quorum information.

The addition of GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse classes is consistent with the PR objective of introducing a new feature to retrieve current quorum information. These classes will likely be used to encapsulate the request and response data for the new RPC method.


249-251: New RPC method added to Platform2 protocol for retrieving current quorum information.

The addition of the getCurrentQuorumsInfoWithMessage:responseHandler:callOptions: method to the Platform2 protocol is in line with the PR objective. This method follows the established pattern for other RPC methods in the protocol, taking a message, response handler, and call options as parameters.


29-30: Summary of changes: New RPC method for retrieving current quorum information.

The changes in this file successfully implement the new feature for retrieving current quorum information. The additions include:

  1. New class declarations for request and response objects.
  2. A new RPC method in the Platform2 protocol.
  3. Corresponding methods in the deprecated Platform protocol for backwards compatibility.

These changes are consistent with the existing code structure and follow the established patterns for RPC method declarations in this file. The implementation aligns well with the PR objectives and should integrate smoothly with the existing codebase.

Also applies to: 249-251, 528-534

packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbrpc.m (1)

758-776: LGTM! New method implementation is consistent with existing patterns.

The new getCurrentQuorumsInfo method is well-implemented and follows the established pattern in the Platform class. It correctly includes three variations:

  1. A simple method to start the RPC call
  2. A method to create and return a not-yet-started RPC object
  3. A method to create and return a unary proto call

The implementation uses appropriate types (GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse) and follows the correct naming conventions. The use of GRPCProtoCall and GRPCUnaryProtoCall is consistent with gRPC best practices.

packages/dapi-grpc/clients/platform/v0/python/platform_pb2_grpc.py (3)

172-176: LGTM: New method getCurrentQuorumsInfo added to PlatformStub.

The implementation follows the established pattern for other methods in the class. It correctly sets up the gRPC channel, and handles serialization and deserialization appropriately.


537-541: LGTM: getCurrentQuorumsInfo correctly added to add_PlatformServicer_to_server.

The new method is properly integrated into the rpc_method_handlers dictionary, maintaining consistency with other entries. Serialization and deserialization are handled correctly.


Line range hint 1-1094: Summary: New getCurrentQuorumsInfo method successfully integrated.

The changes effectively introduce the new getCurrentQuorumsInfo functionality to the gRPC service. The implementation is consistent with existing code patterns and correctly handles serialization, deserialization, and gRPC channel setup. Minor improvements in documentation (adding docstrings) were suggested to enhance code readability and maintain consistency with best practices.

packages/dapi-grpc/clients/platform/v0/java/org/dash/platform/dapi/v0/PlatformGrpc.java (4)

979-1008: Method descriptor for getCurrentQuorumsInfo looks good.

The implementation of the method descriptor for getCurrentQuorumsInfo is correct and consistent with other method descriptors in the file. It properly sets up the request and response types, method type, full method name, and marshalling for request and response objects.


1290-1295: Implementations of getCurrentQuorumsInfo in service and client stubs are correct.

The getCurrentQuorumsInfo method has been properly implemented in:

  • PlatformImplBase class
  • PlatformStub class
  • PlatformBlockingStub class
  • PlatformFutureStub class

All implementations use the correct request and response types, have matching method signatures, and use proper call options and channel methods.

Also applies to: 1804-1810, 2059-2064, 2344-2350


2384-2384: Method ID for getCurrentQuorumsInfo is correctly assigned.

The method ID for getCurrentQuorumsInfo is properly defined with the value 31, which appears to be the next available ID in the sequence. This assignment is consistent with the pattern used for other methods in the file.


2527-2530: getCurrentQuorumsInfo is correctly included in the service definition.

The getCurrentQuorumsInfo method has been properly integrated into the service definition:

  1. It's correctly added to the MethodHandlers switch statement with the right method ID.
  2. The method is included in the service descriptor builder.

These additions ensure that the new method is fully integrated into the gRPC service.

Also applies to: 2623-2623

packages/dapi-grpc/clients/platform/v0/nodejs/platform_protoc.js (3)

78-85: New exports for GetCurrentQuorumsInfo messages

The code correctly exports the new message types for GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse, along with their nested classes. This ensures that these messages are available for use throughout the application.


4133-4258: Definition of GetCurrentQuorumsInfoRequest and related message classes

The code properly defines constructors and prototype inheritance for the new message types:

  • GetCurrentQuorumsInfoRequest
  • GetCurrentQuorumsInfoRequest.GetCurrentQuorumsInfoRequestV0
  • GetCurrentQuorumsInfoResponse
  • GetCurrentQuorumsInfoResponse.ValidatorV0
  • GetCurrentQuorumsInfoResponse.ValidatorSetV0
  • GetCurrentQuorumsInfoResponse.GetCurrentQuorumsInfoResponseV0

This setup is essential for correct message serialization and deserialization in the gRPC client.


44168-45523: Implementation of serialization and deserialization methods

The code implements serialization and deserialization methods for the newly added messages. By defining methods like serializeBinary, deserializeBinary, and toObject, the messages can be accurately converted to and from the protobuf wire format. This ensures seamless communication over the network.

packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbobjc.h (2)

57-60: New Class Declarations Added Correctly

The new class declarations for GetCurrentQuorumsInfoRequest_GetCurrentQuorumsInfoRequestV0, GetCurrentQuorumsInfoResponse_GetCurrentQuorumsInfoResponseV0, GetCurrentQuorumsInfoResponse_ValidatorSetV0, and GetCurrentQuorumsInfoResponse_ValidatorV0 are appropriately added and follow the existing naming conventions.


4840-4963: Implementation of New RPC Methods Aligns with Codebase Standards

The addition of the GetCurrentQuorumsInfoRequest and GetCurrentQuorumsInfoResponse classes, along with their associated nested classes and enums, is well-structured and consistent with the codebase's existing patterns. The properties and methods are accurately defined, and the implementation adheres to Objective-C conventions.

packages/dapi-grpc/clients/platform/v0/objective-c/Platform.pbobjc.m (7)

67-72: New class declarations are correctly added

The class declarations for the new classes related to quorum information are added properly and follow the naming conventions:

  • GetCurrentQuorumsInfoRequest
  • GetCurrentQuorumsInfoRequest_GetCurrentQuorumsInfoRequestV0
  • GetCurrentQuorumsInfoResponse
  • GetCurrentQuorumsInfoResponse_GetCurrentQuorumsInfoResponseV0
  • GetCurrentQuorumsInfoResponse_ValidatorSetV0
  • GetCurrentQuorumsInfoResponse_ValidatorV0

12446-12497: Implementation of GetCurrentQuorumsInfoRequest is correctly defined

The GetCurrentQuorumsInfoRequest class is implemented correctly with dynamic properties and the descriptor method. The oneof field version is set up appropriately, and the storage structure is properly defined.


12498-12533: Implementation of GetCurrentQuorumsInfoRequest_GetCurrentQuorumsInfoRequestV0 is correctly defined

The subclass GetCurrentQuorumsInfoRequest_GetCurrentQuorumsInfoRequestV0 is implemented properly with an empty descriptor, as there are no fields defined. The class setup is correct and follows the required structure.


12536-12593: Implementation of GetCurrentQuorumsInfoResponse is correctly defined

The GetCurrentQuorumsInfoResponse class is implemented correctly with dynamic properties and the descriptor method. The oneof field version is set up appropriately, matching the request class structure.


12594-12658: Implementation of GetCurrentQuorumsInfoResponse_ValidatorV0 is correctly defined

The GetCurrentQuorumsInfoResponse_ValidatorV0 class is implemented properly with dynamic properties for proTxHash, nodeIp, and isBanned. The storage structure and field descriptors are correctly set up, ensuring proper memory management.


12660-12737: Implementation of GetCurrentQuorumsInfoResponse_ValidatorSetV0 is correctly defined

The GetCurrentQuorumsInfoResponse_ValidatorSetV0 class is implemented correctly with dynamic properties for quorumHash, coreHeight, membersArray, and thresholdPublicKey. The storage structure and field descriptors are accurately defined.


12739-12828: Implementation of GetCurrentQuorumsInfoResponse_GetCurrentQuorumsInfoResponseV0 is correctly defined

The GetCurrentQuorumsInfoResponse_GetCurrentQuorumsInfoResponseV0 class is implemented properly with dynamic properties for quorumHashesArray, currentQuorumHash, validatorSetsArray, lastBlockProposer, and metadata. The storage structure and field descriptors are appropriately set up, ensuring accurate data handling.

packages/dapi-grpc/clients/platform/v0/web/platform_pb.js (3)

78-85: New export symbols for 'GetCurrentQuorumsInfo' messages added.

The new message types GetCurrentQuorumsInfoRequest, GetCurrentQuorumsInfoResponse, and their nested versions are correctly exported.


4133-4258: Definition of 'GetCurrentQuorumsInfoRequest' message classes.

The classes for GetCurrentQuorumsInfoRequest and its nested GetCurrentQuorumsInfoRequestV0 are properly defined, including constructors and inheritance from jspb.Message.


44168-45524: Implementation of serialization and deserialization methods.

The serialization, deserialization, and toObject methods for GetCurrentQuorumsInfoRequest, GetCurrentQuorumsInfoResponse, and their nested message types are correctly implemented following Protocol Buffers JavaScript conventions.

Comment on lines +5853 to +5854
export type AsObject = {
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid using '{}' as a type; explicitly define the object shape.

The AsObject type is currently defined as an empty object {}. Using {} as a type is discouraged because it matches any non-nullable value, which may not be the intended behavior. It's better to explicitly define the object shape or omit the AsObject type if it has no fields.

Apply this diff to remove the empty AsObject type:

 export namespace GetCurrentQuorumsInfoRequestV0 {
-    export type AsObject = {
-    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export type AsObject = {
}
export namespace GetCurrentQuorumsInfoRequestV0 {
}
🧰 Tools
🪛 Biome

[error] 5853-5854: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

/// * `Ok(Some(Self))` when object is found.
/// * `Ok(None)` when object is not found.
/// * [`Err(Error)`](Error) when an error occurs.
async fn fetch_unproved_with_settings(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have a default implementation here, in a similar way to Fetch?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's just do that in another PR.

lklimek
lklimek previously approved these changes Sep 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dapi-endpoint DAPI endpoint addition or modification
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants