Skip to content

refactor(key-wallet): ManagedAccountType::from_account_type refactor#828

Open
ZocoLini wants to merge 3 commits into
devfrom
refactor/account-type
Open

refactor(key-wallet): ManagedAccountType::from_account_type refactor#828
ZocoLini wants to merge 3 commits into
devfrom
refactor/account-type

Conversation

@ZocoLini

@ZocoLini ZocoLini commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator

While benchmarking and implementing the CoinJoin internal pool tracking I found this duplicated code, I consolidated the ManagedAccountType centralizing the logic

Summary by CodeRabbit

  • Bug Fixes
    • Improved account setup for multiple wallet account types, making account creation more consistent.
    • Fixed address pool generation for platform payment and related account flows, reducing the chance of setup failures.
    • Improved error handling during address derivation so wallet creation now returns errors more safely instead of failing unexpectedly.

@ZocoLini ZocoLini requested a review from xdustinface June 29, 2026 10:49
@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@ZocoLini, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 49 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 36fa3a48-e7f8-4206-8c39-7a058faa0400

📥 Commits

Reviewing files that changed from the base of the PR and between 6d315ca and 7383c08.

📒 Files selected for processing (1)
  • key-wallet/src/managed_account/managed_account_type.rs
📝 Walkthrough

Walkthrough

Two new pub(crate) helpers, single_pool and dual_pools, are added to ManagedAccountType to centralize derivation-path resolution and AddressPool construction with proper error propagation. The from_account_type match arms and five account-construction methods in ManagedAccountCollection are updated to call these helpers, and the now-redundant local build_managed_account_type helper is deleted.

Changes

AddressPool Construction Refactor

Layer / File(s) Summary
single_pool and dual_pools helpers
key-wallet/src/managed_account/managed_account_type.rs
Adds single_pool (single AddressPool from a derived base path) and dual_pools (external/internal AddressPool pair via child indices 0/1), both propagating derivation errors with ? instead of unwrap().
from_account_type rewritten
key-wallet/src/managed_account/managed_account_type.rs
Standard arm switches to dual_pools; CoinJoin, identity, provider key, DashPay, and PlatformPayment arms switch to dual_pools or single_pool with appropriate AddressPoolType and gap-limit constants.
ManagedAccountCollection call-sites updated
key-wallet/src/managed_account/managed_account_collection.rs
create_managed_funds/keys/platform_account_from_account variants replace Self::build_managed_account_type / manual AddressPool::new with ManagedAccountType::from_account_type or ManagedAccountType::single_pool; build_managed_account_type is deleted; imports adjusted.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • dashpay/rust-dashcore#821: Touches the same ManagedAccountType CoinJoin dual-pool construction and from_account_type logic that this PR refactors via the new dual_pools helper.

Suggested reviewers

  • xdustinface
  • llbartekll

🐇 Two pools or one, the path is clear,
No more unwrap() to fill us with fear.
single_pool, dual_pools — helpers so neat,
Two hundred lines gone, the refactor complete!
Hop hop hooray, the wallet is clean! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactor centered on ManagedAccountType::from_account_type in key-wallet.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/account-type

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
key-wallet/src/managed_account/managed_account_collection.rs (1)

551-558: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the platform key matches the derivation account type.

This derives the address pool from account.account_type, but the returned ManagedPlatformAccount is labeled with key.account / key.key_class. If those diverge, the account watches the wrong DIP-17 path under the wrong identity.

Proposed fix
         // Use the account's existing public key
         let key_source = KeySource::Public(account.account_xpub);
 
+        let expected_account_type = crate::account::AccountType::PlatformPayment {
+            account: key.account,
+            key_class: key.key_class,
+        };
+        if account.account_type != expected_account_type {
+            return Err(crate::error::Error::InvalidParameter(
+                "Platform payment account key does not match account_type".into(),
+            ));
+        }
+
         // DIP-17 Platform Payment addresses: single pool on the account's path.
         let addresses = ManagedAccountType::single_pool(
-            account.account_type,
+            expected_account_type,
             AddressPoolType::Absent,
             DIP17_GAP_LIMIT,
             account.network,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@key-wallet/src/managed_account/managed_account_collection.rs` around lines
551 - 558, Validate that the platform key identity matches the derivation
account type before building the DIP-17 pool. In `ManagedAccountCollection`
where `ManagedAccountType::single_pool` is called, make sure the
`account.account_type` used for derivation cannot diverge from the
`ManagedPlatformAccount` identity implied by `key.account` and `key.key_class`;
if they differ, either reject the entry or derive from the key’s account type
instead. Update the account/pool construction so the watched path and returned
platform account label stay aligned.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@key-wallet/src/managed_account/managed_account_type.rs`:
- Around line 500-502: The fallback to DerivationPath::master() in the managed
account address-pool helpers hides derivation-path failures and can produce
addresses for the wrong account/network. Update the logic around
account_type.derivation_path(network) in managed_account_type so it returns or
propagates the error instead of using unwrap_or_else to default to m. Adjust the
affected helper(s) to return Result and use proper error propagation with the
existing error type pattern so callers can handle derivation-path failures
explicitly.

---

Outside diff comments:
In `@key-wallet/src/managed_account/managed_account_collection.rs`:
- Around line 551-558: Validate that the platform key identity matches the
derivation account type before building the DIP-17 pool. In
`ManagedAccountCollection` where `ManagedAccountType::single_pool` is called,
make sure the `account.account_type` used for derivation cannot diverge from the
`ManagedPlatformAccount` identity implied by `key.account` and `key.key_class`;
if they differ, either reject the entry or derive from the key’s account type
instead. Update the account/pool construction so the watched path and returned
platform account label stay aligned.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f5e4013e-802d-4662-9ddd-c8647d6c70b3

📥 Commits

Reviewing files that changed from the base of the PR and between 03096dd and 6d315ca.

📒 Files selected for processing (2)
  • key-wallet/src/managed_account/managed_account_collection.rs
  • key-wallet/src/managed_account/managed_account_type.rs

Comment on lines +500 to +502
let path = account_type
.derivation_path(network)
.unwrap_or_else(|_| crate::bip32::DerivationPath::master());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not silently fall back to the master path.

If derivation_path(network) fails, these helpers still generate address pools from m, which can make callers watch or persist addresses for the wrong account/network path. Propagate or map the derivation-path error instead of replacing it with DerivationPath::master(). As per coding guidelines, “Use proper error types (thiserror) and propagate errors appropriately” and “Return Result<T> for all fallible operations and use the ? operator for error propagation in Rust code.”

Proposed fix
-        let path = account_type
-            .derivation_path(network)
-            .unwrap_or_else(|_| crate::bip32::DerivationPath::master());
+        let path = account_type.derivation_path(network)?;

         crate::managed_account::address_pool::AddressPool::new(
             path, pool_type, gap_limit, network, key_source,
         )
@@
-        let base_path = account_type
-            .derivation_path(network)
-            .unwrap_or_else(|_| crate::bip32::DerivationPath::master());
+        let base_path = account_type.derivation_path(network)?;

Also applies to: 525-527

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@key-wallet/src/managed_account/managed_account_type.rs` around lines 500 -
502, The fallback to DerivationPath::master() in the managed account
address-pool helpers hides derivation-path failures and can produce addresses
for the wrong account/network. Update the logic around
account_type.derivation_path(network) in managed_account_type so it returns or
propagates the error instead of using unwrap_or_else to default to m. Adjust the
affected helper(s) to return Result and use proper error propagation with the
existing error type pattern so callers can handle derivation-path failures
explicitly.

Source: Coding guidelines

@ZocoLini ZocoLini force-pushed the refactor/account-type branch from c6a27a2 to 7383c08 Compare June 29, 2026 10:59
@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.84848% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.32%. Comparing base (ddb59d9) to head (7383c08).
⚠️ Report is 1 commits behind head on dev.

Files with missing lines Patch % Lines
...wallet/src/managed_account/managed_account_type.rs 85.71% 11 Missing ⚠️
.../src/managed_account/managed_account_collection.rs 81.81% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #828      +/-   ##
==========================================
+ Coverage   73.18%   73.32%   +0.13%     
==========================================
  Files         323      323              
  Lines       72295    72234      -61     
==========================================
+ Hits        52911    52967      +56     
+ Misses      19384    19267     -117     
Flag Coverage Δ
core 76.94% <ø> (ø)
ffi 47.71% <ø> (-0.02%) ⬇️
rpc 20.00% <ø> (ø)
spv 90.37% <ø> (+0.02%) ⬆️
wallet 72.31% <84.84%> (+0.49%) ⬆️
Files with missing lines Coverage Δ
.../src/managed_account/managed_account_collection.rs 55.98% <81.81%> (-2.85%) ⬇️
...wallet/src/managed_account/managed_account_type.rs 67.03% <85.71%> (+25.74%) ⬆️

... and 12 files with indirect coverage changes

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