Skip to content

wollet: cache: skip outputs spent by known txs - #203

Open
Jeon1691 wants to merge 2 commits into
Blockstream:masterfrom
Jeon1691:fix/201-spent-output-resurrection
Open

Jeon1691 wants to merge 2 commits into
Blockstream:masterfrom
Jeon1691:fix/201-spent-output-resurrection

Conversation

@Jeon1691

@Jeon1691 Jeon1691 commented Nov 16, 2026 •

Copy link
Copy Markdown

Fixes #201.

Problem

Cache::update_unspent adds the wallet outputs of every txid new to heights, and removes only the inputs of the txids in the same update. If a known transaction already spends one of those outputs, the output is added back to unspent. Wollet::utxos() then returns it, the balance counts it, and the transaction builder can select it, so the broadcast fails with bad-txns-inputs-missingorspent.

Besides the case in the issue (a transaction deleted by a scan and found again while its spending transaction stays), the same happens when a transaction is found after its spending transaction, for example through another wallet script. The second case does not involve a deletion, so a fix limited to re-added transactions would not cover it.

Change

Before adding the outputs, drop the ones spent by a known transaction (in heights, not in this update; spenders in this update are still handled by inputs_new).

A spending transaction cannot confirm before the transaction it spends, so only the known transactions at the lowest candidate height or above, and the unconfirmed ones, are read. sorted_txids is sorted by descending height with unconfirmed first, so the iteration stops at the first lower transaction:

  • a receive in the mempool or at the tip reads only the unconfirmed and tip transactions;
  • a first sync reads nothing, since every transaction is in the update;
  • only an old transaction found late or coming back reads most of the history, and only once.

A scan can read servers at different heights, so a transaction can be reported unconfirmed while its spending transaction is cached as confirmed, and the bound then skips the spender (reported by @diorwave below). Two checks cover this:

  • a transaction coming back unconfirmed after a deletion (still in the txs store, not in heights) reads all known transactions; a server reporting it as confirmed has seen its block, so the bound reads the spender;
  • when the height of a known transaction changes, its unspent outputs are checked again against the transactions at its new height or above, so an output added with an inconsistent height is removed once a scan reports the right height. This also covers a transaction seen for the first time, and the case of a deleted transaction applied again as unconfirmed with Wollet::apply_transaction while its spending transaction is cached as confirmed.

An update that neither adds a wallet output nor changes the height of a transaction with unspent outputs reads nothing, so updates still do not read every stored transaction. The utxo_only and v5 snapshot paths are unchanged. height_sort_key replaces the unwrap_or(u32::MAX) in rebuild_sorted_txids, so both use the same ordering.

A transaction seen for the first time with an inconsistent height still shows its spent output until a scan reports its height.

Tests

test_output_spent_by_known_tx_is_not_unspent is one table-driven test in cache.rs:

Case Before After
re-added tx, confirmed spending tx (the issue) unspent spent
re-added tx, unconfirmed spending tx unspent spent
tx found after its spending tx unspent spent
tx found after its spending tx, same block unspent spent
re-added tx reported unconfirmed, spending tx confirmed unspent spent
same, another wallet tx confirmed in a later block unspent spent
tx seen first unconfirmed after its confirmed spending tx, then confirmed unspent spent
re-added tx, no spending tx unspent unspent

The same-block row fails if the bound is changed from >= to >. The three rows with an unconfirmed transaction fail without, in order, the full read for an unconfirmed re-added transaction, the full read instead of also reading only the highest cached block, and the check on height change. The last row checks that a re-added output with no spending transaction is still added.

  • cargo test -p lwk_wollet --lib: 141 passed.
  • cargo clippy -p lwk_wollet --all-targets -- -D warnings, cargo fmt --check: clean.
  • cargo test -p lwk_wollet --test e2e, on aarch64-linux (an OrbStack NixOS VM, since nix develop does not evaluate on aarch64-darwin): 131 passed, 19 ignored, 7 failed.
    • Executables: elementsd 23.3.3 and bitcoind from the pinned nixpkgs (1c3fe55), Liquid electrs built from the pinned e60ca890 (the flake build fails on aarch64-linux because the elementsd crate's build script does not support it), waterfalls built from the pinned b2b31351, and Docker for the Jade and Ledger emulators.
    • 5 failures are missing executables: AMP2_MOCK_EXEC (amp2::test_amp2_flow, amp2::test_elip153_flow, test_jade::emul_elip153_flow), LIGHTNINGD_EXEC, ASSET_REGISTRY_EXEC.
    • registry::test_registry_v2 times out against the emulated registry container, also on master.
    • ct_discount failed while starting the test environment (test_env.rs:390, the electrs header subscription returned an empty reply) and passes 3/3 alone.
    • In earlier runs, jade_sign_wollet_pset failed to pull its image and test_zmq_endpoint was flaky in this VM on both branches; both passed in this run.

Notes

  • With a persisted transaction store, restore takes the stored v5 unspent snapshot as is. A wallet that already has a resurrected output keeps it until it is scanned again from an empty store; the CHANGELOG entry says so. A one-time check on restore could repair it, but it would read the transactions that the snapshot avoids reading, so I left it out. Happy to add it if you prefer.
  • On the open question in the issue, one possible cause is servers at different heights: Esplora fetches the mempool and the chain history of each address separately, so a scan can miss a transaction that has just left the mempool. I have not reproduced it against a live server. The second case above does not need it.
  • While testing this I found two related bugs that this PR does not change, and reported them separately: Cache unspent restores an input of a deleted transaction that a known replacement still spends #204 (inputs of a deleted transaction restored although a replacement spends them) and Applying a merged update with a txid in both txid_height_new and txid_height_delete drops its outputs from unspent #205 (a merged update with a txid both added and deleted drops its outputs).

@diorwave

Copy link
Copy Markdown

Tested this with a randomized model of scans that compares unspent with the set derived from heights (owned outputs minus inputs of known txs), including txs missing from one scan and coming back as in #201. Master fails on every seed, this PR on none.

One case is still open. If the scan that brings a tx back started before the block confirming it and its spender, the tx comes back unconfirmed while the spender is cached as confirmed. spent_by_known_txs then reads only the unconfirmed txs and the output is added back. It stays unspent after the next scan reports the right height, since that is a height-only change. It is the inconsistent heights case from the description, but a normal scan can reach it, not only apply_transaction.

As a row of test_output_spent_by_known_tx_is_not_unspent it fails on this branch:

(
    // The scan bringing A back started before the block confirming A and B.
    "re-added tx reported unconfirmed, spender confirmed",
    vec![
        a_seen(None),
        b_seen(None),
        (vec![(b_txid, Some(101))], vec![a_txid], vec![]),
        a_back(None),
    ],
    false,
),

For an unconfirmed tx, also reading the txs at the highest cached height fixes it, and the model passes with it:

let min_height =
    min_height.or_else(|| self.sorted_txids.iter().find_map(|txid| self.heights[txid]));

It only adds the txs of the top block, and covers a scan spanning one block.

`update_unspent` adds the wallet outputs of every tx new to `heights`,
but only removes the inputs of the txs in the same update. An output
already spent by a known tx was added back to `unspent`, so
`Wollet::utxos()` returned it, the balance counted it and the tx
builder could select it, making the broadcast fail. This happens when:

* a tx is removed by a scan and found again, while its spending tx
  stays in the history;
* a tx is found after its spending tx, for example through another
  wallet script.

Before adding the outputs, drop the ones spent by a known tx. A
spending tx cannot confirm before the tx it spends, so only the known
txs at the same height or above, and the unconfirmed ones, are read.

A scan can read servers at different heights, so a tx can be reported
unconfirmed while its spending tx is cached as confirmed, and the
spending tx is then not read:

* for a tx found again unconfirmed, all the known txs are read; a
  server reporting it as confirmed has seen its block, so the height
  bound reads its spending tx;
* when the height of a known tx changes, its unspent outputs are
  checked again, so an output added with an inconsistent height is
  removed once a scan reports the right height. This also covers a tx
  found for the first time.

Updates that neither add a wallet output nor change the height of a tx
with unspent outputs read no tx, so updates still do not read every
stored tx.

Fixes Blockstream#201
Cover the cases where `update_unspent` added an output already spent by
a known tx: a tx found again after a scan removed it, with a confirmed
or unconfirmed spending tx, and a tx found after its spending tx, also
in the same block. A re-added tx with no spending tx must keep its
output unspent.

Also cover a tx reported unconfirmed by a server that has not seen the
block of its cached spending tx: found again, also when another wallet
tx is in a later block, and found for the first time, then reported
with its height.
@Jeon1691
Jeon1691 force-pushed the fix/201-spent-output-resurrection branch from 7c6ebe2 to f83999e Compare November 23, 2026 10:37
@Jeon1691 Jeon1691 changed the title wollet: cache: keep outputs spent by known txs wollet: cache: skip outputs spent by known txs Nov 23, 2026
@Jeon1691

Copy link
Copy Markdown
Author

Thanks for testing this against a model of scans, and for the failing row.

I added the row, together with a variant where another wallet tx is confirmed at 102 after B at 101. Reading the top cached block misses B in that variant, so I used two other checks:

  • A tx that comes back unconfirmed after a deletion (it is still in the txs store but no longer in heights) now reads all known txs. When the server reports it as confirmed, it has seen that block, so the existing height bound still reads the spender.
  • When the height of a known tx changes, its unspent outputs are checked again against the txs at its new height or above. A tx seen for the first time from a server that has not seen block 101 yet, while B is cached at 101, gets its output removed by the scan that reports its height. This is the third new row. It also repairs the Wollet::apply_transaction case from the description.

Updates that neither add a wallet output nor change the height of a tx with unspent outputs still read no tx.

About how a scan reaches it: step 3 already caches B at 101, so I think step 4 needs a server answering from an older chain state than the previous scan saw, for example backends at different heights. Esplora fetches the mempool and the chain history of each address separately, so the same thing could explain a confirmed tx dropping out of one scan in #201. I have not reproduced it against a live server.

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.

Cache unspent re-adds a spent output when its transaction is deleted and then seen again

2 participants