Skip to content

key-wallet: report funds awaiting finality from transaction builds #1185

Open

Description

@lklimek

TL;DR: A transaction build restricted to final inputs should distinguish a real funding shortfall from one that the wallet's waiting coins would cover. That diagnosis belongs in key-wallet, alongside selection and transaction assembly. Platform PR dashpay/platform#5395 currently reconstructs and retries builds above the library to obtain it, including a replayable builder in FFI and a hand-written reconstruction of asset-lock configuration.

User story

As a wallet application developer, I want a transaction build to tell me whether the requested operation lacks funds or needs existing funds to become final, so I can give the user the right reason for a refusal through the same API in Rust and mobile clients.

Scenario

Base flow

A wallet holds 400,000 duffs in final coins and 600,000 duffs in waiting coins. A payment requests 800,000 duffs, plus a fee the combined coins can cover. The caller requires final inputs: confirmed in a block or InstantSend-locked. The waiting coins are otherwise spendable, unreserved and not excluded from this build.

Actual behavior

TransactionBuilder drops the waiting inputs before selection and reports insufficient funds. The caller cannot tell from that error whether the waiting coins would fund the same transaction, including its outputs, fee rate, payload, selection strategy and input limit.

The workaround in platform#5395 builds the operation again with waiting coins treated as final in cloned accounts. Since the builder is consumed and cannot be reconstructed from its public API, the FFI layer records setter calls as a recipe. The asset-lock path separately reconstructs key-wallet's configuration for the trial.

There is also a gap for asset-lock drains: if the build succeeds over final coins but the resulting lock is below the caller's minimum, the later refusal does not run that trial, even when waiting coins would raise the lock above the minimum.

Expected behavior

The original builder returns a typed funding diagnosis when the same operation could be prepared using waiting coins. If those coins still cannot fund it, the original failure remains. A minimum-constrained drain uses the same rule, judged on its actual lock value after the fee.

No diagnostic transaction is broadcast, signed, or reserved. The result says that funding would be possible if the selected waiting coins became final; it does not promise that they will become final or that later signing will succeed.

Detailed discussion

Reviewed the rust-dashcore revision pinned by the current Platform checkout, edc4d430, and platform#5395 at dfa8251. This is a code-inspection-based implementation request; no new reproduction test or network run was performed for this issue.

In transaction_builder.rs, assemble_unsigned currently filters candidates, selects coins, assembles the transaction and reserves the selection. With require_final_inputs, it removes non-final candidates before selection. It therefore has the relevant configuration and candidates, but discards the information needed to classify the shortfall.

The asset-lock builder already enables require_final_inputs; the missing capability here is the shared diagnosis, not another finality filter. Ordinary transaction builds should retain their existing default policy unless the caller requests final inputs.

Proposed implementation

  1. Separate preparation from reservation. Extract one internal preparation path for selection, fee calculation, input-limit checks, change, drain handling, payload placeholders and output ordering. It should return the prepared unsigned transaction, selected inputs and fee without reserving them. Both the real attempt and the diagnostic attempt must use this path.

  2. Keep eligible waiting candidates until the outcome is known. Snapshot reservation exclusions for the build and retain the original candidate scope. Try final coins first. For insufficient funds, no available UTXOs or too many inputs, try the same preparation with final and otherwise eligible waiting coins. Report waiting only if that attempt succeeds and actually selects waiting coins. Do not expand a seeded-input-only build to other account coins. Locked, immature, reserved or excluded coins remain unavailable.

  3. Return a typed BuilderError diagnosis. It should identify the value of waiting inputs selected by the successful diagnostic attempt, preserve the original available/required figures where meaningful, and expose the selected outpoints for caller-side checks. TooManyInputs may have no meaningful available/required pair: a larger waiting coin can replace hundreds of small final ones. FFI code 59 remains a downstream mapping, not a key-wallet error-code assignment.

  4. Accept caller-supplied outpoint exclusions. Platform owns its in-broadcast fences and must be able to exclude those coins from both preparation attempts without cloning accounts or modifying UTXO flags. Keep lifecycle and broadcast-state management outside key-wallet. The caller still validates explicitly chosen outpoints against its current wallet state and retains its broadcast-conflict backstop.

  5. Thread an optional minimum drain value through asset-lock building. The caller supplies the minimum; key-wallet checks the built credit-output value, net of the fee, during preparation. A final-coins drain below that value must reach the waiting-coins diagnosis before reservation, signing or credit-key index consumption. If the diagnostic drain also falls short, retain a funding refusal. Do not derive Platform-specific fee policy in key-wallet. Existing asset-lock APIs can delegate to an options-based form with default constraints.

  6. Keep payload finalization single-use. PayloadFinalizer is FnOnce. Preparation and diagnosis should price the placeholder without invoking the callback; the accepted real build invokes it once and retains the existing payload-shape/size guards and owner-guarded cleanup. This deliberately defines the result as a funding diagnosis. The current Platform trial also executes payload finalization, so that semantic difference needs documentation.

  7. Make build-path fee arithmetic safe inside the library. FeeRate::calculate_fee currently multiplies unchecked. The diagnostic attempt may price more candidates than the first attempt. Fee calculations and amount-plus-fee arithmetic must return typed errors on overflow rather than relying on an FFI-side rate bound. Reuse the same checked arithmetic in both attempts.

The diagnostic attempt must not acquire or release reservations, repeat a reservation TTL sweep, consume another change address, derive credit keys, or invoke a signer. It can reuse the change address and reservation snapshot already obtained for the real attempt. Selection and the real reservation must remain atomic under the caller's existing wallet lock.

Downstream simplification

After updating the dependency, platform#5395 can map the native diagnosis and remove its FFI builder recipe, factory-based retry, cloned-account trial and hand-written asset-lock trial configuration. Current-outpoint validation, final-input policy, wallet locks, broadcast fences and host error mapping remain in platform-wallet and its adapters.

Regression coverage

  • Final coins fund the operation: normal success and exactly one real reservation.
  • Only final plus waiting coins fund it: typed waiting diagnosis; waiting value counts only selected waiting inputs.
  • All eligible coins still fall short: original failure, including the fee.
  • Different fee rates, multiple outputs, OP_RETURN and special payloads use the same preparation rules in both attempts.
  • A larger waiting coin resolves TooManyInputs; another case where it does not retains the original failure.
  • Reserved, locked, immature and caller-excluded coins cannot make the diagnosis succeed; seeded-input-only scope and duplicate-input checks are preserved.
  • Exact asset locks and drains, including CoinJoin; a drain that builds over final coins but falls below its minimum; the exact minimum boundary and one duff above it.
  • No extra reservation, change-address use, credit-key index consumption, payload-finalizer call or input signing from diagnosis; overflow returns an error.

Prior work

  • dashpay/platform#5395 — downstream final-input policy, code 59 and the trial/replay workaround this API would replace.
  • #832 — earlier non-final asset-lock funding report. The reviewed builder already has the final-input restriction; this request covers classifying the resulting refusal in the library.

Architectural context: Platform's coding conventions require FFI/mobile layers to delegate to Rust library operations, and place shared behavior in the lowest crate with the information it needs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions