Skip to content

Commit 5aea3d0

Browse files
committed
private broadcast: limit outstanding txs to count of 10,000
Add a belt-and-suspenders feature, limit the amount of memory and cpu possible when unlucky or simply misconfigured. The worst case limit is roughly 400kB * 10,000 = 4GB, regardless of usage pattern. Before this change, sheer volume of broadcasts, mismatches in standardness rules, or simply fee mismatches may result in unbounded growth of memory usage. As the feature may be expanded in the future, explicit bounds helps reasoning going forward.
1 parent dc282ff commit 5aea3d0

13 files changed

Lines changed: 229 additions & 23 deletions

‎src/common/messages.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ bilingual_str TransactionErrorString(const TransactionError err)
143143
return Untranslated("Unspendable output exceeds maximum configured by user (maxburnamount)");
144144
case TransactionError::INVALID_PACKAGE:
145145
return Untranslated("Transaction rejected due to invalid package");
146+
case TransactionError::PRIVATE_BROADCAST_FULL:
147+
return Untranslated("Private broadcast queue is full");
146148
} // no default case, so the compiler can warn about missing cases
147149
assert(false);
148150
}

‎src/net_processing.cpp‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -540,7 +540,7 @@ class PeerManagerImpl final : public PeerManager
540540
std::vector<CTransactionRef> AbortPrivateBroadcast(const uint256& id) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
541541
void SendPings() override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
542542
void InitiateTxBroadcastToAll(const Txid& txid, const Wtxid& wtxid) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
543-
void InitiateTxBroadcastPrivate(const CTransactionRef& tx) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
543+
node::TransactionError InitiateTxBroadcastPrivate(const CTransactionRef& tx) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
544544
void SetBestBlock(int height, std::chrono::seconds time) override
545545
{
546546
m_best_height = height;
@@ -2293,15 +2293,22 @@ void PeerManagerImpl::InitiateTxBroadcastToAll(const Txid& txid, const Wtxid& wt
22932293
}
22942294
}
22952295

2296-
void PeerManagerImpl::InitiateTxBroadcastPrivate(const CTransactionRef& tx)
2296+
node::TransactionError PeerManagerImpl::InitiateTxBroadcastPrivate(const CTransactionRef& tx)
22972297
{
22982298
const auto txstr{strprintf("txid=%s, wtxid=%s", tx->GetHash().ToString(), tx->GetWitnessHash().ToString())};
2299-
if (m_tx_for_private_broadcast.Add(tx)) {
2299+
switch (m_tx_for_private_broadcast.Add(tx)) {
2300+
case PrivateBroadcast::AddResult::Added:
23002301
LogDebug(BCLog::PRIVBROADCAST, "Requesting %d new connections due to %s", NUM_PRIVATE_BROADCAST_PER_TX, txstr);
23012302
m_connman.m_private_broadcast.NumToOpenAdd(NUM_PRIVATE_BROADCAST_PER_TX);
2302-
} else {
2303+
return node::TransactionError::OK;
2304+
case PrivateBroadcast::AddResult::AlreadyPresent:
23032305
LogDebug(BCLog::PRIVBROADCAST, "Ignoring unnecessary request to schedule an already scheduled transaction: %s", txstr);
2304-
}
2306+
return node::TransactionError::OK;
2307+
case PrivateBroadcast::AddResult::QueueFull:
2308+
LogDebug(BCLog::PRIVBROADCAST, "Rejecting private broadcast, queue full (cap=%u): %s", PrivateBroadcast::MAX_TRANSACTIONS, txstr);
2309+
return node::TransactionError::PRIVATE_BROADCAST_FULL;
2310+
} // no default case, so the compiler can warn about missing cases
2311+
assert(false);
23052312
}
23062313

