Skip to content

Conversation

@PastaPastaPasta
Copy link
Member

@PastaPastaPasta PastaPastaPasta commented Jul 9, 2025

…ter error handling

  • Implement standard FromStr trait for Address parsing
  • Keep explicit to_string() method for backward compatibility
  • Add from_string() convenience method
  • Improve error handling by using explicit Error::Bip32 wrapping instead of generic Into
  • Fix AccountDerivation to derive private keys first, then convert to public
  • Update tests to import FromStr trait where needed

These changes make the key-wallet API more idiomatic while maintaining compatibility.

Summary by CodeRabbit

  • Refactor

    • Improved address parsing to use more idiomatic Rust patterns and streamlined script generation for addresses.
    • Standardized error handling for key derivation processes.
    • Simplified and clarified test code by removing unused variables and imports.
  • Bug Fixes

    • Enhanced reliability of address and key derivation by restructuring error mapping and parsing logic.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

The changes refactor address parsing and script generation in the Address struct, moving parsing logic into a FromStr trait implementation and introducing a standalone script_pubkey method. Error handling in key derivation is standardized to use Error::Bip32. Minor cleanups and import adjustments are made in example and test files.

Changes

File(s) Change Summary
key-wallet/src/address.rs Refactored Address parsing into FromStr trait; added script_pubkey method; renamed from_str to from_string.
key-wallet/src/derivation.rs Standardized error handling to use Error::Bip32; changed derivation to use priv→pub extraction.
key-wallet/examples/basic_usage.rs Switched to idiomatic parse::(); removed unused bip44_account variable.
key-wallet/tests/address_tests.rs Imported FromStr; removed unused bip44_account variable in test.
key-wallet/tests/mnemonic_tests.rs Removed unused ExtendedPrivKey import.

Poem

In the warren of code, we hop and we parse,
With FromStr for addresses—oh, how smart and sparse!
Script pubkeys now hop out with glee,
Errors unified, as neat as can be.
🐇 Rusty paws tap—refactor complete!
The blockchain garden smells extra sweet.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)

warning: profiles for the non root package will be ignored, specify profiles at the workspace root:
package: /dash-spv-ffi/Cargo.toml
workspace: /Cargo.toml
Updating git repository https://github.com/dashpay/agora-blsful
error: failed to load source for dependency blsful

Caused by:
Unable to update https://github.com/dashpay/agora-blsful?rev=5f017aa1a0452ebc73e47f219f50c906522df4ea

Caused by:
failed to create directory /usr/local/git/db/agora-blsful-002ebda36d727958

Caused by:
Permission denied (os error 13)


📜 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 b0be986 and bc14806.

