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: wasm sdk build proof-of-concept #2405

Open
wants to merge 37 commits into
base: v2.0-dev
Choose a base branch
from
Open

Conversation

lklimek
Copy link
Contributor

@lklimek lklimek commented Dec 20, 2024

Issue being fixed or feature implemented

To make some decisions about direction in which we should move,
we need to validate if it's possible and reasonable to create WASM
bindings for Rust Dash SDK.

What was done?

  1. Adjusted features to work with wasm32
  2. Implemented WASM transport and other WASM-specific logic

How Has This Been Tested?

Created simple test web page in packages/wasm-sdk/index.html that tests SDK.

Note: It requires hardcoding quorums in packages/wasm-sdk/src/context_provider.rs.

Breaking Changes

TODO

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

  • Added WebAssembly (WASM) SDK support for Dash Platform.
  • Introduced a new context provider for WebAssembly environments.
  • Enhanced support for identity and data contract operations with new methods in the SDK.
  • Added support for CA certificates in the SDK for secure connections.

🔧 Improvements

  • Optimized gRPC transport layer for different target architectures.
  • Improved error handling across multiple modules.
  • Enhanced support for WASM and non-WASM compilation targets.
  • Updated dependency configurations for better performance and flexibility.
  • Introduced new asynchronous functions for verifying identities and data contracts.

🛠 Technical Enhancements

  • Implemented conditional compilation for platform-specific features.
  • Refined timestamp handling and conversion methods.
  • Updated serialization and deserialization processes.
  • Improved proof verification mechanisms.
  • Added new utility functions for document transitions.

🌐 Platform Compatibility

  • Added support for WebAssembly (WASM) targets.
  • Enhanced cross-platform development capabilities.
  • Improved network connection and security configurations.

🔒 Security

  • Enhanced error handling and validation processes.
  • Improved cryptographic key management.

These release notes provide a high-level overview of the significant changes in this update, highlighting the improvements in platform compatibility, performance, and developer experience.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

This pull request introduces comprehensive support for WebAssembly (Wasm) in the Dash SDK, focusing on creating a new wasm-sdk package and configuring various dependencies and modules to enable cross-platform functionality. The changes span multiple packages, adding Wasm-specific configurations, implementing context providers, error handling, and creating interfaces for identity, data contract, and document interactions in a WebAssembly environment.

Changes

File Change Summary
.cargo/config* Added WebAssembly target configuration with getrandom backend for Wasm
Cargo.toml Excluded packages/wasm-sdk from workspace
packages/dapi-grpc/Cargo.toml Updated dependencies and features for Wasm compatibility
packages/rs-dapi-client/Cargo.toml Added Wasm-specific dependencies and feature configurations
packages/rs-dpp/src/* Modified architecture-specific module conditionals
packages/wasm-sdk/* New package with Wasm SDK implementation, including context provider, error handling, and SDK interfaces

Possibly related PRs

  • perf(dpp): reduce JS binding size by 3x #2396: This PR focuses on optimizing the WebAssembly (wasm) size using Binaryen, which is relevant to the main PR's changes that involve adding configuration for the wasm32-unknown-unknown target and the getrandom crate for WebAssembly.
  • build!: update rust to 1.83 - backport #2393 to v1.7 #2398: This PR updates the Rust version to 1.83, which is relevant as it may affect the compatibility and functionality of the changes made in the main PR regarding WebAssembly configurations.

Suggested Reviewers

  • shumkov
  • QuantumExplorer

Poem

🐰 A Rabbit's WebAssembly Tale 🌐
In bytes of magic, Wasm takes flight,
Dash SDK dancing with JavaScript's might,
Identities leap, contracts unfurl,
A web of code begins to swirl!
Hop, hop, hurray! 🎉


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7213a7 and 8993532.

📒 Files selected for processing (3)
  • packages/rs-dapi-client/Cargo.toml (2 hunks)
  • packages/rs-dapi-client/src/transport/tonic_channel.rs (1 hunks)
  • packages/rs-dapi-client/tests/local_platform_connectivity.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/rs-dapi-client/src/transport/tonic_channel.rs
  • packages/rs-dapi-client/Cargo.toml
  • packages/rs-dapi-client/tests/local_platform_connectivity.rs

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.

@lklimek lklimek mentioned this pull request Jan 13, 2025
6 tasks
@shumkov shumkov changed the base branch from v1.8-dev to v2.0-dev January 16, 2025 14:46
@lklimek lklimek changed the title feat: PoC of wasm sdk build feat: wasm sdk build proof-of-concept Jan 22, 2025
@lklimek lklimek marked this pull request as ready for review January 22, 2025 15:18
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: 19

🔭 Outside diff range comments (1)
packages/wasm-dpp/Cargo.toml (1)

Line range hint 13-16: Improve wasm-bindgen version management.

The TODO comment indicates that wasm-bindgen version updates require manual changes in multiple places. Consider:

  1. Using a workspace variable for the version
  2. Implementing the suggested build.rs solution

Would you like me to help implement a build.rs solution to manage wasm-bindgen versions centrally?

🧹 Nitpick comments (26)
packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs (1)

41-41: LGTM! Consider enhancing the error message.

The timestamp handling changes look good. The conversion from to_milis() to to_millis() and the added error handling improve code robustness.

Consider making the error message more specific:

-            .map_err(|e| AbciError::BadRequest(format!("genesis time is invalid: {}", e)))?
+            .map_err(|e| AbciError::BadRequest(format!("failed to convert genesis time to milliseconds: {}", e)))?

Also applies to: 68-70

packages/wasm-sdk/index.html (2)

18-27: Enhance accessibility and user experience.

The input sections lack proper form structure, validation, and accessibility attributes.

Consider these improvements:

-<div class="container">
-<input type="text" id="identityInput" placeholder="Enter Identity ID" />
-<button id="fetchButton">Fetch Identity</button>
-</div>
+<form class="container" onsubmit="return false;">
+  <label for="identityInput">Identity ID:</label>
+  <input 
+    type="text" 
+    id="identityInput" 
+    placeholder="Enter Identity ID"
+    pattern="^[a-zA-Z0-9]+$"
+    required
+    aria-label="Identity ID input"
+  />
+  <button 
+    id="fetchButton"
+    aria-label="Fetch identity information"
+  >Fetch Identity</button>
+</form>

Apply similar changes to the Data Contract input section.


1-85: Overall implementation provides a good foundation for testing.

While this implementation serves well as a proof-of-concept, consider the suggested improvements for better production readiness:

  1. Enhanced error handling and input validation
  2. Improved accessibility
  3. Better code organization and reduced duplication
  4. Security considerations

The basic functionality demonstrates successful WASM SDK integration.

Consider splitting this into separate HTML, CSS, and JavaScript files for better maintainability as the implementation grows.

packages/rs-dapi-client/src/transport/wasm_channel.rs (2)

77-82: Expand error handling in wasm_client_error_to_status

The current implementation of wasm_client_error_to_status only handles TonicStatusError, mapping all other errors to Status::internal. This may not cover all possible error cases appropriately. Consider expanding the error handling to map other specific error variants to more relevant gRPC status codes.


90-90: Consider organizing WasmBackonSleeper into a separate module

There's a TODO comment suggesting moving WasmBackonSleeper to a different module. Organizing code into appropriate modules enhances maintainability and readability. Evaluate whether moving this struct aligns with the project's module structure.

Do you want me to suggest a suitable module for WasmBackonSleeper?

packages/wasm-sdk/src/sdk.rs (1)

77-78: Enhance error context in build method

The build method returns an error using the ? operator without adding context. To improve debugging and user experience, consider enhancing the error message with additional context or mapping it to a more descriptive error.

packages/wasm-sdk/src/verify.rs (1)

183-190: Expand functionality in DocumentWasm

Currently, DocumentWasm only provides the id method. To enhance usability, consider implementing additional methods to expose more of the document's properties and behaviors to the Wasm interface.

packages/wasm-sdk/src/dpp.rs (2)

66-67: Ensure meaningful error messages in set_public_keys

The error message in set_public_keys may not provide useful information to the user. Using public_keys.to_string() might not yield a readable representation of the input. Consider providing a clearer error message that helps the user understand what went wrong.


54-62: Remove commented-out code to improve code cleanliness

There are multiple blocks of commented-out code in the file. Removing unnecessary commented code can enhance readability and maintainability.

Also applies to: 86-105, 141-154, 156-164, 197-221, 235-259, 274-288

packages/wasm-sdk/src/lib.rs (1)

18-24: Consider adding error logging in the start function.

While the panic hook and tracing setup look good, consider adding error logging for initialization failures to help with debugging in the browser environment.

 #[wasm_bindgen(start)]
 pub async fn start() -> Result<(), JsValue> {
     console_error_panic_hook::set_once();
     tracing_wasm::set_as_global_default();
+    tracing::info!("WASM SDK initialized successfully");
 
     Ok(())
 }
packages/dapi-grpc/src/lib.rs (1)

43-46: Consider documenting the versioning module's conditional compilation.

The versioning module's conditional compilation now includes wasm32, but it might be helpful to document why this module is needed for all targets.

-    #[cfg(any(feature = "server", feature = "client", target_arch = "wasm32"))]
+    /// The versioning module is required for all targets (server, client, and wasm32)
+    /// as it provides essential version compatibility checks for gRPC messages.
+    #[cfg(any(feature = "server", feature = "client", target_arch = "wasm32"))]
     mod versioning;
packages/rs-dapi-client/src/transport/tonic_channel.rs (1)

16-21: Remove or implement the commented code.

The commented implementation of backon::Sleeper should either be removed if not needed or implemented if required.

packages/rs-dapi-client/src/lib.rs (1)

29-32: Document the rationale for different Uri implementations.

The conditional exports for Uri type need documentation explaining why different implementations are used for WASM and non-WASM targets.

+/// Uri type is conditionally exported based on the target and features:
+/// - For WASM or non-mocks: using http::Uri for better WASM compatibility
+/// - For mocks on non-WASM: using http_serde::http::Uri for serialization support
 #[cfg(any(target_arch = "wasm32", not(feature = "mocks")))]
 pub use http::Uri;
 #[cfg(all(feature = "mocks", not(target_arch = "wasm32")))]
 pub use http_serde::http::Uri;
packages/rs-dapi-client/src/request_settings.rs (1)

86-89: Enhance documentation for CA certificate handling.

While the implementation is correct, consider adding:

  1. Documentation explaining why CA certificates are not supported in WASM
  2. Examples of how to use with_ca_certificate
  3. Security implications of using custom CA certificates

Apply this diff to improve documentation:

     /// Certificate Authority certificate to use for verifying the server's certificate.
+    /// Note: CA certificates are not supported in WASM environments due to platform limitations.
+    /// In WASM, certificate verification is handled by the browser's built-in mechanisms.
     #[cfg(not(target_arch = "wasm32"))]
     pub ca_certificate: Option<Certificate>,
 }
 impl AppliedRequestSettings {
     /// Use provided CA certificate for verifying the server's certificate.
     ///
     /// If set to None, the system's default CA certificates will be used.
+    /// 
+    /// # Examples
+    /// ```
+    /// # use std::fs;
+    /// # use dapi_grpc::tonic::transport::Certificate;
+    /// # use crate::AppliedRequestSettings;
+    /// let cert = fs::read("ca.pem").unwrap();
+    /// let cert = Certificate::from_pem(cert);
+    /// let settings = AppliedRequestSettings::default()
+    ///     .with_ca_certificate(Some(cert));
+    /// ```
+    /// 
+    /// # Security Considerations
+    /// Using custom CA certificates bypasses the system's trust store. Only use this
+    /// when connecting to known internal services with self-signed certificates.
     #[cfg(not(target_arch = "wasm32"))]
     pub fn with_ca_certificate(mut self, ca_cert: Option<Certificate>) -> Self {

Also applies to: 93-98

packages/rs-sdk/src/platform/transition/broadcast_identity.rs (1)

108-124: Enhance the unimplemented error message for WASM.

While the conditional compilation is correct, the error message could be more informative for WASM users.

Consider this improved error message:

-        unimplemented!("NativeBlsModule not implemented for wasm32");
+        unimplemented!("BLS operations are not supported in WebAssembly environment. Consider using an alternative signing method.");
packages/wasm-sdk/src/context_provider.rs (3)

39-64: Consider a more maintainable approach for quorum keys.

Hardcoding quorum keys makes updates difficult and increases maintenance overhead. Consider:

  1. Loading keys from a configuration file
  2. Implementing a dynamic fetching mechanism
  3. Adding versioning for the key set

74-80: Optimize quorum key lookup.

The current implementation performs a linear search through the quorum keys. Consider using a HashMap for O(1) lookup time.

+use std::collections::HashMap;
+use std::sync::OnceLock;
+
+static QUORUM_MAP: OnceLock<HashMap<String, String>> = OnceLock::new();
+
+fn get_quorum_map() -> &'static HashMap<String, String> {
+    QUORUM_MAP.get_or_init(|| {
+        QUORUM_KEYS
+            .iter()
+            .map(|k| {
+                let parts: Vec<&str> = k.split(':').collect();
+                (parts[0].to_string(), parts[1].to_string())
+            })
+            .collect()
+    })
+}

Then update the lookup:

-        let key_hex = QUORUM_KEYS
-            .iter()
-            .find(|key| key.starts_with(&quorum_label))
+        let quorum_hash_hex = &quorum_label[..quorum_label.len() - 1];
+        let key_hex = get_quorum_map()
+            .get(quorum_hash_hex)

20-23: Remove specific container references from comments.

The script comments contain specific docker container references that may become outdated. Consider generalizing the documentation.

-  docker exec -ti dashmate_2d59c0c6_mainnet-core-1 dash-cli $@
+  # Use your local dash-cli installation or appropriate container
+  dash-cli $@
packages/rs-dpp/src/data_contract/document_type/index/mod.rs (1)

527-533: Remove redundant to_string() in format args.

The validation logic is correct, but there's a minor optimization opportunity.

Apply this diff to remove the redundant to_string() call:

-                                                        e.to_string()
+                                                        e
🧰 Tools
🪛 GitHub Check: Rust packages (dpp) / Linting

[warning] 531-531: to_string applied to a type that implements Display in format! args
warning: to_string applied to a type that implements Display in format! args
--> packages/rs-dpp/src/data_contract/document_type/index/mod.rs:531:58
|
531 | ... e.to_string()
| ^^^^^^^^^^^^ help: remove this
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_in_format_args
= note: #[warn(clippy::to_string_in_format_args)] on by default

packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs (2)

724-724: Consider breaking down this large function.

The TODO comment correctly identifies that this function is quite large. Consider decomposing it into smaller, more focused functions for better maintainability.

Some suggestions for breaking it down:

  • Extract the type handling logic into a separate function
  • Create a dedicated function for handling nested properties
  • Move the property sorting logic to its own function

Line range hint 725-844: LGTM with some observations.

The function correctly handles:

  • Schema references through resolve_uri
  • Different property types (integer, number, string, array, object)
  • Nested property structures
  • Property sorting by position
  • Required and transient fields

The implementation is thorough and maintains proper error handling.

Consider these architectural improvements:

  1. The nested property handling could be made more efficient by using iterators instead of collecting into vectors
  2. The property type matching could be simplified using a type registry pattern
packages/rs-sdk/src/sdk.rs (1)

551-552: Consider the architectural implications of the TODO comments.

The comments suggest potential improvements to the context provider initialization.

Consider:

  1. Making the context provider immutable after SDK initialization
  2. Using a builder pattern for context provider configuration
  3. Documenting the thread-safety implications of the current design
packages/wasm-sdk/Cargo.toml (1)

6-7: Consider adding "rlib" to crate-type.

The crate type is currently set to only ["cdylib"]. Adding "rlib" would allow the crate to be used as a dependency by other Rust crates while maintaining Wasm compatibility.

[lib]
-crate-type = ["cdylib"]
+crate-type = ["cdylib", "rlib"]
Cargo.toml (1)

35-35: Consider implications of workspace exclusion.

While excluding experimental packages is reasonable, this might lead to:

  1. Duplicate dependencies if not managed carefully
  2. Version mismatches between workspace and excluded package dependencies
  3. Longer build times due to separate compilation

Consider documenting these implications and the criteria for including the package in the workspace once it's ready.

packages/wasm-dpp/scripts/build-wasm.sh (1)

52-52: Optimize wasm-opt flags for better efficiency.

The current wasm-opt command includes multiple GUFA passes (--gufa -Oz --gufa -Oz --gufa -Oz) which might be redundant. A single GUFA pass followed by -Oz should be sufficient as subsequent passes are unlikely to yield additional benefits.

Consider simplifying to:

-  wasm-opt -tnh --flatten --rereloop -Oz --gufa -Oz --gufa -Oz  "$OUTPUT_FILE" -o "$OUTPUT_FILE"
+  wasm-opt -tnh --flatten --rereloop --gufa -Oz "$OUTPUT_FILE" -o "$OUTPUT_FILE"
packages/rs-drive/Cargo.toml (1)

29-32: Remove redundant package name.

The package = "dpp" specification is redundant since it matches the dependency name.

-dpp = { package = "dpp", path = "../rs-dpp", features = [
+dpp = { path = "../rs-dpp", features = [
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd1527d and 2336773.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (60)
  • .cargo/config-release.toml (1 hunks)
  • .cargo/config.toml (1 hunks)
  • Cargo.toml (1 hunks)
  • packages/dapi-grpc/Cargo.toml (2 hunks)
  • packages/dapi-grpc/build.rs (4 hunks)
  • packages/dapi-grpc/src/lib.rs (1 hunks)
  • packages/js-dapi-client/package.json (1 hunks)
  • packages/rs-dapi-client/Cargo.toml (2 hunks)
  • packages/rs-dapi-client/src/address_list.rs (1 hunks)
  • packages/rs-dapi-client/src/connection_pool.rs (1 hunks)
  • packages/rs-dapi-client/src/dapi_client.rs (7 hunks)
  • packages/rs-dapi-client/src/executor.rs (2 hunks)
  • packages/rs-dapi-client/src/lib.rs (1 hunks)
  • packages/rs-dapi-client/src/request_settings.rs (3 hunks)
  • packages/rs-dapi-client/src/transport.rs (1 hunks)
  • packages/rs-dapi-client/src/transport/grpc.rs (2 hunks)
  • packages/rs-dapi-client/src/transport/tonic_channel.rs (1 hunks)
  • packages/rs-dapi-client/src/transport/wasm_channel.rs (1 hunks)
  • packages/rs-dpp/Cargo.toml (5 hunks)
  • packages/rs-dpp/src/balances/credits.rs (0 hunks)
  • packages/rs-dpp/src/bls/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/data_contract_facade.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v0/mod.rs (1 hunks)
  • packages/rs-dpp/src/data_contract/document_type/index/mod.rs (5 hunks)
  • packages/rs-dpp/src/data_contract/mod.rs (1 hunks)
  • packages/rs-dpp/src/identity/identity_facade.rs (1 hunks)
  • packages/rs-dpp/src/lib.rs (0 hunks)
  • packages/rs-dpp/src/util/deserializer.rs (0 hunks)
  • packages/rs-dpp/src/util/json_schema.rs (1 hunks)
  • packages/rs-drive-abci/Cargo.toml (2 hunks)
  • packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs (2 hunks)
  • packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs (3 hunks)
  • packages/rs-drive-abci/src/mimic/mod.rs (2 hunks)
  • packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs (6 hunks)
  • packages/rs-drive-abci/src/platform_types/cleaned_abci_messages/request_init_chain_cleaned_params/v0/mod.rs (2 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/execution.rs (3 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/query.rs (5 hunks)
  • packages/rs-drive-proof-verifier/Cargo.toml (1 hunks)
  • packages/rs-drive-proof-verifier/src/types.rs (2 hunks)
  • packages/rs-drive/Cargo.toml (1 hunks)
  • packages/rs-platform-value/Cargo.toml (0 hunks)
  • packages/rs-platform-value/src/inner_value_at_path.rs (3 hunks)
  • packages/rs-sdk/Cargo.toml (4 hunks)
  • packages/rs-sdk/src/platform/transition/broadcast_identity.rs (2 hunks)
  • packages/rs-sdk/src/sdk.rs (10 hunks)
  • packages/rs-sdk/src/sync.rs (4 hunks)
  • packages/wasm-dpp/Cargo.toml (1 hunks)
  • packages/wasm-dpp/scripts/build-wasm.sh (1 hunks)
  • packages/wasm-sdk/.gitignore (1 hunks)
  • packages/wasm-sdk/Cargo.toml (1 hunks)
  • packages/wasm-sdk/build.sh (1 hunks)
  • packages/wasm-sdk/index.html (1 hunks)
  • packages/wasm-sdk/src/context_provider.rs (1 hunks)
  • packages/wasm-sdk/src/dpp.rs (1 hunks)
  • packages/wasm-sdk/src/error.rs (1 hunks)
  • packages/wasm-sdk/src/lib.rs (1 hunks)
  • packages/wasm-sdk/src/sdk.rs (1 hunks)
  • packages/wasm-sdk/src/state_transitions/documents.rs (1 hunks)
  • packages/wasm-sdk/src/state_transitions/mod.rs (1 hunks)
  • packages/wasm-sdk/src/verify.rs (1 hunks)
💤 Files with no reviewable changes (4)
  • packages/rs-dpp/src/util/deserializer.rs
  • packages/rs-dpp/src/balances/credits.rs
  • packages/rs-dpp/src/lib.rs
  • packages/rs-platform-value/Cargo.toml
✅ Files skipped from review due to trivial changes (5)
  • packages/wasm-sdk/src/state_transitions/mod.rs
  • packages/rs-dapi-client/src/address_list.rs
  • packages/rs-dapi-client/src/connection_pool.rs
  • packages/wasm-sdk/.gitignore
  • packages/wasm-sdk/build.sh
🧰 Additional context used
📓 Learnings (3)
packages/rs-dapi-client/src/executor.rs (1)
Learnt from: lklimek
PR: dashpay/platform#2277
File: packages/rs-dapi-client/src/executor.rs:38-38
Timestamp: 2024-11-12T14:57:47.419Z
Learning: In `packages/rs-dapi-client/src/executor.rs`, for the structs `ExecutionError<E>` and `ExecutionResponse<R>`, only the serde derives (`Serialize`, `Deserialize`) should be conditional based on the "mocks" feature; the other derives (`Debug`, `Clone`, `Eq`, `PartialEq`) should always be present.
packages/rs-drive-abci/Cargo.toml (1)
Learnt from: shumkov
PR: dashpay/platform#2375
File: packages/rs-drive-abci/Cargo.toml:61-63
Timestamp: 2024-12-05T09:29:38.918Z
Learning: In the `drive-abci` package, avoid adding unused dependencies like `hashbrown` to `Cargo.toml`. The team relies on CI to detect dependency version issues.
packages/rs-sdk/Cargo.toml (1)
Learnt from: lklimek
PR: dashpay/platform#2277
File: packages/rs-dapi-client/Cargo.toml:22-22
Timestamp: 2024-11-12T14:57:47.419Z
Learning: In `packages/rs-dapi-client/Cargo.toml`, `backon` will not work without the `tokio-sleep` feature in our setup, so it's unnecessary to declare `tokio-sleep` as a separate feature in the `[features]` section.
🪛 GitHub Check: Rust packages (dpp) / Linting
packages/rs-dpp/src/data_contract/document_type/index/mod.rs

[warning] 531-531: to_string applied to a type that implements Display in format! args
warning: to_string applied to a type that implements Display in format! args
--> packages/rs-dpp/src/data_contract/document_type/index/mod.rs:531:58
|
531 | ... e.to_string()
| ^^^^^^^^^^^^ help: remove this
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_in_format_args
= note: #[warn(clippy::to_string_in_format_args)] on by default

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Rust packages (wasm-dpp) / Tests
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Rust packages (drive-abci) / Linting
  • GitHub Check: Rust packages (drive) / Tests
  • GitHub Check: Build Docker images (Dashmate helper, dashmate-helper, dashmate-helper) / Build Dashmate helper image
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (62)
packages/rs-drive-abci/src/execution/engine/initialization/init_chain/v0/mod.rs (1)

22-22: LGTM! Error handling improvement.

Good improvement in error handling by using AbciError::InvalidChainLock for genesis time conversion failures. The error message clearly indicates the context of the failure.

Also applies to: 158-163

packages/rs-drive-abci/src/platform_types/block_proposal/v0.rs (3)

8-13: LGTM! Well-organized imports.

Good improvement in import organization by grouping related items from tenderdash_abci::proto.


101-103: Consistent error handling for timestamp conversions.

Good improvement in error handling for block time conversions. The error messages are clear and consistent across both TryFrom implementations.

Also applies to: 109-110, 174-176, 182-185


138-138: Improved consensus versions handling.

Good change in dereferencing consensus versions with *consensus_versions to ensure proper value copying.

Also applies to: 242-242

packages/rs-drive-abci/src/execution/engine/finalize_block_proposal/v0/mod.rs (1)

12-12: LGTM! Consistent timestamp handling.

The changes maintain consistency with other files in terms of timestamp handling and error reporting.

Also applies to: 198-201

packages/rs-drive-abci/src/mimic/mod.rs (2)

41-41: Import updated for consistency.

The import has been updated from ToMilis to ToMillis to fix the typo and align with the correct method name.


242-244: Improved error handling for timestamp conversion.

The timestamp conversion now includes error handling using expect() to provide a clear error message if the conversion fails.

packages/rs-drive-abci/tests/strategy_tests/query.rs (4)

28-28: Import updated for consistency.

The import has been updated from ToMilis to ToMillis to fix the typo and align with the correct method name.


75-75: Simplified lifetime specification.

The lifetime specification has been simplified from impl<'a> ProofVerification<'a> to impl ProofVerification<'_>.


160-160: Improved error handling for timestamp conversion.

The timestamp conversion now includes error handling using expect() to provide a clear error message if the conversion fails.


171-171: Improved parameter types using slices.

The parameter types have been updated from &Vec<Identity> to &[Identity] to follow Rust best practices. Using slices instead of references to vectors provides more flexibility and better ergonomics.

Also applies to: 197-197

packages/rs-drive-abci/tests/strategy_tests/execution.rs (2)

46-46: Import updated for consistency.

The import has been updated from FromMilis to FromMillis to fix the typo and align with the correct method name.


1159-1159: Improved error handling for timestamp conversion.

The timestamp conversion now includes error handling using expect() to provide a clear error message if the conversion fails.

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

64-71: Review error propagation in poll_ready method

In the poll_ready method, errors from self.client.poll_ready(cx) are mapped using map_err(wasm_client_error_to_status). Ensure that all possible errors are correctly mapped and that the error handling in wasm_client_error_to_status is comprehensive, as noted in an earlier comment.

packages/wasm-sdk/src/sdk.rs (1)

145-155: Verify SDK configuration in epoch_testing

In the epoch_testing function, the SDK is initialized with an empty AddressList. This may prevent the SDK from connecting to any nodes, resulting in failure to fetch extended epoch information. Ensure the SDK is configured with valid node addresses.

packages/wasm-sdk/src/verify.rs (2)

28-70: Validate placeholder values in verify_identity_response

The verify_identity_response function uses empty vectors for IDs and proofs, which may not produce meaningful verification results. Ensure that these placeholders are replaced with valid data or that the function properly handles the absence of real data.


73-128: Replace placeholder data in verify_data_contract

Similar to the previous comment, verify_data_contract uses empty vectors and placeholder values. Verify that the function operates correctly with actual data, and consider implementing error handling for cases where real data is not provided.

packages/wasm-sdk/src/error.rs (1)

1-13: Error handling implementation is appropriate

The WasmError struct and the to_js_error function provide a clear way to convert Rust errors into JavaScript JsError. This approach enhances interoperability between Rust and JavaScript in the Wasm context.

packages/rs-dpp/src/bls/mod.rs (1)

1-1: Confirm native_bls compatibility with Wasm

By changing the condition to #[cfg(feature = "bls-signatures")], the native_bls module will now be included for all targets when the bls-signatures feature is enabled, including wasm32. Please verify that native_bls is compatible with the wasm32 target to avoid compilation errors.

packages/wasm-sdk/src/lib.rs (1)

10-11: LGTM! Good choice of allocator for WASM.

Using wee_alloc as the global allocator is a good choice for WebAssembly as it's designed to produce a small code size, which is crucial for WASM modules.

packages/dapi-grpc/src/lib.rs (1)

7-19: Verify the mutual exclusivity of feature flags.

The conditional compilation setup looks correct, but we should ensure that the feature combinations are mutually exclusive to prevent potential compilation issues.

Let's verify the feature combinations:

✅ Verification successful

Feature flags configuration is correct and mutually exclusive

The feature combinations in Cargo.toml and the conditional compilation flags in lib.rs are properly configured to ensure mutual exclusivity:

  • Server configuration takes precedence when both server and client features are enabled
  • Client configuration only activates when server is not enabled
  • WASM target has a separate path that's mutually exclusive with others
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential feature flag conflicts
echo "Analyzing Cargo.toml for feature combinations..."
rg -A 5 '^\[features\]' Cargo.toml || echo "No features section found in Cargo.toml"

# Check if any files exist in both client and wasm directories
echo "Checking for duplicate files across directories..."
for file in $(fd -t f . core/client); do
  base_name=$(basename "$file")
  if [ -f "core/wasm/$base_name" ]; then
    echo "Warning: $base_name exists in both client and wasm directories"
  fi
done

Length of output: 467


Script:

#!/bin/bash
# Check for potential feature flag conflicts in the correct location
echo "Analyzing Cargo.toml for feature combinations..."
cat packages/dapi-grpc/Cargo.toml

# Verify the directory structure
echo -e "\nChecking directory structure..."
ls -la packages/dapi-grpc/src/core/

Length of output: 2588

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

30-34: Review the TLS configuration security settings.

The TLS configuration uses both native and webpki roots, which might be redundant. Consider choosing one based on the target platform.

Let's analyze the TLS configuration:

packages/wasm-sdk/src/state_transitions/documents.rs (1)

28-35: ⚠️ Potential issue

Implement document field extraction and validation.

The TODO comment and hardcoded default values indicate incomplete implementation. This could lead to security vulnerabilities if document fields are not properly validated.

Please implement proper field extraction and validation. Here's a script to check for similar patterns in the codebase:

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

4-24: LGTM! Well-structured conditional compilation.

The conditional module exports and client implementations are cleanly separated based on target architecture, ensuring proper functionality for both WASM and non-WASM environments.

packages/rs-dpp/src/data_contract/data_contract_facade.rs (1)

59-66: Verify feature flag combinations.

The conditional compilation looks correct, but we should verify that all possible feature flag combinations work as expected, especially the interaction between "validation", "identity-serialization", and "client" features.

Run this script to check feature combinations:

Also applies to: 73-80

✅ Verification successful

Feature flag combinations are properly defined and safe to use

The conditional compilation for the "validation" feature is correctly implemented and works well with other features. The feature dependencies are properly defined in Cargo.toml, and the feature can be safely enabled or disabled without affecting other functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check Cargo.toml for feature definitions and their dependencies
rg -A 5 '\[features\]' 

Length of output: 3041


Script:

#!/bin/bash
# Get detailed view of rs-dpp's Cargo.toml
cat packages/rs-dpp/Cargo.toml

Length of output: 9012

packages/rs-dpp/src/identity/identity_facade.rs (1)

59-65: LGTM! Clean implementation of conditional validation.

The conditional compilation of the skip_validation parameter is well-implemented, ensuring proper feature flag handling for WebAssembly optimization.

packages/rs-dapi-client/src/executor.rs (1)

Line range hint 37-52: LGTM! Proper implementation of custom PartialEq.

The custom implementation correctly compares all relevant fields while maintaining the required derive attributes as per previous feedback.

packages/rs-dpp/src/util/json_schema.rs (2)

Line range hint 30-38: LGTM! The URI resolution logic is well-implemented.

The function correctly:

  • Validates URI format
  • Processes path components
  • Handles errors appropriately

29-29: Address the TODO comment about function size.

The TODO comment suggests potential performance concerns due to regex usage. Consider:

  1. Profiling the function to quantify the impact
  2. Investigating alternatives to regex for path processing

Let's verify the regex usage in the codebase:

packages/dapi-grpc/build.rs (3)

16-22: LGTM! The main function properly handles different implementation types.

The conditional compilation ensures appropriate code generation based on features and target architecture.


Line range hint 24-38: LGTM! The generate_code function is well-structured.

The function properly configures and generates code for both core and platform protobuf files.


223-258: LGTM! The ImplType enum and its implementation are well-designed.

The enum provides:

  • Clear separation between different build targets
  • Proper configuration for each target type
  • Consistent directory naming
packages/rs-dapi-client/src/dapi_client.rs (3)

81-83: LGTM! The CA certificate field is properly conditional.

The field is correctly guarded with #[cfg(not(target_arch = "wasm32"))] to ensure it's only available for non-wasm targets.


Line range hint 113-118: LGTM! The with_ca_certificate method is well-implemented.

The method:

  • Is properly conditional for non-wasm targets
  • Has clear documentation
  • Maintains immutable design pattern

318-319: LGTM! The sleeper implementation enhances retry behavior.

The BackonSleeper provides proper backoff functionality for retries.

packages/rs-sdk/src/sync.rs (2)

23-25: LGTM! The error handling is properly conditional.

The NotInTokioRuntime error is correctly guarded for non-wasm targets.


243-243: LGTM! The retry function properly implements backoff behavior.

The BackonSleeper integration provides proper retry timing control.

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

5-9: LGTM!

The new imports are correctly organized and necessary for implementing the new transport request functionality.


473-482: LGTM!

The implementation of the transport request for MasternodeListRequest follows the established pattern and correctly handles streaming responses with appropriate timeout settings.

packages/rs-platform-value/src/inner_value_at_path.rs (2)

6-37: Great improvement to the implementation!

The new implementation of is_array_path is more efficient and maintainable:

  • Replaces regex with simple string operations
  • Clear step-by-step logic with helpful comments
  • Proper handling of edge cases

423-493: Excellent test coverage!

The test suite is comprehensive and well-structured:

  • Covers valid, invalid, and edge cases
  • Clear test names that describe the test scenarios
  • Helps ensure the robustness of the new implementation
packages/rs-drive-proof-verifier/src/types.rs (1)

38-38: LGTM!

The addition of the encode_to_vec method is well-implemented:

  • Correctly feature-gated with mocks
  • Proper error handling for serialization
  • Follows the platform's serialization patterns

Also applies to: 243-252

packages/rs-dpp/src/data_contract/document_type/index/mod.rs (2)

61-86: Excellent optimization with LazyRegex!

The LazyRegex implementation is well-designed:

  • Uses OnceLock for efficient lazy initialization
  • Clean and intuitive interface
  • Thread-safe implementation

524-538: LGTM!

The integration of LazyRegex is clean and maintains the existing functionality while improving performance through lazy initialization.

🧰 Tools
🪛 GitHub Check: Rust packages (dpp) / Linting

[warning] 531-531: to_string applied to a type that implements Display in format! args
warning: to_string applied to a type that implements Display in format! args
--> packages/rs-dpp/src/data_contract/document_type/index/mod.rs:531:58
|
531 | ... e.to_string()
| ^^^^^^^^^^^^ help: remove this
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_in_format_args
= note: #[warn(clippy::to_string_in_format_args)] on by default

packages/rs-sdk/src/sdk.rs (1)

279-279: Consider removing or clarifying the TODO comment.

The comment indicates this method was made public for tests, but this might not be the best approach for test accessibility.

Consider:

  1. Using the #[cfg(test)] attribute instead
  2. Creating a dedicated test-only interface
  3. Documenting why this needs to be public if it's actually required for non-test use cases
.cargo/config-release.toml (1)

16-17: LGTM: Proper WASM configuration added.

The addition of WASM target configuration with the appropriate getrandom backend is correct and necessary for WebAssembly support.

.cargo/config.toml (1)

29-31: LGTM: Consistent WASM configuration.

The WASM target configuration matches the release configuration, maintaining consistency across build types.

packages/wasm-sdk/Cargo.toml (3)

24-32: Document transport configuration issues.

The commented-out tonic configuration suggests there might be transport-related issues. Consider documenting these issues and the planned resolution in a more detailed comment or issue.

Would you like me to help create an issue to track the transport configuration requirements and limitations?


21-22: Verify wasm-bindgen version compatibility.

The wasm-bindgen version is pinned to 0.2.99. This exact version pinning might cause compatibility issues with other dependencies.

✅ Verification successful

The wasm-bindgen version pinning is intentional and consistent

The exact version pinning to 0.2.99 is consistent across the codebase and appears to be a deliberate choice for stability, especially considering the custom serde-wasm-bindgen fork being used. No compatibility issues were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if other packages in the workspace use different wasm-bindgen versions
rg '"wasm-bindgen"' -A 1

Length of output: 860


Script:

#!/bin/bash
# Search for wasm-bindgen dependencies in all Cargo.toml files
fd Cargo.toml --type f --exec rg -A 3 'wasm-bindgen.*=.*' {}

Length of output: 1052


23-23: Remove or implement TODO comment.

The TODO comment suggests that drive-proof-verifier might not be needed. This should be verified and either removed or implemented.

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

8-8: Verify feature removal impact.

The removal of default features and commenting out of dpp features (document-value-conversion, extended-document) might affect functionality. Please ensure:

  1. These features aren't required for core functionality
  2. The changes don't break existing use cases

Also applies to: 29-32

✅ Verification successful

Features are safely removed without impact

The verification shows that the commented-out features (document-value-conversion and extended-document) are not used in the codebase and their removal doesn't affect functionality:

  • No conditional compilation using these features
  • Not included in default features
  • Not required by other dependencies
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for usage of commented-out features
rg "document_value_conversion|extended_document" packages/rs-drive-proof-verifier/src/

Length of output: 88


Script:

#!/bin/bash
# Check the complete Cargo.toml content
cat packages/rs-drive-proof-verifier/Cargo.toml

# Search for cfg feature attributes with various naming patterns
rg -i "cfg.*feature.*document.*value|cfg.*feature.*extended.*document" packages/rs-drive-proof-verifier/src/

# Search for any mentions of these features in dependency specifications
rg "document-value-conversion|extended-document" packages/rs-drive-proof-verifier/Cargo.toml

Length of output: 1738

packages/rs-dapi-client/Cargo.toml (1)

23-33: Well-structured target-specific dependencies!

Good separation of wasm32 and non-wasm32 dependencies. The use of target-specific sections helps maintain clean dependency management.

packages/dapi-grpc/Cargo.toml (2)

24-28: LGTM! Clear separation of client and server features.

The feature declarations are well-structured with clear dependencies. The client feature is appropriately simplified while the server feature includes all necessary components.


48-60: LGTM! Well-structured target-specific dependencies.

The separation of dependencies for wasm32 and non-wasm32 targets is clean and appropriate:

  • wasm32: Includes getrandom with js feature for WASM compatibility
  • non-wasm32: Includes full tonic features for native builds
packages/js-dapi-client/package.json (1)

85-86: LGTM! Necessary addition for WASM distribution.

Adding "dist" to the files array ensures that built WASM files are included in the package distribution.

packages/rs-drive-abci/Cargo.toml (1)

42-45: LGTM! Explicit feature selection for dapi-grpc.

The dependency is well-configured with:

  • Disabled default features to avoid pulling unnecessary dependencies
  • Explicit selection of required features
packages/rs-sdk/Cargo.toml (3)

9-21: LGTM! Dependencies correctly configured for WASM compatibility.

The dependencies are properly configured with default-features = false to prevent pulling in non-WASM compatible features.


26-27: LGTM! Proper target-specific configuration for tokio.

The tokio configuration is correctly split between WASM and non-WASM targets, ensuring proper async runtime support in both environments.

Also applies to: 46-47


117-118: LGTM! Required WASM compilation target types.

The crate-type = ["cdylib", "rlib"] configuration is correct for WASM compilation support.

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

58-59: LGTM! Dependencies correctly made optional.

Dependencies are properly marked as optional to reduce the default build size, which is particularly important for WASM builds.

Also applies to: 62-63


124-144: Verify the impact of commented-out features.

Several features have been commented out in the dash-sdk-features. While this might help reduce the WASM bundle size, we should verify that this doesn't break any required functionality.

packages/rs-dpp/src/data_contract/mod.rs (1)

26-31: LGTM! Well-structured feature gates for the conversion module.

The new conversion module is properly gated behind relevant feature flags, allowing for flexible format support while maintaining WASM compatibility.

packages/wasm-sdk/index.html Outdated Show resolved Hide resolved
packages/wasm-sdk/index.html Outdated Show resolved Hide resolved
packages/wasm-sdk/index.html Outdated Show resolved Hide resolved
packages/wasm-sdk/index.html Outdated Show resolved Hide resolved
packages/rs-dapi-client/src/transport/wasm_channel.rs Outdated Show resolved Hide resolved
packages/wasm-sdk/src/context_provider.rs Show resolved Hide resolved
packages/rs-sdk/src/sync.rs Show resolved Hide resolved
packages/rs-sdk/src/sdk.rs Outdated Show resolved Hide resolved
packages/rs-dapi-client/Cargo.toml Outdated Show resolved Hide resolved
Comment on lines +55 to +58
tenderdash-abci = { git = "https://github.com/dashpay/rs-tenderdash-abci", version = "1.2.1", rev = "a558c0a2deab149183f125a012b14b709150401c", features = [
"grpc",
] }

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

Dependency version and commit hash mismatch needs attention

The current configuration is problematic because:

  • The specified version 1.2.1 doesn't exist as a tag in the repository
  • The commit hash points to a very recent change (January 13, 2025)

Recommendations:

  • Either use a properly tagged version for stability
  • Or if you need this specific commit, remove the version field and rely solely on the commit hash
  • Consider waiting for an official release instead of using an untagged commit
🔗 Analysis chain

Verify the commit hash stability.

Using a specific commit hash instead of a tag could make the build less stable across different environments.

Run this script to verify the commit's stability:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the commit exists and is part of a release
gh api repos/dashpay/rs-tenderdash-abci/commits/a558c0a2deab149183f125a012b14b709150401c \
  --jq '.parents[].sha' || echo "Commit not found"

# Check if commit is part of any tag
gh api repos/dashpay/rs-tenderdash-abci/tags --jq '.[] | select(.commit.sha == "a558c0a2deab149183f125a012b14b709150401c") | .name'

Length of output: 287


Script:

#!/bin/bash
# Check if v1.2.1 tag exists and get its commit hash
gh api repos/dashpay/rs-tenderdash-abci/git/refs/tags/v1.2.1 --jq '.object.sha' || echo "Tag v1.2.1 not found"

# Get the commit date to understand timeline
gh api repos/dashpay/rs-tenderdash-abci/commits/a558c0a2deab149183f125a012b14b709150401c --jq '.commit.committer.date'

Length of output: 337

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

♻️ Duplicate comments (1)
packages/wasm-sdk/src/verify.rs (1)

71-126: ⚠️ Potential issue

Replace placeholder values with actual verification data.

Similar to verify_identity_response, this function uses empty vectors which won't provide actual verification.

🧹 Nitpick comments (7)
packages/wasm-sdk/src/dpp.rs (4)

225-227: Consider returning a Uint8Array instead of Vec<u8>

In the hash method, returning a Uint8Array would be more compatible with JavaScript environments and WebAssembly, providing better interoperability.

Apply this diff to modify the return type:

-    pub fn hash(&self) -> Result<Vec<u8>, JsError> {
+    pub fn hash(&self) -> Result<js_sys::Uint8Array, JsError> {
         self.inner.hash().map_err(to_js_error)
+            .map(|hash| js_sys::Uint8Array::from(hash.as_slice()))
     }

262-266: Validate the buffer before deserialization

In the from_buffer method, it's good practice to validate the input buffer to ensure it's not empty or malformed before attempting deserialization. This can prevent potential panics or undesired behavior.

Apply this diff to add buffer validation:

     pub fn from_buffer(buffer: Vec<u8>) -> Result<IdentityWasm, JsError> {
+        if buffer.is_empty() {
+            return Err(JsError::from("Buffer is empty"));
+        }
         let identity: Identity = PlatformDeserializable::deserialize_from_bytes(buffer.as_slice())
             .map_err(to_js_error)?;
         Ok(identity.into())

41-47: Handle invalid platform versions gracefully

In the new constructor, when retrieving the platform version using PlatformVersion::get(platform_version), consider providing a user-friendly error message or defaulting to a supported version if an invalid version is supplied.

Apply this diff to enhance error handling:

     pub fn new(platform_version: u32) -> Result<IdentityWasm, JsError> {
-        let platform_version = &PlatformVersion::get(platform_version).map_err(to_js_error)?;
+        let platform_version = PlatformVersion::get(platform_version)
+            .map_err(|_| JsError::from("Invalid platform version supplied"))?;

         Identity::default_versioned(&platform_version)
             .map(Into::into)
             .map_err(to_js_error)
     }

296-299: Expose additional DataContract methods for completeness

Currently, the DataContractWasm struct provides the id and to_json methods. Consider exposing additional methods such as get_document_type or get_schema to provide more functionality to the Wasm SDK users.

packages/rs-dapi-client/src/transport/wasm_channel.rs (2)

77-82: Enhance error handling in wasm_client_error_to_status

The wasm_client_error_to_status function currently handles TonicStatusError and maps all other errors to Status::internal. To provide more detailed error information, consider handling additional specific variants of tonic_web_wasm_client::Error.

Would you like assistance in expanding the error handling to cover more error cases?


90-91: Consider relocating WasmBackonSleeper to a dedicated module

There's a TODO comment suggesting moving WasmBackonSleeper to a different module. Organizing code by placing it in an appropriate module can improve maintainability and readability.

Would you like help in refactoring to move WasmBackonSleeper to a suitable module?

packages/rs-dapi-client/tests/local_platform_connectivity.rs (1)

Line range hint 9-13: Consider documenting the test identity bytes.

The OWNER_ID_BYTES constant contains hardcoded test data. Adding a doc comment explaining what this identity represents and why these specific bytes were chosen would improve maintainability.

+    /// Test identity bytes representing [add context here]
+    /// Source: [explain where these bytes came from]
     pub const OWNER_ID_BYTES: [u8; 32] = [
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2336773 and e7213a7.

📒 Files selected for processing (12)
  • Cargo.toml (1 hunks)
  • packages/rs-dapi-client/Cargo.toml (2 hunks)
  • packages/rs-dapi-client/src/transport/wasm_channel.rs (1 hunks)
  • packages/rs-dapi-client/tests/local_platform_connectivity.rs (1 hunks)
  • packages/rs-sdk/Cargo.toml (5 hunks)
  • packages/rs-sdk/src/sdk.rs (10 hunks)
  • packages/wasm-sdk/index.html (1 hunks)
  • packages/wasm-sdk/src/dpp.rs (1 hunks)
  • packages/wasm-sdk/src/lib.rs (1 hunks)
  • packages/wasm-sdk/src/sdk.rs (1 hunks)
  • packages/wasm-sdk/src/state_transitions/documents.rs (1 hunks)
  • packages/wasm-sdk/src/verify.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • Cargo.toml
  • packages/wasm-sdk/index.html
  • packages/rs-sdk/src/sdk.rs
  • packages/rs-sdk/Cargo.toml
🧰 Additional context used
📓 Learnings (1)
packages/wasm-sdk/src/lib.rs (1)
Learnt from: lklimek
PR: dashpay/platform#2405
File: packages/wasm-sdk/src/lib.rs:13-17
Timestamp: 2025-01-23T09:43:25.080Z
Learning: The codebase uses tracing_wasm for WebAssembly tracing as it provides sufficient functionality for the project's needs.
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: Rust packages (drive-abci) / Unused dependencies
  • GitHub Check: Rust packages (drive-abci) / Tests
  • GitHub Check: Rust packages (drive-abci) / Formatting
  • GitHub Check: Rust packages (drive-abci) / Linting
  • GitHub Check: Rust packages (drive-abci) / Check each feature
  • GitHub Check: Rust packages (drive) / Unused dependencies
  • GitHub Check: Rust packages (drive) / Tests
  • GitHub Check: Rust packages (drive) / Linting
  • GitHub Check: Rust packages (dpp) / Tests
  • GitHub Check: Rust packages (dpp) / Linting
  • GitHub Check: Rust packages (dpp) / Check each feature
  • GitHub Check: Rust packages (dash-sdk) / Tests
  • GitHub Check: Rust packages (dash-sdk) / Linting
  • GitHub Check: Rust packages (dash-sdk) / Check each feature
  • GitHub Check: Rust packages (dapi-grpc) / Unused dependencies
  • GitHub Check: Rust packages (dapi-grpc) / Linting
  • GitHub Check: Build Docker images (Drive, drive, drive-abci) / Build Drive image
  • GitHub Check: Build Docker images (Dashmate helper, dashmate-helper, dashmate-helper) / Build Dashmate helper image
  • GitHub Check: Build Docker images (DAPI, dapi, dapi) / Build DAPI image
  • GitHub Check: Build JS packages / Build JS
🔇 Additional comments (18)
packages/rs-dapi-client/Cargo.toml (6)

8-8: Great improvement on default features!

Moving to empty default features is a good practice that aligns with Rust conventions and reduces unnecessary dependencies in production builds.


23-28: Well-structured target-specific dependency split!

Good practice to separate non-wasm dependencies. The backon configuration with tokio-sleep is appropriate for native targets.


46-50: Well-coordinated dependency updates for WASM support.

Good addition of the getrandom feature to rand while disabling default features. This aligns well with the WASM target requirements.


43-43: Verify the http dependency version.

Let's check if version 1.1.0 is the latest stable version and if there are any known security issues.

✅ Verification successful

The http dependency version 1.1.0 is secure and properly configured.

The version is recent and well above any known vulnerable versions. While version 1.2.0 is available, the current version is secure and stable.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for latest version and security advisories for http
echo "Latest version on crates.io:"
curl -s https://crates.io/api/v1/crates/http | jq '.crate.max_stable_version'

echo -e "\nChecking for security advisories..."
gh api graphql -f query='{
  securityVulnerabilities(first: 5, ecosystem: RUST, package: "http") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 1230


29-33: Verify security advisories for WASM dependencies.

Let's check for any security advisories on the new WASM dependencies.

✅ Verification successful

No security advisories found for WASM dependencies

All WASM dependencies (gloo-timers, tonic-web-wasm-client, wasm-bindgen-futures, and getrandom) are clear of known security vulnerabilities in the GitHub Security Advisory Database.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for security advisories for the new WASM dependencies
for pkg in "gloo-timers" "tonic-web-wasm-client" "wasm-bindgen-futures" "getrandom"; do
  echo "Checking $pkg..."
  gh api graphql -f query='{
    securityVulnerabilities(first: 5, ecosystem: RUST, package: "'$pkg'") {
      nodes {
        advisory {
          summary
          severity
          publishedAt
        }
        vulnerableVersionRange
        firstPatchedVersion {
          identifier
        }
      }
    }
  }'
done

Length of output: 2111


21-21: Verify the impact of renaming 'offline-testing' to 'online-testing'.

This appears to be a significant semantic change that could affect existing code. Let's verify all usages to ensure nothing breaks.

packages/wasm-sdk/src/dpp.rs (1)

102-103: Handle potential precision loss when converting between u64 and f64

Converting between u64 and f64 can lead to precision loss for large integer values. Since JavaScript numbers are floating-point, they cannot accurately represent integers beyond 2^53 - 1. Consider using string representations or JavaScript BigInt to handle large integer values safely.

Also applies to: 107-108, 112-113, 117-118, 122-123, 127-128, 132-133

packages/wasm-sdk/src/lib.rs (3)

3-8: LGTM!

The module organization is clean and follows a logical structure.


10-11: LGTM!

Using wee_alloc is a good choice for WebAssembly as it's a size-optimized allocator.


13-24: LGTM!

The start function correctly sets up error handling with console_error_panic_hook and tracing with tracing_wasm. Based on the learnings, tracing_wasm provides sufficient functionality for the project's needs.

packages/wasm-sdk/src/state_transitions/documents.rs (1)

42-75: LGTM!

The implementation includes:

  • Comprehensive boundary checks for signature_public_key_id
  • Proper error handling and conversion
  • Correct serialization to bytes
packages/wasm-sdk/src/sdk.rs (4)

26-83: LGTM!

The implementations are well-structured with:

  • Proper wrapping of SDK functionality
  • Correct implementation of Deref traits
  • Consistent builder methods

85-112: LGTM!

The functions include:

  • Proper base58 identifier handling
  • Comprehensive error handling with descriptive messages

114-145: ⚠️ Potential issue

Replace zero-initialized values with secure implementations.

While this is marked as a mock implementation, using zero-initialized values for identifiers and private keys is unsafe and should not be used as an example.

Apply this diff to improve security:

-let id = Identifier::from_bytes(&[0; 32]).expect("create identifier");
+let id = Identifier::random();

-let asset_lock_proof_private_key =
-    PrivateKey::from_slice(&[0; 32], Network::Testnet).expect("create private key");
+// TODO: Implement secure private key handling
+let asset_lock_proof_private_key = /* secure key generation */;

Likely invalid or redundant comment.


195-208: ⚠️ Potential issue

Implement mock signing for testing purposes.

While the comment explains why actual signing is not implemented, the todo!() macro will panic if called. For testing purposes, implement a mock that returns empty bytes.

Apply this diff to provide a mock implementation:

-        todo!("signature creation is not implemented due to lack of dash platform wallet support in wasm")
+        // Mock implementation for testing
+        Ok(dash_sdk::dpp::platform_value::BinaryData::new(vec![0; 32]))

Likely invalid or redundant comment.

packages/wasm-sdk/src/verify.rs (1)

182-189: LGTM!

The DocumentWasm implementation correctly wraps Document and provides proper base58 string conversion for IDs.

packages/rs-dapi-client/tests/local_platform_connectivity.rs (2)

1-2: LGTM! The feature flag change improves clarity.

The change from #[cfg(not(feature = "offline-testing"))] to #[cfg(feature = "online-testing")] makes the test configuration more explicit and easier to understand. This aligns well with the feature restructuring needed for WASM compatibility.


Line range hint 14-53: Verify local server dependency in CI environment.

The test requires a local DAPI server running on port 2443. Ensure that the CI pipeline is configured to handle this dependency appropriately when the "online-testing" feature is enabled.

✅ Verification successful

Local DAPI server dependency is properly handled in CI

The test is correctly configured with the online-testing feature flag, and the CI environment properly handles the DAPI server dependency through the local network setup action which builds and deploys DAPI as part of the test infrastructure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if CI configuration handles local DAPI server setup

# Look for CI configuration files
echo "Checking CI configuration files..."
fd -t f '\.ya?ml$' .github/workflows/

# Look for Docker compose or similar setup files
echo "Checking for Docker setup files..."
fd -t f 'docker-compose.*\.ya?ml$' .

# Look for documentation about test setup
echo "Checking for test setup documentation..."
fd -t f 'README\.md$'

Length of output: 2526


Script:

#!/bin/bash
# Check CI configuration for Rust package tests
echo "Content of tests-rs-package.yml:"
cat .github/workflows/tests-rs-package.yml

echo -e "\nChecking rs-dapi-client documentation:"
cat packages/rs-dapi-client/README.md 2>/dev/null || echo "README not found"

echo -e "\nChecking for online-testing feature usage:"
rg "online-testing|test.*feature" packages/rs-dapi-client/ -g '!target'

echo -e "\nChecking for test setup in Cargo.toml:"
cat packages/rs-dapi-client/Cargo.toml

Length of output: 11620


Script:

#!/bin/bash
# Check main test workflow and search for DAPI setup
echo "Content of main tests workflow:"
cat .github/workflows/tests.yml