23072314
void PeerManagerImpl::RelayAddress(NodeId originator,

‎src/net_processing.h‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <consensus/amount.h>
1010
#include <net.h>
1111
#include <node/txorphanage.h>
12+
#include <node/types.h>
1213
#include <private_broadcast.h>
1314
#include <protocol.h>
1415
#include <uint256.h>
@@ -147,8 +148,10 @@ class PeerManager : public CValidationInterface, public NetEventsInterface
147148
/**
148149
* Initiate a private transaction broadcast. This is done
149150
* asynchronously via short-lived connections to peers on privacy networks.
151+
* @retval node::TransactionError::OK The transaction is scheduled for private broadcast (or was already scheduled).
152+
* @retval node::TransactionError::PRIVATE_BROADCAST_FULL Rejected because the private broadcast queue is full.
150153
*/
151-
virtual void InitiateTxBroadcastPrivate(const CTransactionRef& tx) = 0;
154+
[[nodiscard]] virtual node::TransactionError InitiateTxBroadcastPrivate(const CTransactionRef& tx) = 0;
152155

153156
/** Send ping message to all peers */
154157
virtual void SendPings() = 0;

‎src/node/transaction.cpp‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,7 @@ TransactionError BroadcastTransaction(NodeContext& node,
133133
node.peerman->InitiateTxBroadcastToAll(txid, wtxid);
134134
break;
135135
case TxBroadcast::NO_MEMPOOL_PRIVATE_BROADCAST:
136-
node.peerman->InitiateTxBroadcastPrivate(tx);
137-
break;
136+
return node.peerman->InitiateTxBroadcastPrivate(tx);
138137
}
139138

140139
return TransactionError::OK;

‎src/node/types.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ enum class TransactionError {
2525
MAX_FEE_EXCEEDED,
2626
MAX_BURN_EXCEEDED,
2727
INVALID_PACKAGE,
28+
PRIVATE_BROADCAST_FULL,
2829
};
2930

3031
/**

‎src/private_broadcast.cpp‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,23 @@
33
// file COPYING or https://opensource.org/license/mit/.
44

55
#include <private_broadcast.h>
6+
67
#include <util/check.h>
78

89
#include <algorithm>
910

1011

11-
bool PrivateBroadcast::Add(const CTransactionRef& tx)
12+
[[nodiscard]] PrivateBroadcast::AddResult PrivateBroadcast::Add(const CTransactionRef& tx)
1213
EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
1314
{
1415
LOCK(m_mutex);
15-
const bool inserted{m_transactions.try_emplace(tx).second};
16-
return inserted;
16+
// Re-adding an already-tracked transaction is a no-op regardless of the cap.
17+
if (m_transactions.contains(tx)) return AddResult::AlreadyPresent;
18+
19+
if (m_transactions.size() >= m_max_transactions) return AddResult::QueueFull;
20+
21+
m_transactions.try_emplace(tx);
22+
return AddResult::Added;
1723
}
1824

1925
std::optional<size_t> PrivateBroadcast::Remove(const CTransactionRef& tx)

‎src/private_broadcast.h‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ class PrivateBroadcast
3838
/// after it is broadcast, then we consider it stale / for rebroadcasting.
3939
static constexpr auto STALE_DURATION{1min};
4040

41+
/// Maximum number of transactions tracked simultaneously.
42+
/// Additions that would exceed this are rejected (see Add()).
43+
static constexpr size_t MAX_TRANSACTIONS{10'000};
44+
45+
/// @param[in] max_transactions Cap on the number of simultaneously tracked
46+
/// transactions. Defaults to MAX_TRANSACTIONS.
47+
explicit PrivateBroadcast(size_t max_transactions = MAX_TRANSACTIONS)
48+
: m_max_transactions{max_transactions} {}
49+
4150
struct PeerSendInfo {
4251
CService address;
4352
NodeClock::time_point sent;
@@ -50,13 +59,23 @@ class PrivateBroadcast
5059
std::vector<PeerSendInfo> peers;
5160
};
5261

62+
/// Outcome of Add().
63+
enum class AddResult {
64+
//! The transaction was newly added.
65+
Added,
66+
//! The transaction was already present; no change.
67+
AlreadyPresent,
68+
//! Rejected: the queue is already at MAX_TRANSACTIONS.
69+
QueueFull,
70+
};
71+
5372
/**
5473
* Add a transaction to the storage.
5574
* @param[in] tx The transaction to add.
56-
* @retval true The transaction was added.
57-
* @retval false The transaction was already present.
75+
* @return Whether the transaction was newly added, was already present, or
76+
* was rejected because the queue is full (see AddResult).
5877
*/
59-
bool Add(const CTransactionRef& tx)
78+
[[nodiscard]] AddResult Add(const CTransactionRef& tx)
6079
EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
6180

6281
/**
@@ -196,6 +215,8 @@ class PrivateBroadcast
196215
const NodeClock::time_point time_added{NodeClock::now()};
197216
std::vector<SendStatus> send_statuses;
198217
};
218+
/// Cap on the number of simultaneously tracked transactions (see Add()).
219+
const size_t m_max_transactions;
199220
mutable Mutex m_mutex;
200221
std::unordered_map<CTransactionRef, TxSendStatus, CTransactionRefHash, CTransactionRefComp>
201222
m_transactions GUARDED_BY(m_mutex);

‎src/rpc/mempool.cpp‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ static RPCMethod sendrawtransaction()
6060
"dedicated, short-lived connections to Tor or I2P peers or IPv4/IPv6 peers\n"
6161
"via the Tor network. This conceals the transaction's origin. The transaction\n"
6262
"will only enter the local mempool when it is received back from the network.\n"
63+
"The private broadcast queue is bounded: when it is full, this RPC fails and\n"
64+
"the transaction is not scheduled, until an existing one completes or is\n"
65+
"aborted. Use getprivatebroadcastinfo to inspect the queue and abortprivatebroadcast to abort.\n"
6366

6467
"\nA specific exception, RPC_TRANSACTION_ALREADY_IN_UTXO_SET, may throw if the transaction cannot be added to the mempool.\n"
6568

‎src/rpc/util.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,8 @@ RPCErrorCode RPCErrorFromTransactionError(TransactionError terr)
395395
return RPC_TRANSACTION_REJECTED;
396396
case TransactionError::ALREADY_IN_UTXO_SET:
397397
return RPC_VERIFY_ALREADY_IN_UTXO_SET;
398+
case TransactionError::PRIVATE_BROADCAST_FULL:
399+
return RPC_OUT_OF_MEMORY;
398400
default: break;
399401
}
400402
return RPC_TRANSACTION_ERROR;

‎src/test/fuzz/private_broadcast.cpp‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ FUZZ_TARGET(private_broadcast)
3838
FuzzedDataProvider fdp(buffer.data(), buffer.size());
3939
FakeNodeClock clock_ctx{ConsumeTime(fdp)};
4040

41-
PrivateBroadcast pb;
41+
const size_t cap{fdp.ConsumeIntegralInRange<size_t>(1, 12)};
42+
PrivateBroadcast pb{cap};
4243

4344
// Random transaction that the test generated and passed to Add(). Trimmed when Remove() is called.
4445
// The values are the number of times a transaction was picked for sending.
@@ -64,15 +65,20 @@ FUZZ_TARGET(private_broadcast)
6465
fdp,
6566
[&] { // Add()
6667
CTransactionRef tx;
67-
bool from_transactions{false};
6868
if (transactions.empty() || fdp.ConsumeBool()) {
6969
tx = MakeTransactionRef(ConsumeTransaction(fdp, std::nullopt));
7070
} else {
7171
tx = PickIterator(fdp, transactions)->first;
72-
from_transactions = true;
7372
}
74-
if (pb.Add(tx)) {
75-
Assert(!from_transactions);
73+
74+
const bool present_before{transactions.contains(tx)};
75+
const auto res{pb.Add(tx)};
76+
if (present_before) {
77+
Assert(res == PrivateBroadcast::AddResult::AlreadyPresent);
78+
} else if (transactions.size() >= cap) {
79+
Assert(res == PrivateBroadcast::AddResult::QueueFull);
80+
} else {
81+
Assert(res == PrivateBroadcast::AddResult::Added);
7682
transactions.emplace(tx, 0);
7783
}
7884
},

0 commit comments

Comments
 (0)