Skip to content

wallet: Only broadcast resubmitted transactions that were added to the mempool - #36482

Open
achow101 wants to merge 5 commits into
bitcoin:masterfrom
achow101:broadcasttx-if-new
Open

achow101 wants to merge 5 commits into
bitcoin:masterfrom
achow101:broadcasttx-if-new

Conversation

@achow101

@achow101 achow101 commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

As discussed in #36403, one of the issues with current rebroadcast behavior is that the rebroadcast begins an unconditional relay of a transaction to peers. While this is broadcast is limited to peers that have not previously been inv'd the transaction, there is still a privacy leak in this double relay of a transaction, especially so for transactions that are still in nodes' mempools.

This PR changes the rebroadcast to only rebroadcast transactions if the transaction was not already present in our mempool. This provides some additional privacy while retaining intended rebroadcast behavior as transactions that have likely fallen out of nodes' mempools are the ones that actually need to be rebroadcast.

The wallet rebroadcast tests are additionally refactored for isolation so that their behaviors can still be tested after this change. Additionally, a test for the loading resubmission was added, as well as a test for the new behavior.

BroadcastTransaction takes different modes of broadcasting. Add one
which will attempt to add a transaction to the mempool, and if that
succeeds, broadcast the transaction to peers. If the transaction already
exists in the mempool, it will not be rebroadcast.
@DrahtBot DrahtBot added the Wallet label Oct 8, 2026
@DrahtBot

DrahtBot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK vasild
Concept ACK polespinasa, ismaelsadeeq

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #36540 (mempool: remove time-based transaction expiry by ismaelsadeeq)
  • #36481 (wallet, rpc, gui: Allow users to manually rebroadcast a wallet transaction by achow101)
  • #36398 (wallet: only rebroadcast transactions originating from the wallet by mzumsande)
  • #36257 (qa: assert_equal -> assert_true/assert_false by hodlinator)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@polespinasa

Copy link
Copy Markdown
Member

concept ACK

block.solve()
node.submitblock(block.serialize().hex())

def evict_mempool_transaction(self, conflict_utxo, node, wallet, indep_wallet):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This replacement pattern with indep_utxo is just the mechanism that an attacker could do to probe for which nodes a given address belong to, so this doesn't appear to completely solve the receiver issue from #3828.

@murchandamus murchandamus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This PR introduces the new MEMPOOL_AND_BROADCAST_ADDED TxBroadcast case, and uses it when the wallet resubmits transactions to the node’s mempool instead of the transaction being rebroadcast to all peers that it hadn’t been inventoried. The tests check that the rebroadcast happens when the transaction is added to the mempool and doesn’t happen when the transaction was already present. This is an obvious privacy improvement.

The only open question I have at the moment is whether the combination of using MEMPOOL_NO_BROADCAST on wallet loading and then MEMPOOL_AND_BROADCAST_ADDED on the wallet’s rebroadcast could prevent a transaction from being resubmitted to the network. E.g., if a wallet submits a low-feerate transaction, then the node is turned off for some period during which a feerate spike causes most of the network to drop the transaction, then the node is turned back on, wouldn’t this mean that the wallet’s transaction is not rebroadcast at all?

Also, I’m not sure whether using MEMPOOL_AND_BROADCAST_ADDED during wallet loading would fix that, if the node still had the transaction in its mempool from before going offline.

@fametrano

Copy link
Copy Markdown

After a restart, this branch does not announce a wallet transaction that peers already received while our own mempool keeps it, so the answer to murch's question is yes.

I built 4dbd27f and its base f739c78 and ran a regtest script that connects a fresh P2PInterface peer, moves mocktime 36 hours ahead so that MaybeResendWalletTxs runs, and sends an unrelated transaction as a barrier. A wallet transaction still in the mempool is announced on base and not on the branch, as intended. One that expired and was accepted again is announced on both. One rejected as non-final is announced on neither.

