Skip to content

refactor(key-wallet)!: validate child indexes at construction with ChildIndex - #1328

Merged
xdustinface merged 4 commits into
devfrom
refactor/child-index
Dec 3, 2026
Merged

xdustinface merged 4 commits into
devfrom
refactor/child-index

Conversation

@ZocoLini

@ZocoLini ZocoLini commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

ChildNumber::Normal and Hardened now hold a ChildIndex: a u32 below 2^31 that can only be built through ChildIndex::new, ChildIndex::new_const (checked at compile time in const contexts) or deserialization (serde and bincode), all of which check the range. The wire format is unchanged.

Account-level indexes take ChildIndex end to end (AccountType, ManagedAccountType, the account collections, wallet helpers, transaction building and the key-wallet-manager accessors), so the derivation paths built from them cannot fail at runtime.

Breaking changes:

  • ChildNumber::from_normal_idx and from_hardened_idx are removed; use ChildNumber::Normal(..) / Hardened(..) directly.
  • ChildNumber::from_idx takes a ChildIndex and returns ChildNumber.
  • ChildNumber variants are tuple variants.
  • The dip9 path builders and AccountType::derivation_path no longer return Result.
  • AccountType index fields, index() and the collection keys are ChildIndex.
  • DerivationPathBuilder is removed.
  • DerivationPath::application_encryption_path takes rotation: ChildIndex and no longer returns Result.
  • ManagedPlatformAccount::new takes ChildIndex for account and key_class.

Address pool indexes stay u32, since they are counters with arithmetic, and are validated when the child number is built.

PR Hygiene · eb5dcab

  • Bots — coderabbitai ✓
  • Self-review — posted; again after any push
  • Build green
  • Approvals
    • dash-spv (dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs, dash-spv/src/sync/mempool/sync_manager.rs, dash-spv/src/test_utils/wallet.rs and 3 more) — QuantumExplorer or xdustinface
    • key-wallet-manager (key-wallet-manager/benches/filter_scan.rs, key-wallet-manager/examples/wallet_creation.rs, key-wallet-manager/src/accessors.rs and 7 more) — QuantumExplorer or xdustinface
    • key-wallet (key-wallet/benches/address_generation.rs, key-wallet/examples/account_types.rs, key-wallet/examples/basic_usage.rs and 62 more) — QuantumExplorer or xdustinface

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

Summary by CodeRabbit

  • API Changes
    • Account and key-derivation indices now use a dedicated, range-checked index type across wallet APIs.
    • Derivation paths are returned directly rather than through fallible results.
    • The path builder API has been removed; callers using it will need to update.

@coderabbitai

coderabbitai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change introduces ChildIndex as a bounded type for BIP32 child and wallet account indices. It updates derivation, account, wallet, and transaction APIs to use the type, removes DerivationPathBuilder, and migrates related call sites and tests.

Changes: Typed child-index migration