📒 Files selected for processing (5)
  • key-wallet/examples/basic_usage.rs (1 hunks)
  • key-wallet/src/address.rs (2 hunks)
  • key-wallet/src/derivation.rs (3 hunks)
  • key-wallet/tests/address_tests.rs (1 hunks)
  • key-wallet/tests/mnemonic_tests.rs (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
key-wallet/tests/mnemonic_tests.rs (2)
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet/src/address.rs:30-40
Timestamp: 2025-06-15T15:31:44.136Z
Learning: In the key-wallet crate, QuantumExplorer prefers keeping wildcard arms that default unknown Network variants to testnet prefixes rather than using exhaustive matches or panics. This fallback behavior is intentional.
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
key-wallet/tests/address_tests.rs (2)
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet/src/address.rs:30-40
Timestamp: 2025-06-15T15:31:44.136Z
Learning: In the key-wallet crate, QuantumExplorer prefers keeping wildcard arms that default unknown Network variants to testnet prefixes rather than using exhaustive matches or panics. This fallback behavior is intentional.
key-wallet/examples/basic_usage.rs (1)
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
key-wallet/src/derivation.rs (2)
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet/src/address.rs:30-40
Timestamp: 2025-06-15T15:31:44.136Z
Learning: In the key-wallet crate, QuantumExplorer prefers keeping wildcard arms that default unknown Network variants to testnet prefixes rather than using exhaustive matches or panics. This fallback behavior is intentional.
key-wallet/src/address.rs (3)
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#74
File: key-wallet-ffi/src/lib_tests.rs:41-48
Timestamp: 2025-06-15T16:42:18.187Z
Learning: In key-wallet-ffi, the HDWallet::derive_xpriv method returns Result<String, KeyWalletError>, not an ExtPrivKey wrapper. When unwrapped, it yields a String that can have .is_empty() called on it.
Learnt from: QuantumExplorer
PR: dashpay/rust-dashcore#51
File: dash/src/sml/masternode_list_entry/hash.rs:7-12
Timestamp: 2025-02-25T06:19:32.230Z
Learning: The `consensus_encode` method on `MasternodeListEntry` writing to a `Vec` buffer cannot fail, so using `.expect()` is appropriate rather than propagating the error with the `?` operator.
Learnt from: DCG-Claude
PR: dashpay/rust-dashcore#0
File: :0-0
Timestamp: 2025-06-26T15:48:36.342Z
Learning: In Rust FFI code, unwrap() must not be used on CString::new, especially for error messages or untrusted input, as it can panic if the string contains null bytes. Instead, use unwrap_or_else with a fallback to a known-safe, hardcoded string to prevent panics across FFI boundaries.
🔇 Additional comments (11)
key-wallet/tests/mnemonic_tests.rs (1)

4-4: LGTM: Clean import removal.

The ExtendedPrivKey import is correctly removed since it's not used anywhere in the test file. Only the Network enum is actually needed for the test cases.

key-wallet/tests/address_tests.rs (1)

3-3: LGTM: Necessary import for FromStr trait.

The import is required to support the new FromStr trait implementation for Address used in the test on line 66.

key-wallet/examples/basic_usage.rs (1)

70-70: LGTM: Idiomatic Rust parsing pattern.

Using .parse::<Address>() is more idiomatic than calling Address::from_str() directly. This demonstrates the improved API with the new FromStr trait implementation.

key-wallet/src/derivation.rs (4)

31-31: LGTM: Improved error handling with explicit Error::Bip32.

Using explicit Error::Bip32 instead of generic Into::into provides clearer error semantics as mentioned in the PR objectives.


77-77: LGTM: Consistent error handling pattern.

The explicit Error::Bip32 mapping maintains consistency with the error handling pattern established in the trait implementation.


161-163: LGTM: Corrected AccountDerivation logic.

The change from direct derive_pub to derive_priv followed by public key conversion aligns with the PR objective of correcting the AccountDerivation logic to derive private keys before converting to public keys.


171-173: LGTM: Consistent derivation pattern.

The change maintains consistency with the corrected derivation logic in the receive_address method.

key-wallet/src/address.rs (4)

6-6: LGTM: Necessary import for FromStr trait implementation.

The import is required for the new FromStr trait implementation.


101-103: LGTM: Backward compatibility maintained.

The from_string method preserves backward compatibility while leveraging the new idiomatic FromStr trait implementation, as mentioned in the PR objectives.


105-128: LGTM: Well-structured script generation.

The script_pubkey method correctly generates Bitcoin-standard scripts for both P2PKH and P2SH addresses with proper opcodes and structure.


130-168: LGTM: Idiomatic FromStr trait implementation.

The FromStr implementation follows Rust best practices and correctly handles:

  • Base58 decoding with validation
  • Address length validation (21 bytes)
  • Hash extraction from the payload
  • Network and address type inference from version bytes
  • Proper error handling with descriptive messages

This aligns with the PR objective of implementing the standard FromStr trait for more idiomatic Rust API.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@DCG-Claude DCG-Claude force-pushed the feat/key-wallet-api-improvements branch 3 times, most recently from a892419 to 908213e Compare July 9, 2025 22:06
…ter error handling

- Implement standard FromStr trait for Address parsing
- Keep explicit to_string() method for backward compatibility
- Add from_string() convenience method
- Improve error handling by using explicit Error::Bip32 wrapping instead of generic Into
- Fix AccountDerivation to derive private keys first, then convert to public
- Update tests to import FromStr trait where needed

These changes make the key-wallet API more idiomatic while maintaining compatibility.
@DCG-Claude DCG-Claude force-pushed the feat/key-wallet-api-improvements branch from 908213e to bc14806 Compare July 9, 2025 22:10
@PastaPastaPasta
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@PastaPastaPasta PastaPastaPasta merged commit 44e12a9 into dashpay:v0.40-dev Jul 9, 2025
17 checks passed
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.

1 participant