With -persistmempool=0, the load-time resubmission puts the transaction back without broadcast. With mempool.dat, it comes back already out of the unbroadcast set, because a peer requested it before shutdown. The branch announced nothing in either case, and with -persistmempool=0 nothing over two periodic resubmissions and six ReattemptInitialBroadcast windows; base announced it at each resubmission. The same holds whenever our mempool keeps a transaction that peers dropped, until it expires from our mempool (two weeks by default). A node offline for days now takes its own mempool as a proxy for everyone else's. test_resubmit_on_load stops before the first periodic resubmission; extending it would pin whichever behaviour is intended.

Smaller: the comment above ResubmitWalletTransactions still names MEMPOOL_AND_BROADCAST_TO_ALL for the periodic path, and "resubmit N unconfirmed transactions" now counts transactions not relayed. I can share the script as a gist.

Comment thread src/node/transaction.cpp
// There's already a transaction in the mempool with this txid. Don't
// try to submit this transaction to the mempool (since it'll be
// rejected as a TX_CONFLICT), but do attempt to reannounce the mempool
// transaction if broadcast_method is not TxBroadcast::MEMPOOL_NO_BROADCAST.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

in 4446226 node: Add option to relay txs only if they are added to mempool

$ git diff
diff --git a/src/node/transaction.cpp b/src/node/transaction.cpp
index 3be8919b16..23d394c7aa 100644
--- a/src/node/transaction.cpp
+++ b/src/node/transaction.cpp
@@ -62,7 +62,8 @@ TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef t
             // There's already a transaction in the mempool with this txid. Don't
             // try to submit this transaction to the mempool (since it'll be
             // rejected as a TX_CONFLICT), but do attempt to reannounce the mempool
-            // transaction if broadcast_method is not TxBroadcast::MEMPOOL_NO_BROADCAST.
+            // transaction if broadcast_method is not TxBroadcast::MEMPOOL_NO_BROADCAST
+            // or TxBroadcast::MEMPOOL_AND_BROADCAST_ADDED.
             //
             // The mempool transaction may have the same or different witness (and
             // wtxid) as this transaction. Use the mempool's wtxid for reannouncement.

Comment on lines +194 to +195
assert int(txid1, 16) not in invs
assert int(txid2, 16) not in invs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

in 858be1c test: Test wallet unconfirmed resubmission on load

This asserts are wrong, in invs we have wtxid so they will never fail.
Easy way to test it is changing txid1 or txid2 with broadcast_txid it will pass anyway, but if you use broadcast_wtxid the test will fail.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For me it fails with both broadcast_txid and broadcast_wtxid. They are equal. Here is some debug output:

         invs = peer.get_invs()
         assert int(txid1, 16) not in invs
         assert int(txid2, 16) not in invs
+        print(f"txid1:  {int(txid1, 16)}")
+        print(f"wtxid1: {int(self.nodes[0].get_wallet_rpc("loading_resubmit").gettransaction(txid1)["wtxid"], 16)}")
+        print(f"txid2:  {int(txid2, 16)}")
+        print(f"wtxid2: {int(self.default_wallet.gettransaction(txid2)["wtxid"], 16)}")
+        print(f"broadcast_txid:  {int(broadcast_txid, 16)}")
+        print(f"broadcast_wtxid: {int(broadcast_wtxid, 16)}")
+        print(f"invs[]: {invs}")

output:

txid1:  50556715902934661947412272260573146809491106239685953740317537168349755949630
wtxid1: 46464095935464499678726971305872763512167833087509151534719235003950002890391
txid2:  66017971935110931380568664541653393034732726126770766062901131324024597221773
wtxid2: 30565878341147032154661473719272837167420234698891461705525763184751019784320
broadcast_txid:  29166901737146472027258190114347233193678720285132270983418691067319012104802
broadcast_wtxid: 29166901737146472027258190114347233193678720285132270983418691067319012104802
invs[]: [29166901737146472027258190114347233193678720285132270983418691067319012104802]

I think it is more robust and easier to reason about if we test that neither one of the transaction id or witness transaction id are in the invs[].

@vasild vasild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 4dbd27f modulo #36482 (comment)