Layer / File(s) Summary
Child-index and derivation-path types
key-wallet/src/bip32.rs, key-wallet/src/dip9.rs, key-wallet/src/derivation.rs, key-wallet/src/derivation_slip10.rs, key-wallet/src/lib.rs
Adds bounded ChildIndex constructors and updates ChildNumber and derivation-path APIs to use typed indices. Removes DerivationPathBuilder and its crate-root re-export.
Account and address derivation models
key-wallet/src/account/*, key-wallet/src/managed_account/*, key-wallet/src/derivation_bls_bip32.rs
Changes account indices, collection keys, and derivation methods to use ChildIndex. Updates address-pool child construction and account derivation.
Wallet and transaction interfaces
key-wallet/src/wallet/*, key-wallet/src/transaction_checking/account_checker.rs, key-wallet-manager/src/accessors.rs, key-wallet-manager/src/lib.rs
Changes wallet lookup, transaction-building, asset-lock, and transaction-checking index parameters and related account-index collections to ChildIndex.
Call sites and validation
dash-spv/*, key-wallet-manager/*, key-wallet/examples/*, key-wallet/benches/*, key-wallet/src/tests/*, key-wallet/tests/*
Updates account-index call sites and fixtures to construct typed indices. Tests cover the valid 31-bit boundary and reject out-of-range decoding.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Refactor

Suggested reviewers: pastapastapasta, quantumexplorer

Merge Risk: Minimal · up to eb5dc

This refactor replaces raw integer account and child indices with a validated 31-bit type, and it removes DerivationPathBuilder and makes the path builders return paths directly. Existing serialized data keeps the same encoding for all valid indices. No concrete defect was found in the supplied changes. The breaking API changes are intentional and called out in the PR description.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a new ChildIndex type that validates child indexes at construction. The changeset adds ChildIndex in key-wallet/src/bip32.rs, migrates account-level indexes and wallet…
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: a new ChildIndex type that validates child indexes at construction. The changeset adds ChildIndex in key-wallet/src/bip32.rs, migrates account-level indexes and wallet APIs to it, and removes from_normal_idx and from_hardened_idx. The title is specific and matches the primary change. It uses the conventional commit prefix refactor(key-wallet)! to mark a breaking change.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4b3765c and eb5dcab.

Files selected for processing: 81

  • dash-spv/src/sync/filters/coinjoin_gap_discovery_tests.rs
  • dash-spv/src/sync/mempool/sync_manager.rs
  • dash-spv/src/test_utils/wallet.rs
  • dash-spv/tests/dashd_sync/helpers.rs
  • dash-spv/tests/dashd_sync/tests_multi_wallet.rs
  • dash-spv/tests/dashd_sync/tests_transaction.rs
  • key-wallet-manager/benches/filter_scan.rs
  • key-wallet-manager/examples/wallet_creation.rs
  • key-wallet-manager/src/accessors.rs
  • key-wallet-manager/src/event_tests.rs
  • key-wallet-manager/src/events.rs
  • key-wallet-manager/src/lib.rs
  • key-wallet-manager/src/process_block.rs
  • key-wallet-manager/src/test_utils/addresses.rs
  • key-wallet-manager/tests/integration_test.rs
  • key-wallet-manager/tests/spv_integration_tests.rs
  • key-wallet/benches/address_generation.rs
  • key-wallet/examples/account_types.rs
  • key-wallet/examples/basic_usage.rs
  • key-wallet/src/account/account_collection.rs
  • key-wallet/src/account/account_collection_test.rs
  • key-wallet/src/account/account_trait.rs
  • key-wallet/src/account/account_type.rs
  • key-wallet/src/account/bls_account.rs
  • key-wallet/src/account/derivation.rs
  • key-wallet/src/account/eddsa_account.rs
  • key-wallet/src/account/mod.rs
  • key-wallet/src/account/serialization.rs
  • key-wallet/src/address_metadata_tests.rs
  • key-wallet/src/bip32.rs
  • key-wallet/src/derivation.rs
  • key-wallet/src/derivation_bls_bip32.rs
  • key-wallet/src/derivation_slip10.rs
  • key-wallet/src/dip9.rs
  • key-wallet/src/lib.rs
  • key-wallet/src/managed_account/address_pool.rs
  • key-wallet/src/managed_account/managed_account_collection.rs
  • key-wallet/src/managed_account/managed_account_trait.rs
  • key-wallet/src/managed_account/managed_account_type.rs
  • key-wallet/src/managed_account/managed_core_funds_account.rs
  • key-wallet/src/managed_account/managed_platform_account.rs
  • key-wallet/src/managed_account/transaction_record.rs
  • key-wallet/src/test_utils/account.rs
  • key-wallet/src/test_utils/wallet.rs
  • key-wallet/src/tests/account_tests.rs
  • key-wallet/src/tests/address_reservation_tests.rs
  • key-wallet/src/tests/advanced_transaction_tests.rs
  • key-wallet/src/tests/backup_restore_tests.rs
  • key-wallet/src/tests/dashpay_contact_gap_limit_tests.rs
  • key-wallet/src/tests/edge_case_tests.rs
  • key-wallet/src/tests/integration_tests.rs
  • key-wallet/src/tests/keep_finalized_transactions_tests.rs
  • key-wallet/src/tests/locked_outpoints_tests.rs
  • key-wallet/src/tests/observed_spent_outpoints_tests.rs
  • key-wallet/src/tests/performance_tests.rs
  • key-wallet/src/tests/provider_key_derivation_tests.rs
  • key-wallet/src/tests/restore_utxos_tests.rs
  • key-wallet/src/tests/special_transaction_matching_tests.rs
  • key-wallet/src/tests/spent_outpoints_tests.rs
  • key-wallet/src/tests/unit_variant_wallet_tests.rs
  • key-wallet/src/tests/wallet_tests.rs
  • key-wallet/src/transaction_checking/account_checker.rs
  • key-wallet/src/transaction_checking/transaction_router/tests/asset_unlock.rs
  • key-wallet/src/transaction_checking/transaction_router/tests/conversions.rs
  • key-wallet/src/transaction_checking/transaction_router/tests/provider.rs
  • key-wallet/src/transaction_checking/transaction_router/tests/routing.rs
  • key-wallet/src/transaction_checking/wallet_checker.rs
  • key-wallet/src/wallet/accounts.rs
  • key-wallet/src/wallet/helper.rs
  • key-wallet/src/wallet/initialization.rs
  • key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs
  • key-wallet/src/wallet/managed_wallet_info/helpers.rs
  • key-wallet/src/wallet/managed_wallet_info/managed_accounts.rs
  • key-wallet/src/wallet/managed_wallet_info/mod.rs
  • key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs
  • key-wallet/src/wallet/managed_wallet_info/transaction_building.rs
  • key-wallet/src/wallet/managed_wallet_info/wallet_info_interface.rs
  • key-wallet/src/wallet/mod.rs
  • key-wallet/src/wallet_comprehensive_tests.rs
  • key-wallet/tests/bip32_tests.rs
  • key-wallet/tests/key_debug_tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.97913% with 74 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.84%. Comparing base (4b3765c) to head (eb5dcab).
⚠️ Report is 15 commits behind head on dev.

Files with missing lines Patch % Lines
...y-wallet/src/wallet/managed_wallet_info/helpers.rs 43.24% 21 Missing ⚠️
key-wallet/src/bip32.rs 94.08% 12 Missing ⚠️
.../src/managed_account/managed_account_collection.rs 37.50% 5 Missing ⚠️
...wallet/src/managed_account/managed_account_type.rs 50.00% 4 Missing ⚠️
...wallet/src/transaction_checking/account_checker.rs 81.81% 4 Missing ⚠️
key-wallet/src/wallet/helper.rs 69.23% 4 Missing ⚠️
key-wallet/src/account/mod.rs 70.00% 3 Missing ⚠️
key-wallet/src/derivation_slip10.rs 84.21% 3 Missing ⚠️
key-wallet/src/dip9.rs 93.61% 3 Missing ⚠️
key-wallet/src/account/bls_account.rs 86.66% 2 Missing ⚠️
... and 10 more
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1328      +/-   ##
==========================================
+ Coverage   87.70%   87.84%   +0.14%     
==========================================
  Files         270      270              
  Lines       72144    72035     -109     
==========================================
+ Hits        63271    63277       +6     
+ Misses       8873     8758     -115     
Flag Coverage Δ
core 83.58% <92.95%> (+0.21%) ⬆️
rpc 83.58% <92.95%> (+0.21%) ⬆️
spv 95.22% <100.00%> (-0.01%) ⬇️
wallet 83.58% <92.95%> (+0.21%) ⬆️
Files with missing lines Coverage Δ
dash-spv/src/sync/mempool/sync_manager.rs 99.53% <100.00%> (ø)
key-wallet-manager/src/events.rs 69.10% <100.00%> (+0.51%) ⬆️
key-wallet-manager/src/process_block.rs 95.77% <100.00%> (ø)
key-wallet/src/account/account_collection.rs 71.78% <100.00%> (ø)
key-wallet/src/account/account_collection_test.rs 100.00% <100.00%> (ø)
key-wallet/src/account/serialization.rs 100.00% <100.00%> (ø)
key-wallet/src/derivation_bls_bip32.rs 95.87% <100.00%> (+0.04%) ⬆️
key-wallet/src/managed_account/address_pool.rs 90.66% <100.00%> (-0.02%) ⬇️
.../src/managed_account/managed_core_funds_account.rs 89.76% <100.00%> (ø)
...et/src/managed_account/managed_platform_account.rs 63.12% <100.00%> (+1.63%) ⬆️
... and 29 more

... and 2 files with indirect coverage changes

Base automatically changed from fix/dip9-child-index-check to dev November 5, 2026 13:10
@github-actions github-actions Bot added the merge-conflict The PR conflicts with the target branch. label Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

This PR has merge conflicts with the base branch. Please rebase or merge the base branch into your branch to resolve them.

@github-actions github-actions Bot added merge-conflict The PR conflicts with the target branch. and removed merge-conflict The PR conflicts with the target branch. labels Nov 9, 2026
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

This PR has merge conflicts with the base branch. Please rebase or merge the base branch into your branch to resolve them.

@github-actions github-actions Bot added merge-conflict The PR conflicts with the target branch. and removed merge-conflict The PR conflicts with the target branch. labels Nov 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR has merge conflicts with the base branch. Please rebase or merge the base branch into your branch to resolve them.

…hildIndex`

`ChildNumber::Normal` and `Hardened` now hold a `ChildIndex`, a `u32` below 2^31
that can only be built through `ChildIndex::new`, `new_const` or deserialization,
all of which check the range. Account indexes (`AccountType`, collections, wallet
and manager accessors) take `ChildIndex`, so derivation paths built from them
can no longer fail at runtime.

- `from_normal_idx` and `from_hardened_idx` are removed; use the variants directly.
- `from_idx` takes a `ChildIndex` and no longer returns a `Result`.
- `dip9` path builders and `AccountType::derivation_path` are infallible.
- `DerivationPathBuilder` is removed.
@ZocoLini
ZocoLini force-pushed the refactor/child-index branch from 78d26db to 0733b9d Compare November 24, 2026 18:03
@github-actions github-actions Bot removed the merge-conflict The PR conflicts with the target branch. label Nov 24, 2026
@ZocoLini
ZocoLini marked this pull request as ready for review November 24, 2026 18:04
@ZocoLini
ZocoLini requested a review from xdustinface November 24, 2026 18:04
@manki-review

manki-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Review superseded by a later review of 0733b9d. This attempt ended as follows.

🔴 Review failed in 17m 28s

Planner (8s)
    refactor · 3893 lines · 2 agents
    judge effort: high

Review (security · full): 44 findings
    ✅ Claude Opus 5.5 · high: 9 findings (3m 7s)
    ✅ GPT 6.2 Sol · high: 28 findings (5m 8s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 27 of 27 done, 7 findings (1m 48s)

Judge

@github-actions

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Nov 24, 2026

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏸️ Review incomplete: The judge failed. Retry with /manki review.

  • Review again
About this review

@manki-review

manki-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

✅ Review complete in 15m 29s

Started automatically, since no review of this commit had finished.

Planner (5s)
    refactor · 3893 lines · 2 agents
    judge effort: high

Review (security · full): 35 findings
    ✅ Claude Opus 5.5 · high: 6 findings (2m 50s)
    ✅ GPT 6.2 Sol · high: 23 findings (3m 38s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 27 of 27 done, 6 findings (1m 40s)

Judge (11m 0s)
    graded 35 findings: 19 kept · 3 dropped · 13 merged
    dropped, as the finders filed them: 1 blocker · 1 warning · 1 suggestion
    refuter: 8 checked · 3 confirmed · 2 disproved · 3 unsettled
    origin checks: 8 checked · 4 older than this PR
    sweeps: 2 of 2 done (49s)
    verdict reader: read the diff (1m 18s)

Posted: 9 findings
    6 warnings · 3 suggestions
    not posted: 2 older than this PR · 7 over the review.notes limit · 1 no proof

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner, security-sensitive paths)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 36% (resets 2026-12-01 05:00 UTC)
  • ChatGPT subscription: weekly 27% (resets 2026-11-25 01:21 UTC)

Judge decisions:

  • Kept: "Removed ChildNumber constructors and struct variants break dashpay/platform and dash-evo-tool on upgrade" (warning): "warning. A change that breaks a consumer is the degraded row by the repository rule. The description lists these as breaking changes and does not claim nothing breaks. bip32.rs:615 makes the variants tuple variants and drops from_normal_idx and from_hardened_idx. The shown consumer code still calls them: address_paths.rs:63, auto_accept.rs:97, invitation.rs:82, persistence.rs:13747. core_address_key.rs:168 still calls .map_err on derivation_path(), which account_type.rs:374 makes infallible."
  • Kept: "Ed25519 public-key decode now accepts a non-hardened child number that private-key decode rejects" (suggestion): "note. derivation_slip10.rs:393 now uses ChildNumber::from, so non-root bytes with bit 31 clear decode as Normal. Private decode rejects the same bytes at line 244. The old public decode accepted these bytes too, but forced the flag to hardened. So acceptance is unchanged and only the reported hardening flag differs, and nothing shown consumes it. Adding the same check as the private decode would make the two decoders agree."
  • Not listed, a check of the code could not confirm it: "Consumer dashpay/platform breaks on the dip9 path builders that no longer return Result" (warning): "warning. dip9.rs:636 changes application_encryption_path to take rotation: ChildIndex and return Self. identity_handle.rs:242-249 passes a u32 and calls .map_err on the result. dash-evo-tool model/wallet/mod.rs:1488 and :1513 pass u32 values to identity_invitation_path and identity_top_up_path. The description lists these as breaking, so this is a consumer break on upgrade.
    Refutation unsettled: At the base commit application_encryption_path and its sibling builders take u32 and return Result<Self, Error>. At the head commit they take ChildIndex and return Self. dashpay/platform passes rotation and calls .map_err(...) on the returned value, so that code stops compiling once it builds against this version. Rule checked: In Rust, a public function whose parameter type changes from u32 to a newtype, and whose return type changes from Result<Self, Error> to Self, breaks every caller that passes a u32 or calls .map_err or ? on the result. DerivationPath has no map_err method.
  • Premise "This trigger happens in realistic use: when dashpay/platform or dash-evo-tool bumps its key-wallet dependency" unsettled. The code does show that platform's rs-platform-wallet uses key-wallet through { workspace = true } and calls the changed API in a way that will not compile. But the workspace root that pins the version was not fetched, and whether or when platform or dash-evo-tool bumps the dependency is up to their maintainers, which no code shows.
    Pair refutation confirmed: Platform passes a u32 rotation and calls .map_err, but the PR's builder takes ChildIndex and returns DerivationPath directly. The source shows an API mismatch on an unchanged upgrade, but no downstream build result verifies the claimed compilation failure. Rule checked: Rust does not implicitly convert a u32 to a newtype or preserve Result methods when a function returns a bare value.
  • Premise "This trigger happens in realistic use: when dashpay/platform or dash-evo-tool bumps its key-wallet dependency" confirmed. A dependency bump is a real upgrade path: Platform declares key-wallet as a workspace dependency, and Dash Evo Tool already resolves it from a pinned rust-dashcore revision."
  • Kept: "Account index parameters change from u32 to ChildIndex, so both consumer repos stop compiling on upgrade" (warning): "warning. helper.rs:16 now takes ChildIndex. So does asset_lock_builder.rs:118. The account maps at account_collection.rs:48 and managed_account_collection.rs:44 and the registration_index field at account_type.rs:52 are now keyed or typed by ChildIndex. ChildIndex has no From<u32>. The shown consumer code passes integer literals and u32 values: payments.rs:1811, build.rs:311, persistence.rs:4875. It breaks once the consumers upgrade."
  • Kept: "Wallet backups written by the old xpub import API can no longer be restored" (warning): "blocker if confirmed. The Some(xpub) branch of add_account at accounts.rs:38 goes to Account::new/from_xpub (mod.rs:101), which store the account type as-is, so such an account could be created and backed up. The new decoders at bip32.rs:589 and bip32.rs:598 reject the old u32 value, and backup.rs:51 fails the whole restore, which is lost data. This also breaks the quoted key-wallet/AGENTS.md rule that existing serialized data must stay decodable. The trigger needs a caller to pass an out-of-range index, so rareTrigger is set.
    Refutation unsettled: On the base revision, add_account with Some(xpub) stores the AccountType unchecked, insert keys maps by the raw u32, and backup encodes the wallet. On head, ChildIndex's Decode and Deserialize call ChildIndex::new, which rejects bit 31, and Wallet::restore decodes the whole wallet in one call, so any such stored index fails the entire restore. Rule checked: A bincode/serde decoder that rejects values the previous encoder wrote makes the old encoded data undecodable, and a derived decode of an enclosing struct propagates that error for the whole value.
  • Premise "On the base revision, Wallet::add_account with Some(xpub), Account::new and AccountCollection::insert accept an AccountType whose index has bit 31 set without returning an error" confirmed. On base, the Some(xpub) branch goes straight to Account::new and from_xpub, which store account_type without checks. The duplicate checks look only at type and xpub, not the index range. insert puts the raw index into the maps and returns Ok for every indexed variant.
  • Premise "This trigger happens in realistic use: when a wallet backed up after importing an account xpub under an index of 2^31 or more is restored after the upgrade" unsettled. Public APIs accept any u32 index for an xpub import: key-wallet's add_account and platform's register_contact_account, whose account_index flows into add_account unchecked. But the callers I found pass 0 or go through derivation_path first, which on base rejects hardened-overflow indexes, and I could not trace where register_contact_account's account_index comes from.
    Pair refutation unsettled: The new ChildIndex decoder rejects a legacy index with bit 31 set. Wallet::restore propagates that error and returns no wallet, so unrelated accounts in the same backup are not restored either. Rule checked: Replacing a serialized integer with a type whose decoder accepts fewer values makes legacy records containing newly rejected values unreadable.
  • Premise "On the base revision, Wallet::add_account with Some(xpub), Account::new and AccountCollection::insert accept an AccountType whose index has bit 31 set without returning an error" confirmed. On the base revision, a supplied xpub bypassed path derivation, Account::new stored the raw AccountType unchanged, and the collection inserted its u32 fields without a range check when the duplicate checks passed.
  • Premise "This trigger happens in realistic use: when a wallet backed up after importing an account xpub under an index of 2^31 or more is restored after the upgrade" unsettled. The API documents xpub import and backup restoration, but the checked import example uses index 5, and no checked caller, documented workflow, or stored backup shows an index with bit 31 set."
  • Not listed, over the review.notes limit: "The public const constructor panics on runtime indexes" (suggestion): "note. bip32.rs:562 adds an assert! to a public const fn that can also run at runtime. This breaks the quoted rule that library code never panics. No library caller shown passes an unchecked runtime value. The runtime use in account_type.rs:375 is always 5 or 1. The panic is documented, and the checked ChildIndex::new exists. The damage is limited to a caller misusing a documented panicking constructor."
  • Kept: "Bound identity top-up private keys derive the registration index twice" (blocker): "blocker if confirmed. account_type.rs:436 puts the hardened registration index in the account path. mod.rs:178, bls_account.rs:300 and eddsa_account.rs:271 return it again as the intermediate. derivation.rs:165-168 appends that intermediate after the account xpriv, giving .../reg'/reg'/leaf where DIP-13 has .../reg'/leaf. This PR only changed types around the same layout, and the base had it too, so it is marked pre-existing. Whether a caller uses this key for signing is not shown.
    Refutation confirmed: For IdentityTopUp, the account path already ends with Hardened(registration_index). derive_from_master_xpriv_extended_xpriv_at builds the account xpriv from that path, then adds has_intermediate_derivation(), which is Hardened(registration_index) again, before the leaf. The result is m/9'/c'/5'/2'/reg'/reg'/i instead of the DIP-13 path .../reg'/i that dip9::identity_top_up_path builds. Nothing else in the crate uses has_intermediate_derivation, so keys derived from the account xpub skip the extr... Rule checked: In BIP32, deriving a child path from an account xpriv adds its levels after the account path, so a hardened level that is already in the account path and is added again ends up in the final path twice.
    Pair refutation confirmed: For a non-watch-only bound top-up account, the account xpriv already ends in registration_index', but the shared helper appends registration_index' again before the leaf, so the ECDSA signing key does not match the DIP-0013 path or the leaf derived from the account xpub. The BLS and EdDSA helpers also repeat the registration level; EdDSA uses a hardened leaf and does not support child derivation from an xpub. Rule checked: Hierarchical key derivation applies each path component relative to the current key, so repeating an index descends another level rather than reusing the same node."
  • Not listed, on code this PR did not change: "Serde drops the index and hardening flag of both 256-bit child variants" (warning): "blocker if confirmed. bip32.rs:735, a line this PR rewrites, maps Normal256 and Hardened256 to u32::MAX. Serde writes u32::from(*self) (line 817) and reads it back through From<u32> (line 807), which gives Hardened(0x7FFFFFFF). The 256-bit index is lost. Whether serde data in practice reaches this impl for paths is not shown.
    Refutation unsettled: ChildNumber's own serde impl writes u32::from(*self), which is u32::MAX for both 256-bit variants. It reads that back through From, which gives Hardened(0x7FFFFFFF), so a directly serialized 256-bit ChildNumber does not round-trip. The base commit already had the same u32::MAX mapping, so this PR only rewrote the syntax. Paths and address pools do not go through this impl, because they serialize as strings. Rule checked: A serde impl that writes a lossy u32 projection of an enum cannot read back the variants that projection merges: here every 256-bit child becomes u32::MAX, and From turns that into Hardened(2^31-1).
  • Premise "Serde serialization of DerivationPath, AddressInfo or an extended key encodes each ChildNumber through the ChildNumber serde impl at key-wallet/src/bip32.rs:812-818, not a string form" disproved. DerivationPath serializes as its Display string, which writes 256-bit children as 0x-hex and parses them back. AddressInfo stores a DerivationPath, and the secp extended keys serialize as strings. Only the BLS extended keys serialize child_number through the ChildNumber impl, and BLS derivation rejects 256-bit children, so derivation never stores one there.
  • Premise "A DashPay address pool persisted through serde stores a path with Normal256 components that reads back as Hardened(2^31-1)" disproved. AddressInfo.path is a DerivationPath, and it serializes through to_string and reads back through FromStr. Normal256 components are written as 0x-hex and parsed back as Normal256, not as Hardened(2^31-1).
    Pair refutation unsettled: Direct Serde serialization of either 256-bit ChildNumber variant writes u32::MAX, which decodes as Hardened(2147483647). Private derivation then uses a four-byte hardened index instead of the original 32-byte index, and public derivation rejects the result where it would accept Normal256. Rule checked: A serialization format that maps distinct values to the same representation cannot reconstruct the original value.
  • Premise "Serde serialization of DerivationPath, AddressInfo or an extended key encodes each ChildNumber through the ChildNumber serde impl at key-wallet/src/bip32.rs:812-818, not a string form" disproved. DerivationPath and both BIP32 extended keys serialize as strings, and AddressInfo delegates its path field to DerivationPath's serializer.
  • Premise "A DashPay address pool persisted through serde stores a path with Normal256 components that reads back as Hardened(2^31-1)" disproved. DashPay paths contain Normal256 components, but the pool's base path and address paths use DerivationPath's string encoding, which writes those components as hex and parses them back as Normal256."
  • Not listed, on code this PR did not change: "Small 256-bit child indexes bypass DIP-14 compatibility mode" (warning): "warning. DIP-14 lines 123 and 154 require ser32(i) for indexes below 2^32. bip32.rs:1269, bip32.rs:1275 and bip32.rs:1518 always hash 32 bytes. Those HMAC lines are unchanged by this PR, which only renamed the match arms, so this is pre-existing. A small value needs a caller to build a 256-bit child below 2^32, which DashPay identity ids do not produce, so rareTrigger is set."
  • Kept: "The examples derive keys outside the accounts they demonstrate" (suggestion): "note. basic_usage.rs:73-75 builds m/9'/5'/0' without the 4' CoinJoin feature level. basic_usage.rs:83-87 builds m/13'/5'/3'/0'/0', which is not the DIP-13 path. An example that misstates the wallet's paths misleads readers who copy it. Using coinjoin_path and identity_authentication_path fixes both."
  • Not listed, over the review.notes limit: "Account derivation duplicates the BIP44 and CoinJoin path builders" (suggestion): "note. The BIP44 and CoinJoin arms at account_type.rs:389 and :405 rebuild paths that bip_44_account and coinjoin_path in dip9.rs already build. Delegating keeps one source for wallet-critical paths."
  • Not listed, over the review.notes limit: "New imports are declared inside functions" (suggestion): "note. bip32.rs:588 adds use serde::de::Error as _; inside deserialize. account_tests.rs:538 adds ChildIndex to a function-local use that the module already imports. Both break the root AGENTS.md import rule."
  • Dropped: "Derivation path decoding may allocate from an untrusted length prefix" (ignore): "ignore. The lead is about the DerivationPath bincode impl, which delegates to Vec<ChildNumber>. The cited head code at bip32.rs:832-840 shows that impl outside the changed hunks. Changing ChildNumber's element decode does not change how the vector allocates, so this PR neither causes nor exposes the concern.
    Refutation disproved: The DerivationPath impls pass decoding straight to Vec:: (bip32.rs:847, 856). Whether that reserves memory from the length prefix depends on grovedb-bincode 2.1.0, the workspace's renamed bincode package, and Manki refused to read its source, so the allocation behaviour is unchecked. Rule checked: bincode's Vec decoder reads a length prefix and may reserve capacity for that many elements before it decodes them; with no byte limit configured, the reservation is not bounded by how many bytes the input actually has.
  • Premise "This PR does not change the bincode Decode and BorrowDecode impls of DerivationPath in key-wallet/src/bip32.rs, which delegate to Vec<ChildNumber>" confirmed. The DerivationPath Encode/Decode/BorrowDecode impls at head (bip32.rs:833-858) are identical to base (bip32.rs:886-911), and both delegate to Vec::, so the PR does not change them.
    Pair refutation disproved: Both DerivationPath decoders delegate directly to Vec, but the tool refused to read the pinned grovedb-bincode 2.1.0 source, so the allocation order is unverified. AddressPool.base_path and AddressInfo.path are decoded fields, but no route from Wallet::restore to those fields was established. Rule checked: A length-prefixed vector decoder can allocate more memory than the input warrants if it reserves capacity before checking the remaining bytes or enforcing a size limit.
  • Premise "This PR does not change the bincode Decode and BorrowDecode impls of DerivationPath in key-wallet/src/bip32.rs, which delegate to Vec<ChildNumber>" confirmed. The base and head implementations are identical: both Decode and BorrowDecode delegate directly to Vec."
  • Kept: "Public address derivation accepts unbounded amounts of work" (warning): "warning. derivation.rs:58 reserves count entries before checking anything. derivation.rs:60 computes start_index + count unchecked, which panics in debug and wraps in release. scan_for_activity (lines 87-94) and generate_addresses (address_pool.rs:416) have no total bound. These lines are unchanged by this PR, which only swapped the per-child constructor, so this is pre-existing. It needs a caller to pass a near-u32::MAX count, so rareTrigger is set.
    Refutation unsettled: derive_batch reserves count slots and computes start_index + count before any per-child check. scan_for_activity only stops after gap_limit unused keys in a row. generate_addresses derives and stores every index in start..start.saturating_add(count) with no total cap. So these public calls do unbounded work when given extreme inputs. Rule checked: In Rust, u32 addition panics on overflow when overflow checks are on and wraps when they are off, and a loop or range with no total cap runs as long as its inputs let it.
  • Premise "This trigger happens in realistic use: the sequence of events the description names" disproved. Nothing calls these APIs with an extreme count. derive_batch and scan_for_activity are only re-exported (lib.rs:46) and have no callers in this repo or in the platform or dash-evo-tool repos. Every in-repo call to generate_addresses passes a small count: the gap limit, which is clamped to MAX_GAP_LIMIT = 1000, or 1, or a bounded generate_up_to. The only route that takes an outside index, extend_coinjoin_pools, has no caller.
    Pair refutation unsettled: The batch reserves capacity from the caller's count and computes the unchecked endpoint before validating any child. With a positive gap limit, repeated activity reports keep the scan running, and pool generation retains each successful derivation even if a later index fails; neither loop has a work budget below the 31-bit index ceiling. Rule checked: A per-child index check does not limit allocation or total work, and Rust integer addition panics on overflow when checks are enabled and wraps otherwise.
  • Premise "This trigger happens in realistic use: the sequence of events the description names" unsettled. The documented CoinJoin migration path forwards a caller-supplied last index into batch generation, but the checked code does not show normal callers or stored data supplying an excessive range or a scan reporting sustained activity."
  • Kept: "Generated hardened addresses report a non-hardened derivation path" (blocker): "blocker if confirmed. address_pool.rs:444 always pushes ChildNumber::Normal onto full_path. address_pool.rs:462 derives AbsentHardened with Hardened. address_pool.rs:515 stores full_path. The path returned to callers names a different key: Ed25519 rejects the normal step, and ECDSA derives another key. The line is changed by this PR. Whether a caller re-derives from this path is not shown.
    Refutation confirmed: generate_address_at_index always appends ChildNumber::Normal(index) to the recorded full_path, but derives an AbsentHardened pool's key with ChildNumber::Hardened(index). It stores the normal-step path in AddressInfo, and get_address_derivation_path returns that path. ProviderPlatformKeys uses an AbsentHardened pool, so this code is reached. A normal step makes SLIP-10 ckd_priv fail with NonHardenedNotSupported. The base commit already had the same mismatch at the same line (ChildNumber::from_no... Rule checked: In BIP32 and SLIP-10, a hardened child and a normal child with the same index are different derivation steps: ECDSA gives a different key for each, and Ed25519 accepts only hardened steps. A recorded path that swaps one for the other therefore cannot reproduce the key.
    Pair refutation confirmed: Provider platform accounts select an AbsentHardened pool, which derives the address with a hardened final child but stores a normal final child and returns it unchanged on lookup. Reusing the reported path fails for Ed25519 and derives the wrong key for ECDSA. Rule checked: A derivation path must preserve whether each child is hardened: BIP32 uses different inputs for hardened and normal children, and Ed25519 SLIP-10 rejects normal children."
  • Not listed, over the review.notes limit: "The identity registration helper derives a different key from Dash Core" (suggestion): "note. dip9.rs:547 appends a hardened index, while DIP-13 line 115 and Dash Core platformkeys.cpp:45 use a normal leaf. The base code already did this, and dip9.rs:538 has a separate non-hardened builder, so the hardened layout looks like a deliberate legacy choice. key-wallet/AGENTS.md forbids changing an existing path. This is a question on which builder registration funding should use."
  • Kept: "The maximum-index test discards the path it is meant to check" (suggestion): "note. edge_case_tests.rs:23 discards the returned path, so the test passes even if the account index is dropped. It also never checks that ChildIndex::new(1 << 31) fails. It still runs the code and would catch a panic, so this is a missing assertion, not a test that cannot fail."
  • Not listed, over the review.notes limit: "The address-pool branch builders use a fully qualified path instead of an import" (suggestion): "note. The changed lines at managed_account_type.rs:525 and :535 spell out crate::bip32::ChildNumber, which breaks the root rule against fully qualified paths."
  • Dropped: "Invitation funding may use different leaf hardening in the helper and the managed pool" (ignore): "ignore. dip9.rs:570 keeps the base's hardened leaf unchanged, and key-wallet/AGENTS.md forbids changing an existing path, so at most this is a note on a legacy layout. A note that rests on unseen code, here how the invitation pool gets its keys, is dropped."
  • Not listed, over the review.notes limit: "Transaction matchers report account zero when the caller omits the index" (suggestion): "note. unwrap_or_default() at account_checker.rs:784 and the sibling lines is the same explicit fallback to 0 as the base's unwrap_or(0). The only in-repo None caller, wallet_checker.rs:95, does not read the index. Deriving the index from the account's own type would remove the redundant argument. This is a question on that design."
  • Not listed, over the review.notes limit: "The first Platform payment account lookup misses nonzero accounts" (suggestion): "note. helpers.rs:628 promises the lowest account index with key class 0, but helpers.rs:630 and :639 look up only (0, 0). That matches the other first_* helpers, which all use index 0. So the doc misstates the code, and either the doc or the lookup should change."
  • Dropped: "ExtendedEd25519PrivKey::new_master has no 64-byte upper bound on the seed" (ignore): "ignore. derivation_slip10.rs:83 is outside every hunk of this PR, and the finding itself says nothing breaks. Code the PR does not touch or affect is not a finding."

Timing:

  • Parse: 5.9s
  • Review agents: 263.1s
  • Judge: 660.3s
  • Total: 929.4s

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ 4 warnings to address. Fix each one, reply in its thread with a reason Manki accepts, or tick Create an issue for this to track it for later. Manki approves once every warning is handled.

Started automatically, since no review of this commit had finished.


Pre-existing · 2 warnings

This PR did not cause these, so none of them block: each is on lines the PR did not change, or the code fails the same way without the PR.

⚠️ Bound identity top-up private keys derive the registration index twice
Warning, not blocking · Pre-existing · Correctness · Moderate · key-wallet/src/account/derivation.rs:165

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/account/derivation.rs:163, so it doesn't block this PR.

What goes wrong: The account key already includes the hardened registration index, but the master-to-child helper appends that level again before the leaf. The resulting private key does not match the standard top-up path or the key derived at the same leaf from the account xpub. The same extra step is present in the ECDSA, BLS, and EdDSA account helpers.

How to fix it
Make the account path the single source for the registration level and append only the leaf in the shared child derivation helper. Verify the ECDSA result against DerivationPath::identity_top_up_path and the account xpub, and preserve discovery of any keys already issued under the duplicated path.

  • Create an issue for this
⚠️ Generated hardened addresses report a non-hardened derivation path
Warning, not blocking · Pre-existing · Correctness · Quick fix · key-wallet/src/managed_account/address_pool.rs:444

Already broken before this PR. Two checks found the same problem on dev at key-wallet/src/managed_account/address_pool.rs:444, so it doesn't block this PR.

What goes wrong: An AbsentHardened pool derives the key with a hardened child but saves an unhardened child in AddressInfo.path. A caller using the stored path cannot reproduce the key: Ed25519 rejects the normal step, and ECDSA derives a different key.

How to fix it
Validate the index once and choose its hardening from pool_type. Use that same child for actual derivation and recorded metadata, and correct existing stored metadata for hardened pools without changing their addresses.

  • Create an issue for this

7 suggestions are not listed.


Checked and left out: 2 findings (1 disproved, 1 unproven)

Disproved by a check of the code · 1 finding

  • Derivation path decoding may allocate from an untrusted length prefix · key-wallet/src/bip32.rs:856
    The DerivationPath impls pass decoding straight to Vec:: (bip32.rs:847, 856). Whether that reserves memory from the length prefix depends on grovedb-bincode 2.1.0, the workspace's renamed bincode package, and Manki refused to read its source, so the allocation behaviour is unchecked.

Not proven, so not listed · 1 warning

  • Consumer dashpay/platform breaks on the dip9 path builders that no longer return Result · key-wallet/src/dip9.rs:636
    A check of the code could not confirm it.

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed 0733b9d, round 1
  • 3893 changed lines read in 15m 29s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 18.1M in (14.5M from cache) · 187k out · about $19.76 at API prices
  • Runner: self-hosted · started after 6s · peak memory 7.7 GiB of 30.0 GiB
  • How Manki reviews

Comment thread key-wallet/src/bip32.rs Resolved
Comment thread key-wallet/src/wallet/helper.rs Resolved
Comment thread key-wallet/src/bip32.rs Resolved
Comment thread key-wallet/src/derivation.rs Resolved
Comment thread key-wallet/src/derivation_slip10.rs Resolved
Comment thread key-wallet/src/tests/edge_case_tests.rs Resolved
Comment thread key-wallet/examples/basic_usage.rs Resolved
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. and removed waiting-bots Waiting for the review bots to report on this head labels Nov 24, 2026
Ed25519 only derives hardened children, but `ExtendedEd25519PubKey::decode` built a `ChildNumber::Normal` from bytes with bit 31 clear. It now reads the child as hardened, as it did before `ChildIndex`.
The test discarded the derived path, so it passed whatever the path held. It now checks that the maximum index lands hardened in the BIP44 path and that the first index past it is rejected.
@manki-review

manki-review Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Review superseded by a later review of eb5dcab. This attempt ended as follows.

🔴 Review failed in 3m 1s

Planner (6s)
    refactor · 3912 lines · 2 agents
    judge effort: high

Review (security · full): 0 findings
    ✅ Claude Opus 5.5 · high: 4 findings (2m 4s)
    🔴 GPT 6.2 Sol · high: failed after 2 attempts (3s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 29 of 29 done, 6 findings (1m 12s)

Judge

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. labels Nov 28, 2026

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏸️ Review incomplete: GPT 6.2 Sol · high failed after retries. Manki starts one more review of this commit on its own within a few minutes. If that one does not finish either, retry with /manki review.

  • Review again
About this review

@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 28, 2026
@manki-review

manki-review Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Review superseded by a later review of eb5dcab. This attempt ended as follows.

🔴 Review failed in 4m 29s

Started automatically, since no review of this commit had finished.

Planner (8s)
    refactor · 3912 lines · 2 agents
    judge effort: high

Review (security · full): 0 findings
    ✅ Claude Opus 5.5 · high: 7 findings (2m 15s)
    🔴 GPT 6.2 Sol · high: failed after 2 attempts (7s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 28 of 28 done, 5 findings (2m 6s)

Judge

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏸️ Review incomplete: GPT 6.2 Sol · high failed after retries. Retry with /manki review.

Started automatically, since no review of this commit had finished.

  • Review again
About this review

@ZocoLini

Copy link
Copy Markdown
Collaborator Author

/manki review

@manki-review

manki-review Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Review superseded by a later review of eb5dcab. This attempt ended as follows.

🔴 Review failed in 3m 58s

Planner (7s)
    refactor · 3912 lines · 2 agents
    judge effort: high

Review (security · full): 0 findings
    ✅ Claude Opus 5.5 · high: 4 findings (2m 13s)
    🔴 GPT 6.2 Sol · high: failed after 2 attempts (7s)
    ✅ Comparisons, related checks, claim checks and pattern checks: 26 of 26 done, 7 findings (1m 55s)

Judge

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏸️ Review incomplete: GPT 6.2 Sol · high failed after retries. Retry with /manki review.

  • Review again
About this review

@manki-review

manki-review Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

✅ Review complete in 17m 35s

Started automatically, since no review of this commit had finished.

Planner (7s)
    refactor · 3912 lines · 2 agents
    judge effort: high

Review (security · full): 37 findings
    ✅ Claude Opus 5.5 · high: 7 findings (2m 13s)
    ✅ GPT 6.2 Sol · high: 24 findings (3m 31s)
    ✅ Comparisons, related checks, claim checks, pattern checks and fix checks: 27 of 27 done, 6 findings (1m 52s)

Judge (12m 21s)
    before the judge: 9 dropped as repeats of earlier resolved findings
    graded 28 findings: 11 kept · 5 dropped · 12 merged
    dropped, as the finders filed them: 1 blocker · 2 warnings · 2 suggestions
    refuter: 6 checked · 1 confirmed · 2 disproved · 3 unsettled
    origin checks: 7 checked · 4 older than this PR
    sweeps: 1 of 1 done (34s)
    verdict reader: read the diff (44s)

Posted: 1 finding
    1 warning
    not posted: 5 older than this PR · 4 on code an earlier round reviewed · 1 rare trigger

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner, security-sensitive paths)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 93% (resets 2026-12-02 17:00 UTC)
  • ChatGPT subscription: weekly 8% (resets 2026-12-02 01:49 UTC)

Judge decisions:

  • Not listed, on code an earlier round reviewed: "Public ChildIndex::new_const panics on caller input, against the crate's no-panic rule" (suggestion): "note. new_const at key-wallet/src/bip32.rs:561-562 is a public const fn whose assert! panics at runtime for an index of 2^31 or more. That breaks the key-wallet rule that library code never panics. The doc comment shows the panic is a deliberate choice. Every runtime call in the library passes a bounded value: the coin type 5 or 1 at account_type.rs:375, and a bool or enum at the dip9 sites. So no current path crashes, and the finding is a design question about a panicking public constructor."
  • Kept: "dashpay/platform stops compiling on upgrade: it passes u32 to ManagedPlatformAccount::new and the account-collection maps" (warning): "warning. A change that breaks a consumer, and the PR lists it as breaking. ManagedPlatformAccount::new now takes ChildIndex (key-wallet/src/managed_account/managed_platform_account.rs:59), and the account maps are keyed by ChildIndex (managed_account_collection.rs:44). The fetched dashpay/platform checkout calls ManagedPlatformAccount::new(0, 0, pool, false) at rs-platform-wallet/src/wallet/apply.rs:716, ManagedPlatformAccount::new(ACCOUNT, 0, ...) at withdrawal.rs:1439 and ManagedPlatformAccount::new(1, 0, ...) at balance_history.rs:1769. None of these compile against the new signature. The persistence.rs:6273 lookup still compiles, because its index comes from AccountType.", trigger 7 and harm 3 of 10: "The downstream consumer fails to compile as soon as it bumps the dependency, which is certain on upgrade."
  • Not listed, on code an earlier round reviewed: "Changed lines keep a fully qualified crate::bip32::ChildNumber path instead of importing it" (suggestion): "note. The PR rewrites key-wallet/src/managed_account/managed_account_type.rs:525 and :535 as crate::bip32::ChildNumber::Normal(..). That is a multi-segment path, which the root AGENTS.md import rule forbids. The module already imports from crate at line 9."
  • Not listed, its trigger is rated below review.min_warning_trigger: "Previously writable accounts can no longer be restored" (warning): "warning. The cell is unchanged from the earlier rounds. The base API let callers store any u32. ChildNumber::Normal { index: u32 } was publicly constructible, as the removed lines in bip32.rs show, and Account::from_xpub (key-wallet/src/account/mod.rs:101-113) stores the AccountType index unchecked. The new ChildIndex decoders at bip32.rs:589 and :598 reject such a value. Wallet::restore (backup.rs:51) then fails for the whole backup, which breaks the rule that existing persisted data must stay decodable. The trigger needs an index at or above 2^31, which normal derivation never produces, so it is marked rare.
    Refutation unsettled: On the head, the ChildIndex decoder rejects any stored u32 with the high bit set (bip32.rs:598). On the base, Wallet::add_account with a supplied xpub went through Account::new and from_xpub and stored the AccountType index without a check. So a stored index of 2^31 or more is possible. But I found no caller, test or documented use that actually supplies such an index, so I could not show this happens in normal use. Rule checked: A bincode decoder that adds a range check rejects stored bytes that the old unchecked decoder accepted, so data written with out-of-range values stops decoding.
  • Premise "This trigger happens in realistic use: when a wallet that stored an account or child index of 2^31 or more is restored from a backup after the upgrade" unsettled. The base public library API add_account(account_type, Some(xpub)) stored any u32 index with no derivation check, so such a backup can exist. Normal wallet creation derives keys and never produces an index of 2^31 or more, and the consumer path I read (platform persistence account_type_from_spec) only passes indexes the wallet had already stored. I found no caller supplying such a value, but I did not search every caller, so I cannot rule it out either way.
    Pair refutation unsettled: The base import path could store and back up a caller-supplied account index without deriving its key. The new decoder rejects indexes at or above 2^31 and returns an error for the entire restore, but I found no legacy backup or import example that supplies such an index. Rule checked: A decoder that narrows a persisted integer field can reject backups written by the old encoder even when the wire format is unchanged.
  • Premise "This trigger happens in realistic use: when a wallet that stored an account or child index of 2^31 or more is restored from a backup after the upgrade" unsettled. The documented import path accepts prebuilt accounts, but the watch-only test uses index zero and the high-bit test decodes a standalone integer, not a legacy wallet backup.", trigger 2 and harm 6 of 10: "It requires stored backups with an account or child index of at least 2^31, which the old constructors mostly rejected, so this is rare."
  • Not listed, on code this PR did not change: "Identity top-up private derivation appends the registration index twice" (warning): "warning, with the cell unchanged from round 1. AccountType::derivation_path already ends in Hardened(registration_index) (key-wallet/src/account/account_type.rs:436). The PR rewrote has_intermediate_derivation to return the same Hardened(registration_index) (account/mod.rs:177, bls_account.rs:300, eddsa_account.rs:271). key-wallet/src/account/derivation.rs:162-168 derives the account key, then prepends that step again. The final path is .../reg'/reg'/leaf instead of the DIP-9 .../reg'/leaf. The inter-round diff does not touch this code. Whether a signing path uses this helper is open.
    Refutation unsettled: For IdentityTopUp, derive_xpriv_from_master_xpriv derives the full account path, which already ends in Hardened(registration_index) (account_type.rs:436). derive_from_master_xpriv_extended_xpriv_at then puts the same step from has_intermediate_derivation in front of the leaf (derivation.rs:162-168). The public helper therefore returns the key at .../reg'/reg'/i, not at the DIP-9 path .../reg'/i. Rule checked: In BIP32, deriving a hardened child from a key that already ends in that same hardened step gives a different key, so .../reg'/reg'/i and .../reg'/i give different private keys.
  • Premise "A key-wallet signing or key-lookup path derives an IdentityTopUp account's leaf private key through derive_from_master_xpriv, so the key it returns does not control the address the account xpub derives at the same leaf" disproved. None of key-wallet's signing paths call this helper; they derive keys by running derive_priv on the full stored path from the root. Outside the account module, the only callers in this repo are tests for provider accounts, and the platform consumer calls it only for provider keys. dash-evo-tool never calls it. So no signing or key-lookup path derives an IdentityTopUp key this way.
    Pair refutation confirmed: The top-up account path already ends in the hardened registration index. The public private-key lookup appends that index again before the leaf, while identity_top_up_path includes it only once. Rule checked: HD derivation applies each path component in order, so repeating a hardened component derives from a different parent key.
  • Premise "A key-wallet signing or key-lookup path derives an IdentityTopUp account's leaf private key through derive_from_master_xpriv, so the key it returns does not control the address the account xpub derives at the same leaf" confirmed. The public ECDSA private-key lookup calls the faulty master-to-leaf helper directly; the built-in asset-lock builder instead derives from the stored address path and bypasses it."
  • Dropped: "Small 256-bit child indexes derive a different key from DIP-14 compatibility mode" (ignore): "ignore. The PR only rewrote the match patterns at bip32.rs:1266-1273. The HMAC input still follows the variant, as it did before. The reference dashpay/dash:src/wallet/platformkeys.cpp:105 also chooses the width by variant, not by value, so the Rust code matches the reference wallet. Changing it would move existing DashPay keys."
  • Dropped: "Account paths reimplement the existing BIP44 and CoinJoin builders" (ignore): "ignore. The hand-built prefixes in AccountType::derivation_path were already there before the PR. The PR only swaps the fallible constructors for ChildIndex, so it adds no near copy and the reuse rule is not broken. What remains is an optional refactor on code this PR did not introduce."
  • Not listed, on code an earlier round reviewed: "New imports are placed inside a method and a test" (suggestion): "note. The added line key-wallet/src/bip32.rs:588 puts use serde::de::Error as _; inside deserialize. key-wallet/src/tests/account_tests.rs:538 puts use crate::bip32::{ChildIndex, ChildNumber}; inside a test function. Both break the root AGENTS.md rule against a use inside a function."
  • Dropped: "Derivation work is unbounded before child-index validation can stop it" (ignore): "ignore. The PR changes only the per-index constructor at derivation.rs:62 and :82. The with_capacity, the range arithmetic, the scan loop and generate_addresses are unchanged. An earlier round already settled the same problem with the author, and nothing in this code changed since."
  • Not listed, on code this PR did not change: "Hardened address pools record a path that cannot reproduce their keys" (warning): "warning, with the cell unchanged from round 1. The rewritten key-wallet/src/managed_account/address_pool.rs:444 always appends ChildNumber::Normal to full_path. Lines 462-464 derive the key with ChildNumber::Hardened for AbsentHardened, and line 515 saves the mismatched path. Ed25519 rejects the normal step (derivation_slip10.rs:125), and ECDSA would derive a different key. The inter-round diff leaves this file alone. Whether anything derives from the stored path is open.
    Refutation unsettled: address_pool.rs:444 records a normal leaf while lines 462-468 derive a hardened one for AbsentHardened, so the stored path is wrong (the base code already did this). But no code found in key-wallet, dashpay/platform or dash-evo-tool derives or signs from AddressInfo.path for the ProviderPlatformKeys pool: the platform node private key comes from its own hardened path. Whether persisted paths are re-derived through dashpay/platform's FFI was not traced, so no observable failure is shown. Rule checked: A BIP32/SLIP-10 path re-derives a key only if each step's hardened flag matches the one used at derivation, and a wrong recorded path only harms someone who derives or signs from it.
  • Premise "Code in key-wallet or a consumer derives or signs with the key at AddressInfo.path for an AbsentHardened pool, such as the provider platform node key pool" unsettled. Inside key-wallet, the only derivations from info.path are next_private_key and peek_next_path, called from asset_lock_builder (not opened, so which accounts they serve was not checked), and address_derivation_path, used to sign spends of UTXOs. The platform node key is derived by platform_node_key_at from its own hardened path. A search of dashpay/platform and dash-evo-tool found no call to next_eddsa_platform_key, but whether dashpay/platform re-derives keys from persisted address paths was no...
    Pair refutation unsettled: The Platform node key pool derives a hardened child but returns an AddressInfo whose path ends in a normal child. The returned path is already wrong, even though no signing caller was shown to use it. Rule checked: A derivation path must preserve whether each child is hardened; SLIP-10 rejects normal children for Ed25519.
  • Premise "Code in key-wallet or a consumer derives or signs with the key at AddressInfo.path for an AbsentHardened pool, such as the provider platform node key pool" unsettled. The generic next_private_key method reads AddressInfo.path, but no call using it on an AbsentHardened pool was verified; the Platform consumer derives node keys from the seed and index instead."
  • Dropped: "The identity registration helper derives a different funding key from DIP-13 and Dash Core" (ignore): "ignore. The PR keeps the same hardened leaf at dip9.rs:547 that from_hardened_idx gave before. The crate deliberately ships both a hardened and a non-hardened registration helper (line 538). key-wallet/AGENTS.md forbids changing an existing path. The comment the finding objects to sits in lines not shown, so the rest is a doc point that cannot be checked here."
  • Dropped: "The depth-limit tests set the key state by hand" (ignore): "ignore. The PR only changes the ChildNumber constructor at derivation_slip10.rs:852. The sk.depth = 254 line was already in the test, so the PR does not add the hand-set state the rule forbids. The test still fails if the depth cap breaks."
  • Not listed, on code this PR did not change: "Transaction amount totals can overflow before coin selection" (warning): "warning, pre-existing. The PR only edits test account lookups in transaction_builder.rs. prepare sums caller output values with unchecked sum() at lines 569 and 571, and adds the fee unchecked at line 622. In a release build a wrapped total lets coin selection pass and build a transaction whose outputs exceed its inputs. In a debug build it panics. The trigger needs output values whose sum exceeds u64::MAX, which no valid Dash amount reaches, so it is marked rare."
  • Not listed, on code this PR did not change: "Wallet scanning misses credit outputs for identity-bound top-ups" (warning): "warning, pre-existing. The PR only changes the map key type at account_checker.rs:588. IdentityTopUp is routed to check_indexed_keys_accounts (line 497). That calls check_transaction_for_match (line 593), which scans only tx.output (line 1165). Registration, not-bound top-up and invitation accounts use the credit-output matcher instead (lines 490-510). The test at special_transaction_matching_tests.rs:180-184 hides this by putting the address in a regular output.
    Refutation confirmed: check_account_type sends IdentityTopUp to check_indexed_keys_accounts, which calls check_transaction_for_match. That function scans only provider payouts and tx.output. No code path runs check_asset_lock_transaction_for_match on identity_topup accounts. Real top-up asset locks put the top-up key's P2PKH only in credit_outputs, so the IdentityTopUp account never matches and its addresses are never marked used by the scan. Rule checked: In a Dash asset-lock transaction, the credit outputs sit in the special-transaction payload (payload.credit_outputs). tx.output holds only the OP_RETURN burn and any change, so a matcher that scans only tx.output can never see a key that is paid only in the credit outputs.
  • Premise "No path in check_account_type or the wallet checker runs check_asset_lock_transaction_for_match on the identity_topup accounts" confirmed. Every call to check_asset_lock_transaction_for_match in key-wallet is in the registration, not-bound, invitation, address top-up and shielded top-up arms. The IdentityTopUp arm uses check_indexed_keys_accounts, which calls only check_transaction_for_match.
  • Premise "An asset lock that pays an identity-bound top-up key only in credit_outputs is not recorded against the IdentityTopUp account" confirmed. The keys-account matcher looks only at provider payout scripts and tx.output, and returns None when neither involves the account. A key paid only in payload.credit_outputs therefore produces no IdentityTopUp match, and nothing in affected_accounts marks it used.
    Pair refutation confirmed: The wallet routes identity-bound top-ups to the regular-output matcher even though the credit-output matcher already supports them. The existing test puts the owned script in a regular output, and the PR's index-type change leaves the pre-existing dispatch unchanged. Rule checked: An AssetLock stores its credit outputs separately from its regular outputs, so scanning only regular outputs cannot find a key that appears only in the credit payload.
  • Premise "No path in check_account_type or the wallet checker runs check_asset_lock_transaction_for_match on the identity_topup accounts" confirmed. The wallet delegates to the collection checker, and the IdentityTopUp branch calls only the indexed regular-output matcher; the credit-output calls target other accounts.
  • Premise "An asset lock that pays an identity-bound top-up key only in credit_outputs is not recorded against the IdentityTopUp account" confirmed. For an AssetLock whose owned top-up script appears only in the payload, the matcher returns no IdentityTopUp match and the wallet's recording loop never visits that account."
  • Not listed, on code this PR did not change: "Matching a nonzero account can return an account-zero result" (warning): "warning. The rewritten lines key-wallet/src/transaction_checking/account_checker.rs:784, 791, 800, 816, 862, 868, 928, 1190 and 1279 fall back to ChildIndex::ZERO when index is None, instead of reading the account's own index. wallet_checker.rs:95 calls check_transaction_for_match(&record.transaction, None). Whether that caller uses the reported index is not shown.
    Refutation disproved: The only caller passing None to the funds matcher is wallet_checker.rs:95. It uses the match only for output_role_lookup, which reads the involved receive and change addresses and never account_index. The other None callers check registration, unbound top-up, invitation and asset-lock top-up accounts, whose matches carry no index, while every indexed map is walked with Some(*index). The base already fell back the same way with unwrap_or(0), and ChildIndex's derived Default is 0, ... Rule checked: A fallback index matters only if some code reads the reported account_index. Every caller in the repository that passes None either ignores the index or checks an account type whose match carries no index.
  • Premise "The caller at key-wallet/src/transaction_checking/wallet_checker.rs:95, which passes None, uses the returned account_index to look up or attribute an account" disproved. The caller at wallet_checker.rs:95 turns the match into output_role_lookup, which builds sets of involved receive and change addresses only, and never reads account_index to look up or attribute an account.
  • Premise "That lookup then attributes a transaction of a non-zero account to account zero or to no account" disproved. No in-repo path feeds a None-derived index into an account lookup. Indexed accounts are always matched with Some(*index), and the None caller only maps addresses to roles on the record it already holds (funds).
    Pair refutation unsettled: The public matcher recognizes a payment using the account’s own address pool but returns index 0 when the caller passes None. The cited wallet caller does not misattribute the transaction: it uses the match only to classify outputs. Rule checked: In Rust, Option::unwrap_or_default() on None returns the type’s default value, not a value inferred from the object being matched.
  • Premise "The caller at key-wallet/src/transaction_checking/wallet_checker.rs:95, which passes None, uses the returned account_index to look up or attribute an account" disproved. The caller at line 95 uses the match only to build an address-to-output-role lookup, which never reads the account index.
  • Premise "That lookup then attributes a transaction of a non-zero account to account zero or to no account" unsettled. That caller updates the spender record by transaction ID within the funds account it is already visiting; it never looks up account 0 or loses the selected account."
  • Not listed, on code an earlier round reviewed: "First Platform payment account lookup only checks account zero" (suggestion): "note. The doc at key-wallet/src/wallet/managed_wallet_info/helpers.rs:628 promises the lowest account index. The code at lines 630 and 639 looks up account 0 only. The same file's first_bip44_managed_account and first_coinjoin_managed_account also mean index 0, so the code follows the crate's pattern and the doc comment misstates it."

Timing:

  • Parse: 9.5s
  • Review agents: 304.1s
  • Judge: 741.3s
  • Total: 1055.0s

Last reviewed eb5dcab · head eb5dcab · up to date

  • Pause automatic reviews
  • Review again
  • Deeper review

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ 1 warning to address. Fix it, reply in its thread with a reason Manki accepts, or tick Create an issue for this to track it for later. Manki approves once every warning is handled.

Caution

Claude subscription has used 93% of its weekly limit, past the 90% mark. It resets 2026-12-02 17:00 UTC.

Once a limit is used up, reviews on that account stop until it resets.

Started automatically, since no review of this commit had finished.


Earlier warnings, not fixed · 3 warnings

An earlier round listed these, and this round did not find them fixed, so they stay listed. None of them blocks.

  • key-wallet/src/wallet/backup.rs:51: Unbounded bincode decoding may allocate from an untrusted length (round 2)
  • key-wallet/src/account/derivation.rs:165: Bound identity top-up private keys derive the registration index twice (round 1)
  • key-wallet/src/managed_account/address_pool.rs:444: Generated hardened addresses report a non-hardened derivation path (round 1)

📌 4 follow-ups agreed for later

Agreed in their threads as later work. None of them blocks.

  • key-wallet/src/bip32.rs:614: Removed ChildNumber constructors and struct variants break dashpay/platform and dash-evo-tool on upgrade (view thread)
  • key-wallet/src/wallet/helper.rs:16: Account index parameters change from u32 to ChildIndex, so both consumer repos stop compiling on upgrade (view thread)
  • key-wallet/src/derivation.rs:58: Public address derivation accepts unbounded amounts of work (view thread)
  • key-wallet/src/bip32.rs:736: Serializing a 256-bit child number as a scalar loses its index and hardening (view thread)

Checked and left out: 1 finding

Rare trigger, so not listed · 1 warning

The progress comment has the full log under "Judge decisions", in its "Review metadata" fold.

About this review
  • Reviewed eb5dcab, round 3
  • 3912 changed lines read in 17m 35s
  • Found by claude-opus-5-5 and gpt-6.2-sol, judged by claude-opus-5-5
  • Tokens: 17.9M in (14.6M from cache) · 183k out · about $18.23 at API prices
  • Runner: self-hosted · started after 12s · peak memory 6.8 GiB of 30.0 GiB
  • How Manki reviews

@ZocoLini

ZocoLini commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

/self-reviewed

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Ready for review — dash-spv: QuantumExplorer or xdustinface · key-wallet-manager: QuantumExplorer or xdustinface · key-wallet: QuantumExplorer or xdustinface.
Full checklist in the description.

@github-actions github-actions Bot added ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human. and removed waiting-self-review Waiting for the author to post /self-reviewed labels Dec 1, 2026

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved. All blocking threads are resolved, and no warning thread holds the approval.

What this does: BIP-32 child indexes and account indexes were plain u32 values. Every derivation call checked them at runtime and could fail.

What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Build key-wallet and run its tests with and without --all-features. Build key-wallet with --all-features so the BLS and Ed25519 code paths compile. Use a wallet created with WalletAccountCreationOptions::Default and one restored from a known mnemonic, built with --all-features.

  1. Run cargo test -p key-wallet --lib bip32. Expect the bip32 tests to compile and pass without extra features.
  2. Create a wallet and derive BIP44 account 0 receive addresses. Expect the same addresses as before the change for the same mnemonic.
  3. Back up a wallet created before this change and restore it. Expect it to decode and list the same accounts.
  4. Parse the path m/44'/5'/0'/0/1. Expect it to format back to the same string.
  5. Parse the path m/2147483648. Expect InvalidChildNumber(2147483648).
  6. Decode a bincode or serde ChildIndex holding 2147483648. Expect an error.
  7. Call ChildIndex::new(0x8000_0000). Expect Err(InvalidChildNumber).
  8. Do derive AccountType::Standard { index: ChildIndex::new_const(0x7FFFFFFF), .. }.derivation_path(Network::Testnet). Expect m/44'/1'/2147483647'.

@xdustinface
xdustinface merged commit 66aa44a into dev Dec 3, 2026
70 of 76 checks passed
@xdustinface
xdustinface deleted the refactor/child-index branch December 3, 2026 08:14
manki-review Bot added a commit to manki-review/review-memory that referenced this pull request Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Bots have reported, the author has self-reviewed, and the build is green: this needs a human.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants