Skip to content

refactor(platform-wallet-storage): drop the unreachable rehydration gap-refill guard - #5981

Draft
Claudius-Maginificent wants to merge 1 commit into
refactor/platform-node-pool-single-ownerfrom
chore/storage-drop-unreachable-refill-guard
Draft

Claudius-Maginificent wants to merge 1 commit into
refactor/platform-node-pool-single-ownerfrom
chore/storage-drop-unreachable-refill-guard

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: Remove about 250 lines of wallet-loading code, and the tests that existed only to reach it, that can no longer run since the rust-dashcore update in #5951. Loading a wallet behaves the same.

Detailed discussion

Internal cleanup with no user-observable effect, so there is no user story or scenario. Stacked on #5951 (rust-dashcore 399f47f9): the code becomes unreachable only with key-wallet's AddressPool invariants from rust-dashcore#1377. Merge after #5951.

Why the code is unreachable

At rust-dashcore 399f47f9, key-wallet clamps gap_limit to 1..=MAX_GAP_LIMIT (1000) in every constructor and setter, and AddressPool::insert refuses gaps and hardened indices. Every pool that SQLite rehydration touches comes from ManagedWalletInfo::from_wallet, so:

  • a gap refill derives at most 1000 addresses, far below the 250 000 cap, and cannot overflow;
  • a refill target past the last normal index becomes key-wallet's own Err(Bip32), reported at the same load site.

The removed tests reached the cap only because cfg(test) lowered it to 500, below MAX_GAP_LIMIT.

Changes (platform-wallet-storage)

  • Gap-refill cap removed: ImpliedRefill, gap_refills_bounded, RefusedRefills, the refusal block in extend_pools_for_restored_addresses, MAX_REHYDRATION_GAP_REFILL, MAX_NORMAL_CHILD_INDEX, LoadSite::RehydrationGapLimit, and WalletStorageError::{RehydrationGapLimitRefillTooLarge, RehydrationGapLimitTargetOutOfRange}.
  • Keyless held-coin placement removed (place_held_coins). Its only remaining callers were the restore_utxos error arms. restore_failed still reports the failure (Strict fails the load, Recovery counts it). It then returns only the coins no funds or DashPay-contact account holds, so the existing fallback places each coin once.
  • Documented precondition on the public apply_persisted_core_state: pools must come from a key-wallet constructor, never from a serde/bincode decode. Decoding skips the gap_limit clamp and index checks, and maintain_gap_limit uses unchecked arithmetic.
  • Tests: tests that only exercised the removed code are deleted. Boundary tests are adapted to real contracts (a pool at MAX_GAP_LIMIT refills its whole window under Strict). New tests pin a failed restore with a contact-held coin and a refill target past the last normal index in both policies.

Behaviour on the one input that changes

A pool whose used index is 2^31 − 1, so its refill target is hardened. In production this needs about 2^31 addresses derived first, roughly 1 TB in memory, before and after this PR. The tests build it through serde, which adds a serde_json dev-dependency.

  • Strict: the load still fails; the error is now RehydrationGapLimitFailed { source: Bip32 } instead of RehydrationGapLimitTargetOutOfRange.
  • Recovery: the load still continues and the wallet total is exact. A coin with no stored owner whose holding pool failed to restore goes to the fallback account (account 0) instead of the account holding its script. When the pool extension and the UTXO restore both hit that pool, the failure is counted twice instead of once.

Breaking changes

Not consensus-breaking. Rust API: WalletStorageError::RehydrationGapLimitRefillTooLarge, WalletStorageError::RehydrationGapLimitTargetOutOfRange and LoadSite::RehydrationGapLimit are removed. platform-wallet-storage is published in the v4.2.0-beta tags, so this is a source break for outside code that names them; none was found in this workspace or in dash-evo-tool.

Follow-ups (not in this PR)

Testing

At fe60560e1b:

Checklist

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • I have added or updated relevant unit/integration/functional/e2e tests