As for the @murchandamus scenario:

  • a transaction is submitted, ends up in the mempool and in the network
  • the node is shut down
  • fee pressure causes the network to forget about the transaction
  • the fee pressure eases on the network
  • the node is started
    • at wallet load it will not broadcast the transaction
    • 12-36h later it will not broadcast either because the transaction is in its mempool

#36481 would help in that case to manually rebroadcast the transaction.

Some non-blocker comments below.

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 4dbd27f37b52e49a8d392bd2ee6713ae7dcf23df modulo https://github.com/bitcoin/bitcoin/pull/36482#discussion_r4567017959

As for the @murchandamus scenario:

* a transaction is submitted, ends up in the mempool and in the network
* the node is shut down
* fee pressure causes the network to forget about the transaction
* the fee pressure eases on the network
* the node is started
  * at wallet load it will not broadcast the transaction
  * 12-36h later it will not broadcast either because the transaction is in its mempool

https://github.com/bitcoin/bitcoin/pull/36481 would help in that case to manually rebroadcast the transaction.

Some non-blocker comments below.
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmsANeEbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/hYEf/AydYNVqVYASuY8u3fQ9
yKZvpNBJvdKWWz5oN0eRZPsH7HQ1nDS/P77bAWyLA6PmwJcoTFh/QEzVl9Oq0O57
9kscEvduOYL1UW4hoOBb9WEdqoUTLywn3OxS5UqcwFGIHs63ErFYn9PRD2/HzO6X
jOmTLlpI1dUS7gQbnrO1Cqy8jLBP0CFPqS/R9tdsi/O1bJ8dwAxGxLIqEeqmFpLD
0lD+m0ufj5A6LfFCyeJhhJ7BrlxpREqQwH5vsUAiExk15vSQ2cQH7AOrY4FXIDEk
Zxb5co8+xxFdYAGo3c0PkaMRwGsUJ5+tobT9qX+FPeskX7fFl0rlO/HnXA5mMjp7
Lfg+uAkOWLBiN+NYnQBMNP+9peArHEAtVR8oTRp5W7BCQJi6QF2vEqXDdiEFFF0h
BzEA+7unMHgxW/6X/Fz9YXCOdrLBDCfhnyyCP4g9hZIxxanA7aG5MIX3x9UlGF3K
HaOyxlzLUTrNPM/O+qrVUQY5pdHD/9B+kt+eXcmDV4CEYGcLl14Hj3ZL+VMsuD4T
fwQoxSwTmlkE59I0i4RMbuR6axwUiApHFpnONqGhpuY+vquYRfdAmW2Kq8NCKkb5
8sTE6dhFVp8xt0+38g5XjppkZRQVhBRbZYcV4Rb3ZAihg65FZz5/p/IXYMPNixzA
8J83rgRSg6y10HG0wTjFUWNvwQOmrOL5PqSlb8x+o3D2/XSRiB9Q5334PBc/UO29
4P121/Q+ZCEpVnOclJUkDj19AJQRYicpoRGWslCUEfJKOi41Fvw2kk7Y5T2jr/3m
TlMz97FEKanhAQgk5opclA6bI+8Lz8CIxokylWV9T8Yy21V17KeeAziTtsaut/Bv
tq1BWqF66OnQTScS4e/cmEjRFY2zmVkslBpO0iT1UTlkHlThmEYzuKQQ6aSwhQJk
W9ddYGKAr7kH7OBPj5KpkL4lMln6Pur83joGpfq8P4jP9ACxnnel0VkySJnkLDcN
zGWVuDNiboSshE+CMNYf3tTS707C3arcWcVDNFwpviby1DvWWMJQsPgx4+9Y+aSE
8ao88/766Hhs7THwZLgkSfgHh0pcqYdl3Xa8UyKK2T2akqdm/F6GrNYOVew/i+cZ
6lZaaMWb5XzrXPmNFY8GY6iCvKyzi6mzPYbBg1RUnfN5aI3LwM7ZyecYptdq2ZDX
6lWCmc2uELhDtGGYUeeK2o9GdSlTN2lOTdG1GnfMRGN3IpAW9pGQRFGCJLx/Jn16
nPbwgS8hhXkapBxM3QhS3l78bZjNOFRnTcDxWKRgDRZabHmNFJ6xM5Z0LbnGwCXC
ige6oUhDsF+csP/ZQ1De6bAtaPcv1OGesPLjss92kV8aDX79/TnhYuuOS3LNmja6
zlE=
=jYfY
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

