Repository navigation
Description
Summary
TransactionBuilder::set_funding does not satisfy the documented contract of ManagedWalletInfo::build_asset_lock. The doc-comment at key-wallet/src/wallet/managed_wallet_info/asset_lock_builder.rs:177-178 promises:
The transaction is built first, and keys are only derived after a successful build — so no addresses are consumed if the build fails.
But the implementation does the opposite: set_funding derives a change address (with state-mutation enabled) before build_signed can determine whether the build succeeds. When the eventual build errors (e.g. NoUtxosAvailable on an empty UTXO set), the funds account has already been mutated — monitor_revision advanced by exactly 1 — and no transaction was produced. Every failed build path leaves a phantom revision bump.
User Story
As a key-wallet consumer (e.g. dashpay/platform rs-platform-wallet) that watches monitor_revision on a ManagedCoreFundsAccount as a cheap "has anything changed?" signal, I need the counter to advance only when a transaction actually mutates the account, so that:
-
Cache invalidation works as intended. Downstream layers that gate cache validity on a stable
monitor_revisionsee phantom advances on every failedbuild_asset_lock, forcing unnecessary cache flushes. The wallet does no useful work in response — nothing actually changed. -
Persistence-flush triggers stay accurate. Persisters that schedule a write whenever
monitor_revisionadvances will write unchanged state to disk after every failed build (e.g. retry after a transientNoUtxosAvailable). I/O cost, no value. -
Monitor diffs reflect reality. Operators inspecting account state across two snapshots should be able to trust that a
monitor_revisiondifference implies a real account mutation. With the bug, equal-state snapshots can show different revisions purely because someone attempted (and failed) a build in between. -
The doc-contract is honoured. See the Summary above — the doc-comment on
build_asset_lockexplicitly promises "no addresses are consumed if the build fails", but today the failure path mutates the funds account. Doc and behaviour disagree.
Current Behavior
On v0.42-dev HEAD 5297d61a, TransactionBuilder::set_funding at key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs:79-83:
pub fn set_funding(mut self, funds_acc: &mut ManagedCoreFundsAccount, acc: &Account) -> Self {
self.inputs = funds_acc.utxos.values().cloned().collect();
self.change_addr = funds_acc.next_change_address(Some(&acc.account_xpub), true).ok();
self
}The true second argument to next_change_address is add_to_state — telling the call to mutate the account. The mutation fires before build_signed runs coin selection. When the eventual coin selection errors (e.g. with NoUtxosAvailable on an empty UTXO set), the funds account is already mutated and no transaction was produced.
Inside next_change_address at key-wallet/src/managed_account/managed_core_funds_account.rs:535-560, the function unconditionally calls self.keys.bump_monitor_revision() (line 557) before returning, regardless of whether the eventual build succeeds:
pub fn next_change_address(
&mut self,
account_xpub: Option<&ExtendedPubKey>,
add_to_state: bool,
) -> Result<Address, &'static str> {
// … derive change address from internal pool …
self.keys.bump_monitor_revision(); // ← unconditional
Ok(addr)
}So the failure path advances monitor_revision by exactly 1 with no corresponding transaction.
Reproduction
Pure async unit test (no SPV harness, no network) at dashpay/platform packages/rs-platform-wallet/tests/e2e/cases/found_022_asset_lock_builder_consumes_change_index_on_failure.rs:143 (on branch feat/rs-platform-wallet-e2e, PR #3549).
The test executes:
let wallet = Wallet::new_random(Network::Testnet, WalletAccountCreationOptions::Default)
.expect("wallet creation must succeed");
let mut info = ManagedWalletInfo::from_wallet(&wallet, 0);
let revision_before = info.accounts
.standard_bip44_accounts.get(&0).unwrap().monitor_revision();
let result = info.build_asset_lock(&wallet, 0, one_credit_output(100_000), 1_000).await;
assert!(result.is_err(), "build must fail on empty UTXO set");
let revision_after = info.accounts
.standard_bip44_accounts.get(&0).unwrap().monitor_revision();
// Today (bug): revision_after == revision_before + 1
// After fix: revision_after == revision_before
assert_eq!(revision_after, revision_before);Run with:
cargo test -p platform-wallet --test e2e -- --ignored found_022_asset_lock_builder_consumes_change_index_on_failureExpected (after fix): monitor_revision is unchanged from the pre-build snapshot — the failed build leaves the funds account untouched.
Actual (today): monitor_revision advances by exactly 1 — the eager set_funding call mutated the account before build_signed could fail.
Deterministic across runs — pure unit test, ~ms execution.
Why the test snapshots monitor_revision specifically (not pool state)
Three other "obvious" assertions for this bug do NOT bite under realistic test setup:
| Candidate assertion | Why it fails to pin the bug |
|---|---|
internal_addresses.highest_used == None after failed build |
highest_used is only mutated by mark_used / mark_index_used / scan_for_usage — none on the eager-derivation path. Holds in both bug-present and bug-fixed states. |
internal_addresses.addresses.is_empty() |
WalletAccountCreationOptions::Default pre-populates the internal pool with 30 derived addresses (full gap-limit window). Pool is never empty. |
(addresses.len(), highest_generated) equality across the failed build |
AddressPool::next_unused (address_pool.rs:521-540) first scans 0..=highest_generated for an unused entry and returns it without calling generate_address_at_index. With 30 unused entries present, the eager call short-circuits without mutating the pool. |
monitor_revision is the only observable footprint of the bug from a fresh-wallet test — but it is deterministic and load-bearing for any consumer that uses the counter for change-signaling.
Root Cause
- Primary defect — placement:
TransactionBuilder::set_fundingperforms change-address derivation beforebuild_signedcan determine whether the build is feasible. The doc-contract assumes derivation runs after successful build; the call order violates that. - Secondary defect — unconditionality:
next_change_addressatmanaged_core_funds_account.rs:535-560unconditionally bumpsmonitor_revisionregardless of whether the derived address is ever used. Even ifset_fundinglearns to call this withadd_to_state=false, the function would still need to skip the bump on a peek-only path. - Combined effect: every failed
build_asset_lockadvancesmonitor_revisionby exactly 1, with no corresponding transaction or account state change.
Affected Versions
v0.42-devHEAD5297d61a(today) — confirmed via the pinning test- All prior
key-walletversions sinceTransactionBuilder::set_fundingwas introduced (search returned 0 issues / 0 PRs touchingset_funding,monitor_revision, ornext_change_address— this surface has never been addressed)
Cross-Repository Impact
In dashpay/platform (rs-platform-wallet):
| Surface | File / line | Exposure |
|---|---|---|
Any build_asset_lock caller (retry-on-transient-failure, e.g. top_up_identity_with_funding, register_identity_with_funding) |
packages/rs-platform-wallet/src/wallet/asset_lock/build.rs and downstream identity paths |
Each retry of a failed build phantom-advances monitor_revision. |
Persistence layer / changeset adapters that diff against monitor_revision |
packages/rs-platform-wallet/src/changeset/ |
Forced re-persistence after no real state change. |
e2e tests that surface the bug:
found_022_asset_lock_builder_consumes_change_index_on_failure.rs— direct pin, RED today- Indirectly, any test that builds an asset-lock and observes
monitor_revisionafterwards would expose this — but in practice the diff is small enough that other test invariants don't catch it. Found-022 is purpose-built.
Severity
MEDIUM — silent funds-account mutation when a build fails. Not data-corrupting (no UTXO state changes, no pool drift, no key leakage), but operationally noisy:
- Doc-comment contract broken; future maintainers will be misled
- Consumers using
monitor_revisionfor change-signaling see phantom bumps - Cumulative effect under failure-heavy workloads (retry loops, contention) can be significant
Notes
Per repo conventions for issue filing, no fix proposal in this body. Two options are referenced in the dashpay/platform TEST_SPEC.md Found-022 entry as implementer notes:
- Option A: defer
next_change_addressuntil afterbuild_signedsucceeds (restructure theTransactionBuilderbuild pipeline so derivation runs only on the success path). - Option B: teach
set_fundingto peek the change address (add_to_state=false) and only persist + bump if the eventual build succeeds.
Either option preserves the doc-comment contract. The choice is left to the implementer.
Activity
Claudius-Maginificent commentedon Jul 6, 2026
Confirmed still live on
dev(647fa98), and there is now acrate-level repro inside key-wallet's own test suite (previously the only
runnable pin lived in the dashpay/platform e2e suite,
found_022_asset_lock_builder_consumes_change_index_on_failure.rsfromplatform#3549).
Crate-level repro:
key-wallet/tests/asset_lock_builder_failed_build.rs, testfound_022_asset_lock_builder_consumes_change_index_on_failure(branch
repro/pr3549-rdc). No network: a freshWallet::new_random(Testnet, Default)has zero UTXOs, soManagedWalletInfo::build_asset_lockmust fail at coin selection — afterTransactionBuilder::set_fundinghas already run.Current output (RED as expected):
Defect sites on
dev(647fa98; lines moved since the issue was filed):key-wallet/src/wallet/managed_wallet_info/transaction_builder.rs:130—set_fundingeagerly callsfunds_acc.next_change_address(Some(&acc.account_xpub), true)beforebuild_signedcan run coin selection;key-wallet/src/managed_account/managed_core_funds_account.rs:601—next_change_addressunconditionally callsself.keys.bump_monitor_revision().This violates
build_asset_lock's own doc contract(
asset_lock_builder.rs:177-178): "The transaction is built first, andkeys are only derived after a successful build — so no addresses are
consumed if the build fails."
Note: #836 inserted a
.require_final_inputs()step between.set_funding(...)and.build_signed(...)inbuild_asset_lock, whichmakes the phantom
monitor_revisionbump MORE likely to actually triggerfor unconfirmed-funds-only wallets.
Why the pin is
monitor_revision: with default options the internal poolis pre-populated with a full gap-limit window, so the eager call
short-circuits to an existing unused entry —
addresses,highest_generatedandhighest_usedare unchanged in both bug-presentand bug-fixed states. The unconditional revision bump is the one
deterministic observable footprint on a fresh wallet (and it is
load-bearing for consumers using
monitor_revisionas a "did the accountchange?" signal). Snapshot-and-compare absorbs incidental setup bumps.
The test flips GREEN once
next_change_addressis deferred pastbuild_signed(orset_fundingpeeks without mutating).Happy to push the branch / open a PR with the test if useful.
🤖 Co-authored by Claudius the Magnificent AI Agent