🤖 Generated with Claude Code

https://claude.ai/code/session_01WunYYijwZNbw3EjHtdMAHC

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • 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

@thepastaclaw

thepastaclaw commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit 26afd1a. Normal review starts when eligible; priority review starts as soon as a slot is available.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

The production SQLite path constructs pools through validated key-wallet constructors, but the public rehydration API still accepts caller-supplied decoded pools. Removing the preflight therefore allows malformed pool metadata to reach unchecked key-wallet arithmetic, causing a debug panic or potentially unbounded derivation before Strict or Recovery can handle the error. Removing the keyless fallback also misattributes coins held by a contact or CoinJoin pool when a refill fails, making the wallet total appear exact while the coin is placed in an account that cannot spend it.

🔴 2 blocking | 🟡 1 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🟡 Suggestion: Mark the released Rust API removals as a breaking change
packages/rs-platform-wallet-storage/src/sqlite/error.rs:590-600

This diff removes public WalletStorageError variants and the public LoadSite::RehydrationGapLimit variant that are present in the v4.2.0-beta.7 tag. The PR title is currently refactor(platform-wallet-storage): ..., while .github/PULL_REQUEST_TEMPLATE.md requires ! in the title when the code introduces breaking changes. Mark the title as a breaking change and carry the migration note into the release metadata so downstream exhaustive matches and diagnostic consumers are warned.

source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, platform-versioning, rust-quality, security-auditor)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 11: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The diff changes wallet rehydration error handling and fallback account placement in rehydrate.rs, which warrants more than a cursory review but does not change funds movement, coin selection, or the storage schema.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet-storage/src/sqlite/rehydrate.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/rehydrate.rs:288-296: Enforce the pool invariant at the public rehydration boundary
  The documented constructor-only precondition is not enforced: `sqlite::rehydrate::apply_persisted_core_state` is public and accepts any `&mut ManagedWalletInfo`, including a value decoded through key-wallet serde or bincode. At the pinned key-wallet revision, `AddressPool::maintain_gap_limit` computes `gap_limit - 1` or `highest_used + gap_limit` with unchecked arithmetic. A decoded pool with `gap_limit == 0` can panic in debug or request an enormous refill in release, while a pool at the last normal child index overflows before `LoadCtx` can route the failure through the typed `RehydrationGapLimitFailed` path. The new boundary test deliberately constructs such a pool through serde, so this is an exercised API path rather than only theoretical input. Keep a checked public entry point, or restrict the unchecked implementation to a validated input type/private caller-controlled path until key-wallet validates decoded pools.
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/rehydrate.rs:798-806: Preserve script-based ownership after a failed refill
  `restore_failed` now decides whether a UTXO was held solely by checking account UTXO maps. However, pinned key-wallet documents that `restore_utxos` extends every pool before inserting any UTXO, so a refill error leaves the maps unchanged even when a contact or CoinJoin pool already contains the coin's script. The coin is therefore returned as unheld and the fallback at lines 489-492 places an ownerless coin in the first funds account, typically BIP44, instead of the account whose pool can resolve it. That account may not have the signing key, and a later rescan can credit a second copy to the actual holding account. Preserve the previous no-refill, script-based placement for restore errors, or use an upstream restore API that reports pool ownership without attempting another refill.

In `packages/rs-platform-wallet-storage/src/sqlite/error.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/error.rs:590-600: Mark the released Rust API removals as a breaking change
  This diff removes public `WalletStorageError` variants and the public `LoadSite::RehydrationGapLimit` variant that are present in the v4.2.0-beta.7 tag. The PR title is currently `refactor(platform-wallet-storage): ...`, while `.github/PULL_REQUEST_TEMPLATE.md` requires `!` in the title when the code introduces breaking changes. Mark the title as a breaking change and carry the migration note into the release metadata so downstream exhaustive matches and diagnostic consumers are warned.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Share core-state rehydration orchestration across persisters — The SQLite storage layer still owns wallet-specific restore orchestration while the FFI persister has a separate route, allowing future failure and fallback semantics to drift. This predates the reviewed range and is not required to resolve the two regressions above.
    • Follow-up: Track a follow-up PR in platform-wallet that owns the shared restore algorithm and has SQLite and FFI persistence adapters call it.

Comment on lines +288 to +296
/// # Precondition
///
/// `wallet_info` must be built by a key-wallet constructor such as
/// `ManagedWalletInfo::from_wallet`, never decoded with serde or bincode.
/// The constructors clamp each pool's gap limit to `1..=MAX_GAP_LIMIT` and
/// keep its indices contiguous and non-hardened, which bounds every gap
/// refill to one window; a decoded pool skips those checks, and key-wallet's
/// `maintain_gap_limit` computes its target with unchecked arithmetic (a gap
/// limit of 0 panics in debug and derives up to `2^31` addresses in release).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Enforce the pool invariant at the public rehydration boundary

The documented constructor-only precondition is not enforced: sqlite::rehydrate::apply_persisted_core_state is public and accepts any &mut ManagedWalletInfo, including a value decoded through key-wallet serde or bincode. At the pinned key-wallet revision, AddressPool::maintain_gap_limit computes gap_limit - 1 or highest_used + gap_limit with unchecked arithmetic. A decoded pool with gap_limit == 0 can panic in debug or request an enormous refill in release, while a pool at the last normal child index overflows before LoadCtx can route the failure through the typed RehydrationGapLimitFailed path. The new boundary test deliberately constructs such a pool through serde, so this is an exercised API path rather than only theoretical input. Keep a checked public entry point, or restrict the unchecked implementation to a validated input type/private caller-controlled path until key-wallet validates decoded pools.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-sol (phase2-reviewer: general, architecture-layering, platform-versioning, rust-quality, security-auditor)

Comment on lines +798 to +806
let accounts = &wallet_info.accounts;
let holders: Vec<_> = (accounts.all_funding_accounts().into_iter())
.chain(accounts.dashpay_external_accounts.values())
.collect();
let unheld = (unspent.iter())
.filter(|u| !holders.iter().any(|a| a.utxos.contains_key(&u.outpoint)))
.map(|u| (*u).clone())
.collect();
Ok((unheld, false))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Preserve script-based ownership after a failed refill

restore_failed now decides whether a UTXO was held solely by checking account UTXO maps. However, pinned key-wallet documents that restore_utxos extends every pool before inserting any UTXO, so a refill error leaves the maps unchanged even when a contact or CoinJoin pool already contains the coin's script. The coin is therefore returned as unheld and the fallback at lines 489-492 places an ownerless coin in the first funds account, typically BIP44, instead of the account whose pool can resolve it. That account may not have the signing key, and a later rescan can credit a second copy to the actual holding account. Preserve the previous no-refill, script-based placement for restore errors, or use an upstream restore API that reports pool ownership without attempting another refill.

source: gpt-6.2-sol (phase2-reviewer: general, architecture-layering, platform-versioning, rust-quality, security-auditor)

@lklimek
lklimek changed the base branch from chore/rust-dashcore-dev to refactor/platform-node-pool-single-owner November 24, 2026 11:38
@lklimek
lklimek added this pull request to stack #6217 November 24, 2026 11:38
@lklimek
lklimek force-pushed the chore/storage-drop-unreachable-refill-guard branch 3 times, most recently from f6f896d to 1569a3b Compare November 27, 2026 14:11
…ap-refill guard

Preserve the final PR scope, including merge resolutions, on the updated native stack.

Co-Authored-By: Codex <[email protected]>
@lklimek
lklimek force-pushed the chore/storage-drop-unreachable-refill-guard branch from 1569a3b to 26afd1a Compare December 1, 2026 08:24

This branch has not been deployed

No deployments
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.

3 participants