echo -e "\nSearching for DAPI setup in workflows:"
rg "dapi.*setup|setup.*dapi|start.*dapi" .github/workflows/

Length of output: 7089


Script:

#!/bin/bash
# Check functional test workflow and dashmate setup
echo "Content of functional test workflow:"
cat .github/workflows/tests-packges-functional.yml

echo -e "\nChecking dashmate docker compose for DAPI setup:"
cat packages/dashmate/docker-compose.build.dapi_api.yml

Length of output: 2379

Comment on lines +59 to +78
#[wasm_bindgen(js_name=setPublicKeys)]
pub fn set_public_keys(&mut self, public_keys: js_sys::Array) -> Result<usize, JsValue> {
if public_keys.length() == 0 {
return Err(format!("Setting public keys failed. The input ('{}') is invalid. You must use array of PublicKeys", public_keys.to_string()).into());
}

// let public_keys = public_keys
// .iter()
// .map(|key| {
// key.to_wasm::<IdentityPublicKeyWasm>("IdentityPublicKey")
// .map(|key| {
// let key = IdentityPublicKey::from(key.to_owned());
// (key.id(), key)
// })
// })
// .collect::<Result<_, _>>()?;
//
// self.inner.set_public_keys(public_keys);

Ok(self.inner.public_keys().len())
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

Method set_public_keys does not set public keys

The set_public_keys method currently does not set any public keys because the implementation code is commented out. As a result, calling this method will not modify the identity's public keys as intended.

Apply this diff to restore the implementation:

+        let public_keys = public_keys
+            .iter()
+            .map(|key| {
+                key.to_wasm::<IdentityPublicKeyWasm>("IdentityPublicKey")
+                    .map(|key| {
+                        let key = IdentityPublicKey::from(key.to_owned());
+                        (key.id(), key)
+                    })
+            })
+            .collect::<Result<_, _>>()?;
+
+        self.inner.set_public_keys(public_keys);
📝 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
#[wasm_bindgen(js_name=setPublicKeys)]
pub fn set_public_keys(&mut self, public_keys: js_sys::Array) -> Result<usize, JsValue> {
if public_keys.length() == 0 {
return Err(format!("Setting public keys failed. The input ('{}') is invalid. You must use array of PublicKeys", public_keys.to_string()).into());
}
// let public_keys = public_keys
// .iter()
// .map(|key| {
// key.to_wasm::<IdentityPublicKeyWasm>("IdentityPublicKey")
// .map(|key| {
// let key = IdentityPublicKey::from(key.to_owned());
// (key.id(), key)
// })
// })
// .collect::<Result<_, _>>()?;
//
// self.inner.set_public_keys(public_keys);
Ok(self.inner.public_keys().len())
#[wasm_bindgen(js_name=setPublicKeys)]
pub fn set_public_keys(&mut self, public_keys: js_sys::Array) -> Result<usize, JsValue> {
if public_keys.length() == 0 {
return Err(format!("Setting public keys failed. The input ('{}') is invalid. You must use array of PublicKeys", public_keys.to_string()).into());
}
let public_keys = public_keys
.iter()
.map(|key| {
key.to_wasm::<IdentityPublicKeyWasm>("IdentityPublicKey")
.map(|key| {
let key = IdentityPublicKey::from(key.to_owned());
(key.id(), key)
})
})
.collect::<Result<_, _>>()?;
self.inner.set_public_keys(public_keys);
Ok(self.inner.public_keys().len())

Comment on lines +26 to +68
pub async fn verify_identity_response() -> Option<IdentityWasm> {
let request = dash_sdk::dapi_grpc::platform::v0::GetIdentityRequest {
version: Some(GetIdentityRequestVersion::V0(GetIdentityRequestV0 {
id: vec![],
prove: true,
})),
};

let response = dash_sdk::dapi_grpc::platform::v0::GetIdentityResponse {
version: Some(Version::V0(GetIdentityResponseV0 {
result: Some(get_identity_response_v0::Result::Proof(Proof {
grovedb_proof: vec![],
quorum_hash: vec![],
signature: vec![],
round: 0,
block_id_hash: vec![],
quorum_type: 0,
})),
metadata: Some(ResponseMetadata {
height: 0,
core_chain_locked_height: 0,
epoch: 0,
time_ms: 0,
protocol_version: 0,
chain_id: "".to_string(),
}),
})),
};

let context = WasmContext {};

let (response, _metadata, _proof) =
<Identity as FromProof<GetIdentityRequest>>::maybe_from_proof_with_metadata(
request,
response,
Network::Dash,
PlatformVersion::latest(),
&context,
)
.expect("parse proof");

response.map(IdentityWasm::from)
}
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

Replace placeholder values with actual verification data.

The function uses empty vectors for proofs and hashes, which won't provide actual verification.

Would you like me to help implement proper verification with actual proof data?

packages/wasm-sdk/src/verify.rs Show resolved Hide resolved
/// Indicate if the sdk should request and verify proofs.
pub fn prove(&self) -> bool {
self.proofs
}

// TODO: If we remove this setter we don't need to use ArcSwap.
// It's good enough to set Context once when you initialize the SDK.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@shumkov this is not so simple - to retrieve data contracts, ContextProvider requires Sdk. It creates circular dependency, where ContextProvider needs Sdk to initialize, and Sdk needs ContextProvider.

See

context_provider.set_sdk(Some(sdk.clone()));
sdk.set_context_provider(context_provider);
how it's done. Not sure if this is optimal solution, but it works.

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