wallet: add bwatch-backed output and transaction tables#9298
Conversation
2d96dc1 to
a36f443
Compare
7ca1f9c to
3d09818
Compare
The next commits move wallet UTXO and tx tracking off chaintopology and
onto bwatch. bwatch doesn't maintain a blocks table, but the legacy
utxoset, transactions and channeltxs tables all have FOREIGN KEY
references into blocks(height) (CASCADE / SET NULL), so we can't just
retarget the existing tables.
Instead, introduce parallel tables (our_outputs, our_txs) without the
blocks(height) FK. The new bwatch-driven code writes only to these,
the legacy tables stay populated by the existing code path during this
release so downgrade still works, and a future release can drop them
once we're past the downgrade window.
Losing the FK also changes what NULL means. In the legacy tables a
NULL blockheight was never written by hand: the ON DELETE SET NULL
trigger produced it when a reorg deleted the block row. These tables
have no such trigger, so unconfirmed is stored as blockheight 0
(NOT NULL) instead, for three reasons:
- everything feeding these tables already speaks u32-with-0: watchman
notifications carry blockheight as a required JSON number, and
wallet_transaction_height() has always returned 0 for unconfirmed,
so values bind straight through without a NULL/non-NULL branch at
every read and write site;
- integer comparisons keep working: the unconfirmed->confirmed
promotion is a single "WHERE blockheight < ?" (0 sorts below any
real height) and reorg rollback is "SET blockheight = 0 WHERE
blockheight >= ?", where a NULL row would match neither;
- it removes the footgun the legacy code warned about ("Note:
blockheight=NULL is not the same as is NULL!"), where lookups had
to branch between "= ?" and "IS NULL".
The same logic gives txindex 0 = unconfirmed/unknown (a *confirmed*
txindex of 0 means coinbase, which blockheight disambiguates) and
reserved_til 0 = not reserved. NULL survives only where 0 is a real
value or genuinely ambiguous: spendheight (NULL = unspent),
channel_dbid, commitment_point.
Schema only here — wallet handlers that write into these tables and the
backfill from outputs/transactions land in subsequent commits.
Co-authored-by: Cursor <cursoragent@cursor.com>
Add the wallet helpers and watch handlers that turn a bwatch scriptpubkey match into our_txs and our_outputs rows. They validate the matching output, notify invoice accounting, record confirmed deposits, and install watches for later spends. The watch_revert handler demotes the rows back to unconfirmed (the 0 sentinel) rather than deleting them: a row also carries state a rediscovery cannot restore (reserved_til, onchaind close metadata), and the still-armed watches re-promote it if the tx confirms again. This matches the legacy tables, whose blocks(height) foreign keys demote rows to NULL when the block row is removed. Unlike got_utxo(), this path does not write transaction_annotations: nothing reads per-transaction annotations anymore, so only the legacy scanner keeps populating them (for downgrade, like the other legacy tables). The watchman dispatch entry is wired in the following commit. Keep this path alongside got_utxo() and wallet_transaction_add(): the legacy scanner must continue populating outputs and transactions for one release so downgrades do not require a rescan. Co-authored-by: Cursor <cursoragent@cursor.com>
Register the wallet/spk owner prefix with watchman so scriptpubkey matches and reverts reach the wallet handlers introduced in the previous commit. Document the owner suffix format alongside the dispatch entry. Co-authored-by: Cursor <cursoragent@cursor.com>
Populate our_outputs/our_txs from the legacy outputs/transactions tables so the bwatch wallet path starts with the same state as the existing wallet. Use outputs rather than utxoset because it already contains only wallet-owned rows and carries wallet metadata like reservations and channel-close info. Downgrade only drops the new tables: later commits keep mirroring writes into the legacy tables, so no copy-back migration is needed. Co-authored-by: Cursor <cursoragent@cursor.com>
When bwatch_got_utxo() records a wallet output, it arms an outpoint watch owned by wallet/utxo/<txid>:<outnum>. This adds the receiving end of that watch: the dispatch entry plus the found/revert handlers. On watch_found (a tx consumed the outpoint): mark the output spent in our_outputs, store the spending tx in our_txs, and emit a withdrawal coin movement. On watch_revert (a reorg removed that tx): clear spendheight so the UTXO is spendable again. Co-authored-by: Cursor <cursoragent@cursor.com>
The legacy tables rely on their blocks(height) ON DELETE SET NULL foreign keys to mark rows unconfirmed/unspent when a block is reorged out. our_outputs/our_txs deliberately carry no blocks FK (bwatch does not maintain a blocks table), so block disconnect and rollback must demote their blockheight/spendheight fields explicitly. Demote, never delete: a row also carries state the chain cannot re-deliver (reserved_til, onchaind close metadata), and this path runs not just on real reorgs but on every startup, when chaintopology invalidates its rescan window. Rediscovery re-promotes the row via wallet_add_our_output / wallet_transaction_add; a tx that never re-confirms just stays unconfirmed and unspendable. Co-authored-by: Cursor <cursoragent@cursor.com>
The bwatch path writes wallet UTXOs to our_outputs while the legacy `outputs` table is what a downgraded binary reads. Mirror every our_outputs write (insert, spend, unspend-on-spend-revert, reservation) into `outputs` so a downgrade for one release needs no copy-back or rescan. Reorg demotion needs no mirror: the legacy rows are demoted by their blocks(height) foreign keys when chaintopology removes the block. The mirroring stops in the release that removes chaintopology, freezing all the legacy tables at the same height. The spend mirror guards its spend_height the same way the insert guards confirmation_height: outputs.spend_height has a foreign key on blocks(height), which only chaintopology populates, and bwatch can deliver the spend before chaintopology has processed that block. Record NULL in that case (status already marks the row spent) and let chaintopology's own spend pass fill in the height. The wallet still reads from `outputs`; switching reads over to our_outputs comes next. Co-authored-by: Cursor <cursoragent@cursor.com>
Before this commit:
chaintopology ──────────────> outputs
bwatch ─────────────────────> our_outputs
└────────────────────> outputs (downgrade mirror)
wallet reads ───────────────> outputs
After this commit:
chaintopology ──────────────> our_outputs
└─────────────> outputs (downgrade mirror)
bwatch ─────────────────────> our_outputs
└────────────────────> outputs (downgrade mirror)
wallet still reads ─────────> outputs
Make each existing chaintopology writer update both representations of
its UTXO state:
- wallet_add_utxo and wallet_add_onchaind_utxo insert into both tables;
- db_set_utxo updates reservations in both tables;
- wallet_confirm_tx updates confirmation heights in both tables; and
- wallet_outpoint_spend marks outputs spent in both tables.
Keeping each pair of writes in the existing helper makes the downgrade
mirror explicit without duplicating SQL at its callers. Reads remain on
legacy `outputs` until the following commit switches them to our_outputs.
Co-authored-by: Cursor <cursoragent@cursor.com>
With every writer dual-writing since the previous two commits, flip the readers: all UTXO queries (listfunds, coin selection, reservations, onchaind close info) now come from our_outputs, and the legacy-only read helpers (wallet_stmt2output, gather_utxos, db_get_unspent_utxos) are deleted. our_output_row_to_utxo replaces wallet_stmt2output, using channel_dbid to discriminate HD outputs from channel-close outputs, and wallet_get_spendable_utxos centralizes the unspent+unreserved query that wallet_find_utxo and wallet_has_funds previously duplicated. migrate_setup_coinmoves keeps reading the legacy table directly: that migration runs at v25.09, before our_outputs exists. Co-authored-by: Cursor <cursoragent@cursor.com>
The wallet's live UTXO state now lives in our_outputs; point the raw-SQL assertions at it (spent means spendheight IS NOT NULL, reserved means reserved_til > 0). Co-authored-by: Cursor <cursoragent@cursor.com>
Same raw-SQL switch as test_connection.py: read the wallet's UTXO state from our_outputs. Co-authored-by: Cursor <cursoragent@cursor.com>
Upgrade a pre-bwatch snapshot db and check the migration mirrored outputs/transactions into our_outputs/our_txs, listfunds still reports the old UTXOs, and the wallet can receive and withdraw new funds. Co-authored-by: Cursor <cursoragent@cursor.com>
Now that the bwatch wallet path records every relevant transaction in our_txs, point the wallet's transaction readers at that table. Since our_txs.blockheight is NOT NULL with 0 = unconfirmed, the legacy NULL handling disappears: wallet_transactions_by_height no longer needs its "IS NULL vs = ?" query split, and wallet_transaction_height reads the column unconditionally. wallet_transaction_add keeps dual-writing the legacy transactions table: the close path still inserts into channeltxs, whose transaction_id foreign key points at transactions(id), and wallet_get_funding_spend joins it. That legacy write can only go away with channeltxs itself. Co-authored-by: Cursor <cursoragent@cursor.com>
Change addresses are no longer bech32-only (p2tr is the default form), so the old name was misleading. Pure rename, no functional change; also drop the unused txfilter.h include. Co-authored-by: Cursor <cursoragent@cursor.com>
The four wallet_datastore_{get,create,update,remove} helpers used to
require the caller to be inside a wallet transaction; otherwise the
underlying db_prepare_v2 fatals at db/utils.c:103 with "Attempting to
prepare a db_stmt outside of a transaction".
watchman persists its pending bwatch ops through these helpers from
plugin callbacks that run outside any transaction, so wrap one on
demand.
Co-authored-by: Cursor <cursoragent@cursor.com>
The flag is registered by the bwatch plugin, not lightningd, so peek at the parsed configvars. Without it ld->watchman stays NULL and the watchman_* entry points are no-ops, leaving chain_topology as the only chain watcher: bwatch and the legacy path must not race each other. The bwatch pytests opt in explicitly (with rescan=0) instead of enabling bwatch globally. Changelog-Experimental: wallet: Add bwatch-driven wallet transaction and UTXO tracking behind --experimental-bwatch. Co-authored-by: Cursor <cursoragent@cursor.com>
init_wallet_scriptpubkey_watches walks every HD key (BIP32 + BIP86) up
to {bip32,bip86}_max_index + keyscan_gap and arms a watch for each
form, so bwatch can report deposits from the very first block it
scans. wallet_get_newindex does the same for fresh keys, keeping
coverage as the wallet grows.
The per-UTXO watch on unconfirmed change is now redundant (the
perennial per-key watch already covers that scriptpubkey), so drop it.
Co-authored-by: Cursor <cursoragent@cursor.com>
The wallet no longer writes UTXO state to the legacy outputs table's status/spend_height columns, so tests that peek at the database directly must read our_outputs instead. Co-authored-by: Cursor <cursoragent@cursor.com>
3d09818 to
139b18c
Compare
cdecker
left a comment
There was a problem hiding this comment.
I have rarely seen a PR that is as well structured and pleasant to review as this one, kudos @sangbida 🤩
I have little to no comments on the code itself, but I have some questions that arose during my reviews, and it shows I did not review the previous chunks of the bwatch work, apologies if this is repeat information for everybody else, but I was hoping you could bring me up to speed quickly. I have the following things I am watching out, that I'd need help with:
- It looks to me like the watches are disabled after the first hit they encounter. What would be the outcome if an attacker were to anticipate an address or a spend that we are watching for, and frontrun it with a bogus payment? I.e., we expect a channel funding with a given script, and the attacker just does not broadcast the actual TX we are waiting for, instead sending a tiny fragment to the address. Does this disarm the watch and we'd be missing the actual funding for example? I know, not incentive compatible, as the attacker is hurting themself, but deviations need to be handled.
- One thing we faced in the old watcher code, was the "transitive infection" of watchers, i.e., due to raciness between the handlers and the block processing, we had to add new watches to any output that was spending a watched output, so that we'd follow the spend DAG, just in case we needed to know any of the later outputs. How does bwatch handle this?
Either way, this PR should be good to go 👍
|
|
||
| stmt = db_prepare_v2(w->db, | ||
| SQL("INSERT OR REPLACE INTO our_txs " | ||
| "(txid, blockheight, txindex, rawtx) VALUES (?, ?, ?, ?);")); |
There was a problem hiding this comment.
Notice that the REPLACE variant with blockheight=0 may inadvertently uncomfirm an existing tx, which may or may not be intended. It might be better to make that a conditional update here:
- First insert and on conflict do nothing.
- Then
UPDATE SET blockheight = ?, txindex = ? WHERE txid = ? AND blockheight = 0;
The WHERE guard allows us to ensure we don't accidentally touch any confirmation (updating a confirmation should only be done if we set it to 0 inbetween I think). Then we can also check how many records that UPDATE changed, and if it was 0 and blockeheight != 0 we have a clear signal of such an unintended downgrade.
|
|
||
| /* Coin movements describe final ledger history, so an unconfirmed | ||
| * discovery is persisted below but does not emit one yet. */ | ||
| if (blockheight) |
There was a problem hiding this comment.
blockheight > 0 would be a bit more self-documenting I think ;-)
| /* Extend the table to cover every key we've derived plus lookahead; | ||
| * same rule wallet_can_spend applies. */ | ||
| while (w->our_addresses_maxindex < max_index + w->keyscan_gap) | ||
| our_addresses_add_for_index(w, ++w->our_addresses_maxindex); |
There was a problem hiding this comment.
The ++ prefix skips index=0 if I'm not mistaken, is that intentional? Also the iteration stops one after maxindex.
Watches are not disabled after the first hit they encounter, watches have to be explicitly unwatched using an unwatch handler before we forget about them. We don't have an unwatch handler for our wallet scriptpubkey watches because they are perennial watches. I'm imagining you're talking about a case like this:
This is what happens instead:
We still haven't implemented the bwatch logic to look for the funding tx to do the channel open so from this PRs view we are still relying on |
Overview
This is the third PR in the
bwatchseries. It introduces two wallet tables:our_outputs, replacingoutputsour_txs, replacingtransactionsExisting wallet data is backfilled into the new tables during migration. The wallet then uses these tables as its primary data source for transaction and UTXO state.
Compatibility and bisectability
The legacy tables remain in place for at least one release so users can downgrade without requiring a rescan.
During this transition, writes are mirrored to both the new and legacy tables. This keeps every commit in the PR series bisectable and ensures that a database written by a newer binary remains usable by an older one. Reads, however, are routed through
our_outputsandour_txs.Much of the apparent duplication in this PR is intentional and will be removed once the compatibility window closes.
Wallet scriptpubkey watches
This PR also adds persistent scriptpubkey watches for wallet addresses.
At startup, the wallet registers watches for its generated address forms. When
bwatchfinds a payment to one of these scripts, the wallet:our_txs;our_outputs;Longer-term direction
A later PR will stop updating the chain-topology-owned legacy tables, including:
blockstransactionsoutputsutxosetblocks