two_min = 2 * 60
node.bumpmocktime(twelve_hrs - two_min)
node.mockscheduler(60) # Tell scheduler to call MaybeResendWalletTxs now
assert_equal(int(wtxid, 16) in peer_second.get_invs(), False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Consider also adding:

assert_equal(int(txid, 16) in peer_second.get_invs(), False)

because neither txid nor wtxid should be in peer_second and both txid wtxid could end in the result of get_invs():

for i in message.inv:
if (i.type == MSG_TX) or (i.type == MSG_WTX):
# save txid
self.tx_invs_received[i.hash] += 1

(hint from #36482 (comment))

Comment on lines +194 to +195
assert int(txid1, 16) not in invs
assert int(txid2, 16) not in invs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For me it fails with both broadcast_txid and broadcast_wtxid. They are equal. Here is some debug output:

         invs = peer.get_invs()
         assert int(txid1, 16) not in invs
         assert int(txid2, 16) not in invs
+        print(f"txid1:  {int(txid1, 16)}")
+        print(f"wtxid1: {int(self.nodes[0].get_wallet_rpc("loading_resubmit").gettransaction(txid1)["wtxid"], 16)}")
+        print(f"txid2:  {int(txid2, 16)}")
+        print(f"wtxid2: {int(self.default_wallet.gettransaction(txid2)["wtxid"], 16)}")
+        print(f"broadcast_txid:  {int(broadcast_txid, 16)}")
+        print(f"broadcast_wtxid: {int(broadcast_wtxid, 16)}")
+        print(f"invs[]: {invs}")

output:

txid1:  50556715902934661947412272260573146809491106239685953740317537168349755949630
wtxid1: 46464095935464499678726971305872763512167833087509151534719235003950002890391
txid2:  66017971935110931380568664541653393034732726126770766062901131324024597221773
wtxid2: 30565878341147032154661473719272837167420234698891461705525763184751019784320
broadcast_txid:  29166901737146472027258190114347233193678720285132270983418691067319012104802
broadcast_wtxid: 29166901737146472027258190114347233193678720285132270983418691067319012104802
invs[]: [29166901737146472027258190114347233193678720285132270983418691067319012104802]

I think it is more robust and easier to reason about if we test that neither one of the transaction id or witness transaction id are in the invs[].

def evict_mempool_transaction(self, conflict_utxo, node, wallet, indep_wallet):
# Evict a transaction spending conflict_utxo by creating a conflict with it that pays a higher feerate
indep_utxo = indep_wallet.listunspent()[0]
psbt = indep_wallet.send(outputs=[{indep_wallet.getnewaddress(): 0.00001}], psbt=True, fee_rate=30, inputs=[conflict_utxo, indep_utxo], solving_data={"descriptors":[conflict_utxo["desc"]]})["psbt"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This assumes that the transaction to be evicted, the one that spends conflict_utxo, has a fee rate less than 30. That is a bit obscure and fragile.

Consider getting the feerate of the transaction to be evicted and using a higher value than that (plus two more asserts - that the to-be-evicted transaction is in the mempool when the function starts and is absent at the end):

--- i/test/functional/wallet_resendwallettransactions.py
+++ w/test/functional/wallet_resendwallettransactions.py
@@ -9,5 +9,8 @@ from test_framework.blocktools import (
     create_block,
 )
-from test_framework.messages import DEFAULT_MEMPOOL_EXPIRY_HOURS
+from test_framework.messages import (
+    COIN,
+    DEFAULT_MEMPOOL_EXPIRY_HOURS,
+)
 from test_framework.p2p import P2PTxInvStore
 from test_framework.test_framework import BitcoinTestFramework
@@ -45,12 +48,20 @@ class ResendWalletTransactionsTest(BitcoinTestFramework):
     def evict_mempool_transaction(self, conflict_utxo, node, wallet, indep_wallet):
         # Evict a transaction spending conflict_utxo by creating a conflict with it that pays a higher feerate
+        evict_txid = node.gettxspendingprevout([{"txid": conflict_utxo["txid"], "vout": conflict_utxo["vout"]}])[0]["spendingtxid"]
+        assert evict_txid in node.getrawmempool()
+        evict_tx_mempool_entry = node.getmempoolentry(evict_txid)
+        evict_tx_feerate = evict_tx_mempool_entry["fees"]["base"] * COIN / evict_tx_mempool_entry["vsize"]
+
         indep_utxo = indep_wallet.listunspent()[0]
-        psbt = indep_wallet.send(outputs=[{indep_wallet.getnewaddress(): 0.00001}], psbt=True, fee_rate=30, inputs=[conflict_utxo, indep_utxo], solving_data={"descriptors":[conflict_utxo["desc"]]})["psbt"]
+        tx1_feerate = evict_tx_feerate * 2
+        psbt = indep_wallet.send(outputs=[{indep_wallet.getnewaddress(): 0.00001}], psbt=True, fee_rate=tx1_feerate, inputs=[conflict_utxo, indep_utxo], solving_data={"descriptors":[conflict_utxo["desc"]]})["psbt"]
         psbt = wallet.walletprocesspsbt(psbt)["psbt"]
         txid1 = node.sendrawtransaction(node.finalizepsbt(psbt)["hex"])
         # Create a conflict with just indep_utxo to evict the previous transaction so that the original can be rebroadcast
-        r = indep_wallet.send(outputs=[{indep_wallet.getnewaddress(): 0.00001}], fee_rate=60, inputs=[indep_utxo], add_to_wallet=False)
+        tx2_feerate = tx1_feerate * 2
+        r = indep_wallet.send(outputs=[{indep_wallet.getnewaddress(): 0.00001}], fee_rate=tx2_feerate, inputs=[indep_utxo], add_to_wallet=False)
         txid2 = node.sendrawtransaction(r["hex"])
         mempool = node.getrawmempool()
+        assert evict_txid not in node.getrawmempool()
         assert txid1 not in mempool
         assert txid2 in mempool

Comment on lines 993 to +1006
def wait_for_broadcast(self, txns, *, timeout=60):
"""Waits for the txns (list of txids) to complete initial broadcast.
The mempool should mark unbroadcast=False for these transactions.
"""
# Wait until invs have been received (and getdatas sent) for each txid.
self.wait_until(lambda: set(self.tx_invs_received.keys()) == set([int(tx, 16) for tx in txns]), timeout=timeout)
# Flush messages and wait for the getdatas to be processed
self.sync_with_ping()

def wait_for_single_broadcast(self, tx, *, timeout=60):
# Wait until invs have been received (and getdatas sent) for each txid.
self.wait_until(lambda: int(tx, 16) in self.tx_invs_received.keys(), timeout=timeout)
# Flush messages and wait for the getdatas to be processed
self.sync_with_ping()

@vasild vasild Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The newly added wait_for_single_broadcast() is almost identical to the existent wait_for_broadcast(). I wonder if the existent function can be modified to use >= instead of == when comparing the sets. This would allow the input list of txids to be a subset of the tx_invs_received.

Or if that is going to break something then take a parameter to control whether to use == or >=.

@DrahtBot
DrahtBot requested a review from polespinasa November 20, 2026 11:59
@ismaelsadeeq

Copy link
Copy Markdown
Member

Concept ACK.
Worth noting that a node with a small mempool can still resubmit and rebroadcast a tx while others have it and won't relay it, so it still has the same leak even with this change. Adding a separate option to disable rebroadcast, ideally off by default, would be useful. That way, it's opt-in for advanced users who need it.

@ismaelsadeeq

Copy link
Copy Markdown
Member

Post-Coredev, I discussed the issue with a few others in BRW, and made a post about what I understand thus far. https://delvingbitcoin.org/t/exploiting-wallet-rebroadcast-to-link-addresses-to-node-ips-and-more/3123

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants