Skip to content

net_processing: make m_tx_for_private_broadcast optional - #34271

Draft
vasild wants to merge 1 commit into
bitcoin:masterfrom
vasild:optional_m_tx_for_private_broadcast
Draft

vasild wants to merge 1 commit into
bitcoin:masterfrom
vasild:optional_m_tx_for_private_broadcast

Conversation

@vasild

@vasild vasild commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Make PeerManagerImpl::m_tx_for_private_broadcast optional because it is needed only in private broadcast mode (-privatebroadcast=1).

A followup to #29415, requested in:
#29415 (comment)
https://github.com/bitcoin/bitcoin/pull/29415/files#r2620864832

has it ever been discussed to make this an std::optional that is only created in private broadcast mode? I don't love how we call various methods (that will usually return without doing anything) from net_processing if private broadcast is not enabled.

@DrahtBot

DrahtBot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/34271.

Reviews

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

Type Reviewers
Concept ACK polespinasa, w0xlt
Approach ACK l0rinc
Stale ACK optout21

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:

  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
  • #35406 (private broadcast: limit outstanding txs to count of 10,000 by instagibbs)
  • #35252 (net: send decoy transactions via private broadcast by andrewtoth)
  • #35016 (net: deduplicate private broadcast state and snapshot types by kenji-yamam0to)
  • #34628 (p2p: Replace per-peer transaction rate-limiting with global rate limits by ajtowns)
  • #29700 (kernel, refactor: return error status on all fatal errors by ryanofsky)

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.

Comment thread src/net_processing.cpp Outdated
@@ -4200,8 +4211,8 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
LogDebug(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
}

if (pfrom.IsPrivateBroadcastConn()) {
const auto pushed_tx_opt{m_tx_for_private_broadcast.GetTxForNode(pfrom.GetId())};
if (pfrom.IsPrivateBroadcastConn() && m_tx_for_private_broadcast.has_value()) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This change creates a situation that should be impossible: to have a private broadcast connection existent and have the optional m_tx_for_private_broadcast empty. Anyway it has to be handled somehow in the code and I think that maybe an assert() or Assume() is too strong? So here it would behave as if it is not a private broadcast connection. Maybe this is not the correct behavior?

I am ~0 on making m_tx_for_private_broadcast optional. In other words, it has some pros and some cons, I am fine either way.

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.

That can happen if InitiateTxBroadcastPrivate() was not called before. That could happen even without this change, and the behavior is very similar: m_tx_for_private_broadcast was initialized with an 'empty' PrivateBroadcast, so the PickTxForSend(), GetStale(), etc. methods would return nothing. However, the difference is that in that case LogDebug's are emitted. An assert might be too strong, as there is no guarantee that InitiateTxBroadcastPrivate() is called upfront, but the LogDebug messages should be emitted the same way if m_tx_for_private_broadcast none, or it is set but does not contain the expected transaction.
Another way would be to lazily init m_tx_for_private_broadcast before every access, but that may be an overkill.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That can happen if InitiateTxBroadcastPrivate() was not called before.

Ok, but how could pfrom.IsPrivateBroadcastConn() be true if InitiateTxBroadcastPrivate() was not called before?

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.

I can't answer that, maybe it can't, but there is no straightforward guarantee in the code; one is a check in CNode, one is a call in PeerManagerImpl. Regardless whether it is possible (now) or not, I'm saying that the behavior regarding logging should be the same after this change than before (even if it is there is no way to get that combination today, there may be some (incorrect) change in the future, so keeping the log is a good idea).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, I changed it to disconnect the peer if that ever happens in the future.

Comment thread src/net_processing.cpp Outdated
@@ -4200,8 +4211,8 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
LogDebug(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom.GetId());
}

if (pfrom.IsPrivateBroadcastConn()) {
const auto pushed_tx_opt{m_tx_for_private_broadcast.GetTxForNode(pfrom.GetId())};
if (pfrom.IsPrivateBroadcastConn() && m_tx_for_private_broadcast.has_value()) {

@optout21 optout21 Jan 13, 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.

How about this approach to have the same LogDebug for the case when m_tx_for_private_broadcast is unset and there is not TX?

        if (pfrom.IsPrivateBroadcastConn()) {
            const auto pushed_tx_opt{!m_tx_for_private_broadcast.has_value() ? std::nullopt : m_tx_for_private_broadcast->GetTxForNode(pfrom.GetId())};
            if (!pushed_tx_opt) {
                LogInfo( ...
                ...
            }
            ...
        }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added some logs and disconnect the peer that has IsPrivateBroadcastConn() true.

@optout21

Copy link
Copy Markdown
Contributor

ConceptACK
Review code; verified that all occurence of m_tx_for_private_broadcast is touched, verified building and unit tests locally; left some comments.

@vasild
vasild force-pushed the optional_m_tx_for_private_broadcast branch from 340d10d to c218ad8 Compare January 13, 2026 15:51
@vasild

vasild commented Jan 13, 2026

Copy link
Copy Markdown
Contributor Author

340d10d26d0163201045594b30d96edd544a2f93...c218ad88764601814204d65ce21c06c851f04014: disconnect the peer if private broadcast storage is not initialized and log those events that cannot happen with the current code and must not happen in the future either.

@polespinasa polespinasa 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.

Concept ACK

I don't understand why we check if m_tx_for_private_broadcast has value inside functions that imply that we are in private broadcast mode.

Comment thread src/net_processing.cpp Resolved
Comment thread src/net_processing.cpp Resolved

@w0xlt w0xlt 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.

Appraoch ACK

@vasild

vasild commented Feb 5, 2026

Copy link
Copy Markdown
Contributor Author

c218ad88764601814204d65ce21c06c851f04014...e1600e02a8c46b97efd47e5e6d38cf068483216f: rebase due to conflicts

@vasild
vasild force-pushed the optional_m_tx_for_private_broadcast branch from e1600e0 to 41f0bc0 Compare February 25, 2026 05:01
@vasild

vasild commented Feb 25, 2026

Copy link
Copy Markdown
Contributor Author

e1600e02a8c46b97efd47e5e6d38cf068483216f...41f0bc0332ff6942809812bbc76cc5fc38e9389e: rebase due to conflicts

@vasild

vasild commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

41f0bc0332ff6942809812bbc76cc5fc38e9389e...75259b79443cb1c7ff73af505a5f6a00f655e4d8: rebase due to conflicts

@optout21 optout21 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.

Re-reviewing 75259b79443cb1c7ff73af505a5f6a00f655e4d8 ; left two comments, otherwise LGTM

Comment thread src/net_processing.cpp Resolved
Comment thread src/net_processing.cpp Resolved
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS native, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/25670945156/job/75355721137
LLM reason (✨ experimental): CI failed because the fuzz target rpc reported “Error processing input …” and exited with code 1.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@vasild
vasild force-pushed the optional_m_tx_for_private_broadcast branch from 75259b7 to 87a4288 Compare May 12, 2026 12:13
@vasild

vasild commented May 12, 2026

Copy link
Copy Markdown
Contributor Author

75259b79443cb1c7ff73af505a5f6a00f655e4d8...87a42882a94f89eb7d418d3f2f3558fb3bc74a17: fix a silent conflict where new methods were added after this PR was created. Added a guard to them as well. This was the reason for the CI failure.

I wonder if this still makes sense, given the followups to the original PR where this was suggested. @mzumsande?

@optout21 optout21 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 87a42882a94f89eb7d418d3f2f3558fb3bc74a17

Review code; verified that all occurrences of m_tx_for_private_broadcast are touched, verified building and unit tests locally.

@DrahtBot
DrahtBot requested review from polespinasa and w0xlt May 15, 2026 09:54

@l0rinc l0rinc 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.

Approach ACK 87a42882a94f89eb7d418d3f2f3558fb3bc74a17

Making the private-broadcast transaction state optional is a useful cleanup for the default net-processing path, but my main concern is that the optional is currently initialized from InitiateTxBroadcastPrivate() instead of from the peer manager’s private-broadcast option. That means a direct call can create private-broadcast state even when the peer manager was constructed with private broadcast disabled. I left a suggested patch and a small unit test for that boundary.

I also left smaller comments around idiomatic optional checks, matching nearby private-broadcast logging style, and clarifying that std::optional<PrivateBroadcast> still reserves inline storage even when disengaged.

Could you also summarize the relevant motivation from the linked #29415 discussion in the PR description or commit message? The links are useful, but having the actual rationale here would make this PR easier to review on its own.

Comment thread src/net_processing.cpp Outdated
Comment on lines 2277 to 2283
void PeerManagerImpl::InitiateTxBroadcastPrivate(const CTransactionRef& tx)
{
// Lazily initialize `m_tx_for_private_broadcast` the first time it is needed.
if (!m_tx_for_private_broadcast.has_value()) {
m_tx_for_private_broadcast.emplace();
}
const auto txstr{strprintf("txid=%s, wtxid=%s", tx->GetHash().ToString(), tx->GetWitnessHash().ToString())};

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.

Shouldn't we do this in PeerManagerImpl::PeerManagerImpl instead?
If so, would it be possible to cover this case with a test? I'm surprised they all passed.

Here we could log instead:

diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 9d0eb588db..23a840daa2 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -2026,6 +2026,10 @@ PeerManagerImpl::PeerManagerImpl(CConnman& connman, AddrMan& addrman,
       m_warnings{warnings},
       m_opts{opts}
 {
+    if (m_opts.private_broadcast) {
+        m_tx_for_private_broadcast.emplace();
+    }
+
     // While Erlay support is incomplete, it must be enabled explicitly via -txreconciliation.
     // This argument can go away after Erlay support is complete.
     if (opts.reconcile_txs) {
@@ -2276,11 +2280,12 @@ void PeerManagerImpl::InitiateTxBroadcastToAll(const Txid& txid, const Wtxid& wt
 
 void PeerManagerImpl::InitiateTxBroadcastPrivate(const CTransactionRef& tx)
 {
-    // Lazily initialize `m_tx_for_private_broadcast` the first time it is needed.
+    const auto txstr{strprintf("txid=%s, wtxid=%s", tx->GetHash().ToString(), tx->GetWitnessHash().ToString())};
     if (!m_tx_for_private_broadcast.has_value()) {
-        m_tx_for_private_broadcast.emplace();
+        LogDebug(BCLog::PRIVBROADCAST, "Ignoring request to privately broadcast transaction because private broadcast is not enabled: %s", txstr);
+        return;
     }
-    const auto txstr{strprintf("txid=%s, wtxid=%s", tx->GetHash().ToString(), tx->GetWitnessHash().ToString())};
+
     if (m_tx_for_private_broadcast->Add(tx)) {
         LogDebug(BCLog::PRIVBROADCAST, "Requesting %d new connections due to %s", NUM_PRIVATE_BROADCAST_PER_TX, txstr);
         m_connman.m_private_broadcast.NumToOpenAdd(NUM_PRIVATE_BROADCAST_PER_TX);

we could likely verify that a peer manager constructed without private broadcast enabled does not create private-broadcast queue state or request private-broadcast connections when InitiateTxBroadcastPrivate is called directly, something like:

diff --git a/src/test/peerman_tests.cpp b/src/test/peerman_tests.cpp
--- a/src/test/peerman_tests.cpp	(revision 419182b0c6b622eee9d19dbd3938c396a494a1ae)
+++ b/src/test/peerman_tests.cpp	(revision 22b159e9217b2fbe125e8d6a8fc7baac1359dfc6)
@@ -6,6 +6,7 @@
 #include <node/miner.h>
 #include <net_processing.h>
 #include <pow.h>
+#include <primitives/transaction.h>
 #include <test/util/setup_common.h>
 #include <validation.h>
 
@@ -75,4 +76,18 @@
     BOOST_CHECK(peerman->GetDesirableServiceFlags(peer_flags) == ServiceFlags(NODE_NETWORK | NODE_WITNESS));
 }
 
+BOOST_AUTO_TEST_CASE(private_broadcast_disabled_ignores_initiate)
+{
+    BOOST_REQUIRE_EQUAL(m_node.connman->m_private_broadcast.NumToOpen(), 0U);
+
+    const auto peerman{PeerManager::make(*m_node.connman, *m_node.addrman, /*banman=*/nullptr, *m_node.chainman, *m_node.mempool, *m_node.warnings, {.private_broadcast = false})};
+    peerman->InitiateTxBroadcastPrivate(MakeTransactionRef(CMutableTransaction{}));
+
+    BOOST_CHECK(peerman->GetPrivateBroadcastInfo().empty());
+    BOOST_CHECK_EQUAL(m_node.connman->m_private_broadcast.NumToOpen(), 0U);
+}
+
 BOOST_AUTO_TEST_SUITE_END()

@vasild vasild Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved the initialization to PeerManagerImpl::PeerManagerImpl(). I am fine either way. Now PeerManagerImpl::InitiateTxBroadcastPrivate() contains an unreachable branch too. So we have these patterns in a few methods:

PeerManagerImpl::PrivateBroadcastSpecificMethod()
{
    if (m_tx_for_private_broadcast is not initialized) {
        // But it should be if this method is called,
        // so there is a bug in the caller.
        // And now what? Assert() or Assume() seems too strong?
        log a warning and return something
    }
...

I did not take the test because that seems like a bug in the caller. Extended the docs of the methods instead to mention that these methods should only be called if private broadcast has been enabled when constructing the peer manager.

Comment thread src/net_processing.cpp
@@ -3556,7 +3570,15 @@ void PeerManagerImpl::PushPrivateBroadcastTx(CNode& node)
{
Assume(node.IsPrivateBroadcastConn());

const auto opt_tx{m_tx_for_private_broadcast.PickTxForSend(node.GetId(), CService{node.addr})};
if (!m_tx_for_private_broadcast.has_value()) {

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.

Since std::optional has a dedicated operator bool() with the same semantics as has_value(), I think if (m_tx_for_private_broadcast) is preferable here.
It is idiomatic C++20 and avoids adding noise around already defensive private-broadcast guards. I would reserve .has_value() for cases where the boolean value is being named or passed onward, not for simple control flow.

Suggested change
if (!m_tx_for_private_broadcast.has_value()) {
if (!m_tx_for_private_broadcast) {

(applies to a few more cases here)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I prefer the .has_value() because it hints the human reader that this is a std:optional instead of bool, unique_ptr, int or whatever other type. Similar to why I prefer to use if (a != 0) for integers instead of if (a).

Comment thread src/net_processing.cpp
@@ -3556,7 +3570,15 @@ void PeerManagerImpl::PushPrivateBroadcastTx(CNode& node)
{
Assume(node.IsPrivateBroadcastConn());

const auto opt_tx{m_tx_for_private_broadcast.PickTxForSend(node.GetId(), CService{node.addr})};
if (!m_tx_for_private_broadcast.has_value()) {
LogWarning("[privatebroadcast] Disconnecting: private broadcast storage is "

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.

Other private-broadcast runtime logs are already almost entirely LogDebug(BCLog::PRIVBROADCAST, ...), consider if this really needs to expose to the logs that we are using private broadcast.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is a serious enough case to warrant a LogWarning(). It shows a that there is a bug in the callers, but somehow I feel that maybe Assume() is too strong here. Or maybe not?

Comment thread src/net_processing.cpp
@@ -1092,7 +1092,7 @@ class PeerManagerImpl final : public PeerManager
void LogBlockHeader(const CBlockIndex& index, const CNode& peer, bool via_compact_block);

/// The transactions to be broadcast privately.
PrivateBroadcast m_tx_for_private_broadcast;
std::optional<PrivateBroadcast> m_tx_for_private_broadcast;

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.

Note that this still reserves storage for a PrivateBroadcast inside every PeerManagerImpl, even when private broadcast is disabled.
This only skips construction and active state - avoiding the object-size footprint too would require indirection, e.g. std::unique_ptr<PrivateBroadcast>.

@mzumsande mzumsande 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.

I wonder if this still makes sense, given the #34476 to the #29415 where this was suggested. @mzumsande?

I think it depends on the general direction in which private broadcast should be taken. I always viewed it as an optional, strictly opt-in module that should be separated well. However, suggestions such as #35252 go into a completely different direction. If in the future even nodes that don't opt into private broadcast (-privatebroadcast=0) would send private transactions, then this would move private broadcast into core functionality, and making m_tx_for_private_broadcast optional wouldn't make sense.

Make `PeerManagerImpl::m_tx_for_private_broadcast` optional because it
is needed only in private broadcast mode (`-privatebroadcast=1`).

Requested in:
bitcoin#29415 (comment)
https://github.com/bitcoin/bitcoin/pull/29415/files#r2620864832
@vasild
vasild force-pushed the optional_m_tx_for_private_broadcast branch from 87a4288 to 14a241f Compare June 30, 2026 14:37
@vasild

vasild commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

87a42882a94f89eb7d418d3f2f3558fb3bc74a17...14a241f3b3d15ce531b7f384cb63302df5d62e60: rebase and take some suggestions.

@vasild

vasild commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

@mzumsande, right, I agree. And I do not have an answer.

@DrahtBot

DrahtBot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

@fanquake
fanquake marked this pull request as draft August 3, 2026 14:24
@fanquake

fanquake commented Aug 3, 2026

Copy link
Copy Markdown
Member

Moved to draft for now, given it needs rebase, and there needs to be some decisions made on general private-broadcast direction.

@DrahtBot

Copy link
Copy Markdown
Contributor

⌛ There hasn't been much activity lately and the patch still needs rebase. What is the status here?

  • Is it still relevant? ➡️ Please solve the conflicts to make it ready for review and to ensure the CI passes.
  • Is it no longer relevant? ➡️ Please close.
  • Did the author lose interest or time to work on this? ➡️ Please close it and mark it with one of the labels 'Up for grabs' or 'Insufficient Review', so that it can be picked up in the future.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants