Branch data Line data Source code
1 : : // Copyright (c) 2024
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <node/txdownloadman_impl.h>
6 : : #include <node/txdownloadman.h>
7 : :
8 : : #include <chain.h>
9 : : #include <consensus/validation.h>
10 : : #include <logging.h>
11 : : #include <txmempool.h>
12 : : #include <validation.h>
13 : : #include <validationinterface.h>
14 : :
15 : : namespace node {
16 : : // TxDownloadManager wrappers
17 : 2641 : TxDownloadManager::TxDownloadManager(const TxDownloadOptions& options) :
18 : 2641 : m_impl{std::make_unique<TxDownloadManagerImpl>(options)}
19 : 2641 : {}
20 : 2641 : TxDownloadManager::~TxDownloadManager() = default;
21 : :
22 : 66 : void TxDownloadManager::ActiveTipChange()
23 : : {
24 : 66 : m_impl->ActiveTipChange();
25 : 66 : }
26 : 4012 : void TxDownloadManager::BlockConnected(const std::shared_ptr<const CBlock>& pblock)
27 : : {
28 : 4012 : m_impl->BlockConnected(pblock);
29 : 4012 : }
30 : 196 : void TxDownloadManager::BlockDisconnected()
31 : : {
32 : 196 : m_impl->BlockDisconnected();
33 : 196 : }
34 : 12978 : void TxDownloadManager::ConnectedPeer(NodeId nodeid, const TxDownloadConnectionInfo& info)
35 : : {
36 : 12978 : m_impl->ConnectedPeer(nodeid, info);
37 : 12978 : }
38 : 45343 : void TxDownloadManager::DisconnectedPeer(NodeId nodeid)
39 : : {
40 : 45343 : m_impl->DisconnectedPeer(nodeid);
41 : 45343 : }
42 : 160723 : bool TxDownloadManager::AddTxAnnouncement(NodeId peer, const GenTxid& gtxid, std::chrono::microseconds now)
43 : : {
44 : 160723 : return m_impl->AddTxAnnouncement(peer, gtxid, now);
45 : : }
46 : 1267215 : std::vector<GenTxid> TxDownloadManager::GetRequestsToSend(NodeId nodeid, std::chrono::microseconds current_time)
47 : : {
48 : 1267215 : return m_impl->GetRequestsToSend(nodeid, current_time);
49 : : }
50 : 440 : void TxDownloadManager::ReceivedNotFound(NodeId nodeid, const std::vector<uint256>& txhashes)
51 : : {
52 : 440 : m_impl->ReceivedNotFound(nodeid, txhashes);
53 : 440 : }
54 : 425 : void TxDownloadManager::MempoolAcceptedTx(const CTransactionRef& tx)
55 : : {
56 : 425 : m_impl->MempoolAcceptedTx(tx);
57 : 425 : }
58 : 5988 : RejectedTxTodo TxDownloadManager::MempoolRejectedTx(const CTransactionRef& ptx, const TxValidationState& state, NodeId nodeid, bool first_time_failure)
59 : : {
60 : 5988 : return m_impl->MempoolRejectedTx(ptx, state, nodeid, first_time_failure);
61 : : }
62 : 0 : void TxDownloadManager::MempoolRejectedPackage(const Package& package)
63 : : {
64 : 0 : m_impl->MempoolRejectedPackage(package);
65 : 0 : }
66 : 24609 : std::pair<bool, std::optional<PackageToValidate>> TxDownloadManager::ReceivedTx(NodeId nodeid, const CTransactionRef& ptx)
67 : : {
68 : 24609 : return m_impl->ReceivedTx(nodeid, ptx);
69 : : }
70 : 98567 : bool TxDownloadManager::HaveMoreWork(NodeId nodeid) const
71 : : {
72 : 98567 : return m_impl->HaveMoreWork(nodeid);
73 : : }
74 : 1315060 : CTransactionRef TxDownloadManager::GetTxToReconsider(NodeId nodeid)
75 : : {
76 : 1315060 : return m_impl->GetTxToReconsider(nodeid);
77 : : }
78 : 12033 : void TxDownloadManager::CheckIsEmpty() const
79 : : {
80 : 12033 : m_impl->CheckIsEmpty();
81 : 12033 : }
82 : 45343 : void TxDownloadManager::CheckIsEmpty(NodeId nodeid) const
83 : : {
84 : 45343 : m_impl->CheckIsEmpty(nodeid);
85 : 45343 : }
86 : 6 : std::vector<TxOrphanage::OrphanTxBase> TxDownloadManager::GetOrphanTransactions() const
87 : : {
88 : 6 : return m_impl->GetOrphanTransactions();
89 : : }
90 : :
91 : : // TxDownloadManagerImpl
92 : 1369 : void TxDownloadManagerImpl::ActiveTipChange()
93 : : {
94 : 1369 : RecentRejectsFilter().reset();
95 : 1369 : RecentRejectsReconsiderableFilter().reset();
96 : 1369 : }
97 : :
98 : 7439 : void TxDownloadManagerImpl::BlockConnected(const std::shared_ptr<const CBlock>& pblock)
99 : : {
100 : 7439 : m_orphanage.EraseForBlock(*pblock);
101 : :
102 [ + + ]: 14878 : for (const auto& ptx : pblock->vtx) {
103 : 7439 : RecentConfirmedTransactionsFilter().insert(ptx->GetHash().ToUint256());
104 [ + + ]: 7439 : if (ptx->HasWitness()) {
105 : 7359 : RecentConfirmedTransactionsFilter().insert(ptx->GetWitnessHash().ToUint256());
106 : : }
107 : 7439 : m_txrequest.ForgetTxHash(ptx->GetHash());
108 : 7439 : m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
109 : : }
110 : 7439 : }
111 : :
112 : 323 : void TxDownloadManagerImpl::BlockDisconnected()
113 : : {
114 : : // To avoid relay problems with transactions that were previously
115 : : // confirmed, clear our filter of recently confirmed transactions whenever
116 : : // there's a reorg.
117 : : // This means that in a 1-block reorg (where 1 block is disconnected and
118 : : // then another block reconnected), our filter will drop to having only one
119 : : // block's worth of transactions in it, but that should be fine, since
120 : : // presumably the most common case of relaying a confirmed transaction
121 : : // should be just after a new block containing it is found.
122 : 323 : RecentConfirmedTransactionsFilter().reset();
123 : 323 : }
124 : :
125 : 358336 : bool TxDownloadManagerImpl::AlreadyHaveTx(const GenTxid& gtxid, bool include_reconsiderable)
126 : : {
127 [ + + ]: 358336 : const uint256& hash = gtxid.GetHash();
128 : :
129 [ + + ]: 358336 : if (gtxid.IsWtxid()) {
130 : : // Normal query by wtxid.
131 [ + + ]: 44552 : if (m_orphanage.HaveTx(Wtxid::FromUint256(hash))) return true;
132 : : } else {
133 : : // Never query by txid: it is possible that the transaction in the orphanage has the same
134 : : // txid but a different witness, which would give us a false positive result. If we decided
135 : : // not to request the transaction based on this result, an attacker could prevent us from
136 : : // downloading a transaction by intentionally creating a malleated version of it. While
137 : : // only one (or none!) of these transactions can ultimately be confirmed, we have no way of
138 : : // discerning which one that is, so the orphanage can store multiple transactions with the
139 : : // same txid.
140 : : //
141 : : // While we won't query by txid, we can try to "guess" what the wtxid is based on the txid.
142 : : // A non-segwit transaction's txid == wtxid. Query this txid "casted" to a wtxid. This will
143 : : // help us find non-segwit transactions, saving bandwidth, and should have no false positives.
144 [ + + ]: 313784 : if (m_orphanage.HaveTx(Wtxid::FromUint256(hash))) return true;
145 : : }
146 : :
147 [ + + + - ]: 358143 : if (include_reconsiderable && RecentRejectsReconsiderableFilter().contains(hash)) return true;
148 : :
149 [ + + ]: 358143 : if (RecentConfirmedTransactionsFilter().contains(hash)) return true;
150 : :
151 [ + + - + ]: 357301 : return RecentRejectsFilter().contains(hash) || m_opts.m_mempool.exists(gtxid);
152 : : }
153 : :
154 : 13526 : void TxDownloadManagerImpl::ConnectedPeer(NodeId nodeid, const TxDownloadConnectionInfo& info)
155 : : {
156 : : // If already connected (shouldn't happen in practice), exit early.
157 [ + + ]: 13526 : if (m_peer_info.contains(nodeid)) return;
158 : :
159 : 13374 : m_peer_info.try_emplace(nodeid, info);
160 [ + + ]: 13374 : if (info.m_wtxid_relay) m_num_wtxid_peers += 1;
161 : : }
162 : :
163 : 72616 : void TxDownloadManagerImpl::DisconnectedPeer(NodeId nodeid)
164 : : {
165 : 72616 : m_orphanage.EraseForPeer(nodeid);
166 : 72616 : m_txrequest.DisconnectedPeer(nodeid);
167 : :
168 [ + + ]: 72616 : if (auto it = m_peer_info.find(nodeid); it != m_peer_info.end()) {
169 [ + + ]: 13374 : if (it->second.m_connection_info.m_wtxid_relay) m_num_wtxid_peers -= 1;
170 : 13374 : m_peer_info.erase(it);
171 : : }
172 : :
173 : 72616 : }
174 : :
175 : 162653 : bool TxDownloadManagerImpl::AddTxAnnouncement(NodeId peer, const GenTxid& gtxid, std::chrono::microseconds now)
176 : : {
177 : : // If this is an orphan we are trying to resolve, consider this peer as a orphan resolution candidate instead.
178 : : // - is wtxid matching something in orphanage
179 : : // - exists in orphanage
180 : : // - peer can be an orphan resolution candidate
181 [ + + ]: 162653 : if (gtxid.IsWtxid()) {
182 [ + + ]: 1888 : if (auto orphan_tx{m_orphanage.GetTx(Wtxid::FromUint256(gtxid.GetHash()))}) {
183 [ + - ]: 27 : auto unique_parents{GetUniqueParents(*orphan_tx)};
184 [ + - ]: 27 : std::erase_if(unique_parents, [&](const auto& txid){
185 : 53 : return AlreadyHaveTx(GenTxid::Txid(txid), /*include_reconsiderable=*/false);
186 : : });
187 : :
188 [ + - ]: 27 : if (unique_parents.empty()) return true;
189 : :
190 [ + - - + ]: 27 : if (auto delay{OrphanResolutionCandidate(peer, Wtxid::FromUint256(gtxid.GetHash()), unique_parents.size())}) {
191 [ # # ]: 0 : m_orphanage.AddAnnouncer(Wtxid::FromUint256(gtxid.GetHash()), peer);
192 : :
193 [ # # ]: 0 : const auto& info = m_peer_info.at(peer).m_connection_info;
194 [ # # ]: 0 : for (const auto& parent_txid : unique_parents) {
195 [ # # ]: 0 : m_txrequest.ReceivedInv(peer, GenTxid::Txid(parent_txid), info.m_preferred, now + *delay);
196 : : }
197 : :
198 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, "added peer=%d as a candidate for resolving orphan %s\n", peer, gtxid.GetHash().ToString());
# # # # ]
199 : : }
200 : :
201 : : // Return even if the peer isn't an orphan resolution candidate. This would be caught by AlreadyHaveTx.
202 : 27 : return true;
203 [ + - ]: 1915 : }
204 : : }
205 : :
206 : : // If this is an inv received from a peer and we already have it, we can drop it.
207 [ + + ]: 162626 : if (AlreadyHaveTx(gtxid, /*include_reconsiderable=*/true)) return true;
208 : :
209 : 162620 : auto it = m_peer_info.find(peer);
210 [ + + ]: 162620 : if (it == m_peer_info.end()) return false;
211 [ + + ]: 160520 : const auto& info = it->second.m_connection_info;
212 [ + + + - ]: 160520 : if (!info.m_relay_permissions && m_txrequest.Count(peer) >= MAX_PEER_TX_ANNOUNCEMENTS) {
213 : : // Too many queued announcements for this peer
214 : : return false;
215 : : }
216 : : // Decide the TxRequestTracker parameters for this announcement:
217 : : // - "preferred": if fPreferredDownload is set (= outbound, or NetPermissionFlags::NoBan permission)
218 : : // - "reqtime": current time plus delays for:
219 : : // - NONPREF_PEER_TX_DELAY for announcements from non-preferred connections
220 : : // - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
221 : : // - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
222 : : // MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
223 : 160520 : auto delay{0us};
224 [ + + ]: 160520 : if (!info.m_preferred) delay += NONPREF_PEER_TX_DELAY;
225 [ + + + + ]: 160520 : if (!gtxid.IsWtxid() && m_num_wtxid_peers > 0) delay += TXID_RELAY_DELAY;
226 [ + + + + ]: 160520 : const bool overloaded = !info.m_relay_permissions && m_txrequest.CountInFlight(peer) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
227 : 543 : if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
228 : :
229 : 160520 : m_txrequest.ReceivedInv(peer, gtxid, info.m_preferred, now + delay);
230 : :
231 : 160520 : return false;
232 : : }
233 : :
234 : 4481 : std::optional<std::chrono::seconds> TxDownloadManagerImpl::OrphanResolutionCandidate(NodeId nodeid, const Wtxid& orphan_wtxid, size_t num_parents)
235 : : {
236 [ + + ]: 4481 : if (m_peer_info.count(nodeid) == 0) return std::nullopt;
237 [ + + ]: 4378 : if (m_orphanage.HaveTxFromPeer(orphan_wtxid, nodeid)) return std::nullopt;
238 : :
239 : 4351 : const auto& peer_entry = m_peer_info.at(nodeid);
240 : 4351 : const auto& info = peer_entry.m_connection_info;
241 : : // TODO: add delays and limits based on the amount of orphan resolution we are already doing
242 : : // with this peer, how much they are using the orphanage, etc.
243 [ + + ]: 4351 : if (!info.m_relay_permissions) {
244 : : // This mirrors the delaying and dropping behavior in AddTxAnnouncement in order to preserve
245 : : // existing behavior: drop if we are tracking too many invs for this peer already. Each
246 : : // orphan resolution involves at least 1 transaction request which may or may not be
247 : : // currently tracked in m_txrequest, so we include that in the count.
248 [ - + ]: 2627 : if (m_txrequest.Count(nodeid) + num_parents > MAX_PEER_TX_ANNOUNCEMENTS) return std::nullopt;
249 : : }
250 : :
251 : 4351 : std::chrono::seconds delay{0s};
252 [ + + ]: 4351 : if (!info.m_preferred) delay += NONPREF_PEER_TX_DELAY;
253 : : // The orphan wtxid is used, but resolution entails requesting the parents by txid. Sometimes
254 : : // parent and child are announced and thus requested around the same time, and we happen to
255 : : // receive child sooner. Waiting a few seconds may allow us to cancel the orphan resolution
256 : : // request if the parent arrives in that time.
257 [ + + ]: 4351 : if (m_num_wtxid_peers > 0) delay += TXID_RELAY_DELAY;
258 [ + + + + ]: 4351 : const bool overloaded = !info.m_relay_permissions && m_txrequest.CountInFlight(nodeid) >= MAX_PEER_TX_REQUEST_IN_FLIGHT;
259 : 38 : if (overloaded) delay += OVERLOADED_PEER_TX_DELAY;
260 : :
261 : 4351 : return delay;
262 : : }
263 : :
264 : 1268422 : std::vector<GenTxid> TxDownloadManagerImpl::GetRequestsToSend(NodeId nodeid, std::chrono::microseconds current_time)
265 : : {
266 : 1268422 : std::vector<GenTxid> requests;
267 : 1268422 : std::vector<std::pair<NodeId, GenTxid>> expired;
268 [ + - ]: 1268422 : auto requestable = m_txrequest.GetRequestable(nodeid, current_time, &expired);
269 [ + + ]: 1295268 : for (const auto& entry : expired) {
270 [ + - - + : 26846 : LogDebug(BCLog::NET, "timeout of inflight %s %s from peer=%d\n", entry.second.IsWtxid() ? "wtx" : "tx",
- - - - -
- ]
271 : : entry.second.GetHash().ToString(), entry.first);
272 : : }
273 [ + + ]: 1402009 : for (const GenTxid& gtxid : requestable) {
274 [ + - + - ]: 133587 : if (!AlreadyHaveTx(gtxid, /*include_reconsiderable=*/false)) {
275 [ + - - + : 133587 : LogDebug(BCLog::NET, "Requesting %s %s peer=%d\n", gtxid.IsWtxid() ? "wtx" : "tx",
- - - - -
- ]
276 : : gtxid.GetHash().ToString(), nodeid);
277 [ + - ]: 133587 : requests.emplace_back(gtxid);
278 [ + - ]: 133587 : m_txrequest.RequestedTx(nodeid, gtxid.GetHash(), current_time + GETDATA_TX_INTERVAL);
279 : : } else {
280 : : // We have already seen this transaction, no need to download. This is just a belt-and-suspenders, as
281 : : // this should already be called whenever a transaction becomes AlreadyHaveTx().
282 [ # # ]: 0 : m_txrequest.ForgetTxHash(gtxid.GetHash());
283 : : }
284 : : }
285 : 1268422 : return requests;
286 : 1268422 : }
287 : :
288 : 549 : void TxDownloadManagerImpl::ReceivedNotFound(NodeId nodeid, const std::vector<uint256>& txhashes)
289 : : {
290 [ + + ]: 1898 : for (const auto& txhash : txhashes) {
291 : : // If we receive a NOTFOUND message for a tx we requested, mark the announcement for it as
292 : : // completed in TxRequestTracker.
293 : 1349 : m_txrequest.ReceivedResponse(nodeid, txhash);
294 : : }
295 : 549 : }
296 : :
297 : 303 : std::optional<PackageToValidate> TxDownloadManagerImpl::Find1P1CPackage(const CTransactionRef& ptx, NodeId nodeid)
298 : : {
299 : 303 : const auto& parent_wtxid{ptx->GetWitnessHash()};
300 : :
301 : 303 : Assume(RecentRejectsReconsiderableFilter().contains(parent_wtxid.ToUint256()));
302 : :
303 : : // Only consider children from this peer. This helps prevent censorship attempts in which an attacker
304 : : // sends lots of fake children for the parent, and we (unluckily) keep selecting the fake
305 : : // children instead of the real one provided by the honest peer. Since we track all announcers
306 : : // of an orphan, this does not exclude parent + orphan pairs that we happened to request from
307 : : // different peers.
308 : 303 : const auto cpfp_candidates_same_peer{m_orphanage.GetChildrenFromSamePeer(ptx, nodeid)};
309 : :
310 : : // These children should be sorted from newest to oldest. In the (probably uncommon) case
311 : : // of children that replace each other, this helps us accept the highest feerate (probably the
312 : : // most recent) one efficiently.
313 [ - + ]: 303 : for (const auto& child : cpfp_candidates_same_peer) {
314 [ # # # # : 0 : Package maybe_cpfp_package{ptx, child};
# # # # ]
315 [ # # # # : 0 : if (!RecentRejectsReconsiderableFilter().contains(GetPackageHash(maybe_cpfp_package)) &&
# # # # #
# ]
316 [ # # # # ]: 0 : !RecentRejectsFilter().contains(child->GetHash().ToUint256())) {
317 [ # # ]: 0 : return PackageToValidate{ptx, child, nodeid, nodeid};
318 : : }
319 : 0 : }
320 : 303 : return std::nullopt;
321 [ - - - - : 303 : }
- - ]
322 : :
323 : 670 : void TxDownloadManagerImpl::MempoolAcceptedTx(const CTransactionRef& tx)
324 : : {
325 : : // As this version of the transaction was acceptable, we can forget about any requests for it.
326 : : // No-op if the tx is not in txrequest.
327 : 670 : m_txrequest.ForgetTxHash(tx->GetHash());
328 : 670 : m_txrequest.ForgetTxHash(tx->GetWitnessHash());
329 : :
330 : 670 : m_orphanage.AddChildrenToWorkSet(*tx);
331 : : // If it came from the orphanage, remove it. No-op if the tx is not in txorphanage.
332 : 670 : m_orphanage.EraseTx(tx->GetWitnessHash());
333 : 670 : }
334 : :
335 : 4452 : std::vector<Txid> TxDownloadManagerImpl::GetUniqueParents(const CTransaction& tx)
336 : : {
337 : 4452 : std::vector<Txid> unique_parents;
338 [ + - ]: 4452 : unique_parents.reserve(tx.vin.size());
339 [ + + ]: 25855 : for (const CTxIn& txin : tx.vin) {
340 : : // We start with all parents, and then remove duplicates below.
341 [ + - ]: 21403 : unique_parents.push_back(txin.prevout.hash);
342 : : }
343 : :
344 : 4452 : std::sort(unique_parents.begin(), unique_parents.end());
345 : 4452 : unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
346 : :
347 : 4452 : return unique_parents;
348 : 0 : }
349 : :
350 : 6131 : node::RejectedTxTodo TxDownloadManagerImpl::MempoolRejectedTx(const CTransactionRef& ptx, const TxValidationState& state, NodeId nodeid, bool first_time_failure)
351 : : {
352 [ + + ]: 6131 : const CTransaction& tx{*ptx};
353 : : // Results returned to caller
354 : : // Whether we should call AddToCompactExtraTransactions at the end
355 : 6131 : bool add_extra_compact_tx{first_time_failure};
356 : : // Hashes to pass to AddKnownTx later
357 : 6131 : std::vector<Txid> unique_parents;
358 : : // Populated if failure is reconsiderable and eligible package is found.
359 : 6131 : std::optional<node::PackageToValidate> package_to_validate;
360 : :
361 [ + + ]: 6131 : if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
362 : : // Only process a new orphan if this is a first time failure, as otherwise it must be either
363 : : // already in orphanage or from 1p1c processing.
364 [ + + + - : 4481 : if (first_time_failure && !RecentRejectsFilter().contains(ptx->GetWitnessHash().ToUint256())) {
+ - + + ]
365 : 4425 : bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
366 : :
367 : : // Deduplicate parent txids, so that we don't have to loop over
368 : : // the same parent txid more than once down below.
369 [ + - ]: 8850 : unique_parents = GetUniqueParents(tx);
370 : :
371 : : // Distinguish between parents in m_lazy_recent_rejects and m_lazy_recent_rejects_reconsiderable.
372 : : // We can tolerate having up to 1 parent in m_lazy_recent_rejects_reconsiderable since we
373 : : // submit 1p1c packages. However, fail immediately if any are in m_lazy_recent_rejects.
374 : 4425 : std::optional<uint256> rejected_parent_reconsiderable;
375 [ + - + + ]: 25312 : for (const uint256& parent_txid : unique_parents) {
376 [ + - + - : 20890 : if (RecentRejectsFilter().contains(parent_txid)) {
+ + ]
377 : : fRejectedParents = true;
378 : : break;
379 [ + - + - : 20895 : } else if (RecentRejectsReconsiderableFilter().contains(parent_txid) &&
+ + + - ]
380 [ + - ]: 8 : !m_opts.m_mempool.exists(GenTxid::Txid(parent_txid))) {
381 : : // More than 1 parent in m_lazy_recent_rejects_reconsiderable: 1p1c will not be
382 : : // sufficient to accept this package, so just give up here.
383 [ + - ]: 8 : if (rejected_parent_reconsiderable.has_value()) {
384 : : fRejectedParents = true;
385 : : break;
386 : : }
387 : 8 : rejected_parent_reconsiderable = parent_txid;
388 : : }
389 : : }
390 [ + + ]: 4425 : if (!fRejectedParents) {
391 : : // Filter parents that we already have.
392 : : // Exclude m_lazy_recent_rejects_reconsiderable: the missing parent may have been
393 : : // previously rejected for being too low feerate. This orphan might CPFP it.
394 [ + - ]: 4422 : std::erase_if(unique_parents, [&](const auto& txid){
395 : 20881 : return AlreadyHaveTx(GenTxid::Txid(txid), /*include_reconsiderable=*/false);
396 : : });
397 : 4422 : const auto now{GetTime<std::chrono::microseconds>()};
398 [ + - ]: 4422 : const auto& wtxid = ptx->GetWitnessHash();
399 : : // Potentially flip add_extra_compact_tx to false if tx is already in orphanage, which
400 : : // means it was already added to vExtraTxnForCompact.
401 [ + - ]: 4422 : add_extra_compact_tx &= !m_orphanage.HaveTx(wtxid);
402 : :
403 : 8876 : auto add_orphan_reso_candidate = [&](const CTransactionRef& orphan_tx, const std::vector<Txid>& unique_parents, NodeId nodeid, std::chrono::microseconds now) {
404 : 4454 : const auto& wtxid = orphan_tx->GetWitnessHash();
405 [ + + ]: 4454 : if (auto delay{OrphanResolutionCandidate(nodeid, wtxid, unique_parents.size())}) {
406 : 4351 : const auto& info = m_peer_info.at(nodeid).m_connection_info;
407 : 4351 : m_orphanage.AddTx(orphan_tx, nodeid);
408 : :
409 : : // Treat finding orphan resolution candidate as equivalent to the peer announcing all missing parents
410 : : // In the future, orphan resolution may include more explicit steps
411 [ + + ]: 25048 : for (const auto& parent_txid : unique_parents) {
412 : 20697 : m_txrequest.ReceivedInv(nodeid, GenTxid::Txid(parent_txid), info.m_preferred, now + *delay);
413 : : }
414 [ - + - - ]: 4351 : LogDebug(BCLog::TXPACKAGES, "added peer=%d as a candidate for resolving orphan %s\n", nodeid, wtxid.ToString());
415 : : }
416 : 4454 : };
417 : :
418 : : // If there is no candidate for orphan resolution, AddTx will not be called. This means
419 : : // that if a peer is overloading us with invs and orphans, they will eventually not be
420 : : // able to add any more transactions to the orphanage.
421 [ + - ]: 4422 : add_orphan_reso_candidate(ptx, unique_parents, nodeid, now);
422 [ + - + + ]: 4454 : for (const auto& candidate : m_txrequest.GetCandidatePeers(ptx)) {
423 [ + - ]: 32 : add_orphan_reso_candidate(ptx, unique_parents, candidate, now);
424 : 0 : }
425 : :
426 : : // Once added to the orphan pool, a tx is considered AlreadyHave, and we shouldn't request it anymore.
427 [ + - ]: 4422 : m_txrequest.ForgetTxHash(tx.GetHash());
428 [ + - ]: 4422 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
429 : :
430 : : // DoS prevention: do not allow m_orphanage to grow unbounded (see CVE-2012-3789)
431 : : // Note that, if the orphanage reaches capacity, it's possible that we immediately evict
432 : : // the transaction we just added.
433 [ + - ]: 4422 : m_orphanage.LimitOrphans(m_opts.m_max_orphan_txs, m_opts.m_rng);
434 : : } else {
435 [ + - ]: 3 : unique_parents.clear();
436 [ + - - + : 3 : LogDebug(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s (wtxid=%s)\n",
- - - - -
- ]
437 : : tx.GetHash().ToString(),
438 : : tx.GetWitnessHash().ToString());
439 : : // We will continue to reject this tx since it has rejected
440 : : // parents so avoid re-requesting it from other peers.
441 : : // Here we add both the txid and the wtxid, as we know that
442 : : // regardless of what witness is provided, we will not accept
443 : : // this, so we don't need to allow for redownload of this txid
444 : : // from any of our non-wtxidrelay peers.
445 [ + - + - ]: 3 : RecentRejectsFilter().insert(tx.GetHash().ToUint256());
446 [ + - + - ]: 3 : RecentRejectsFilter().insert(tx.GetWitnessHash().ToUint256());
447 [ + - ]: 3 : m_txrequest.ForgetTxHash(tx.GetHash());
448 [ + - ]: 3 : m_txrequest.ForgetTxHash(tx.GetWitnessHash());
449 : : }
450 : : }
451 [ + + ]: 1650 : } else if (state.GetResult() == TxValidationResult::TX_WITNESS_STRIPPED) {
452 : : add_extra_compact_tx = false;
453 : : } else {
454 : : // We can add the wtxid of this transaction to our reject filter.
455 : : // Do not add txids of witness transactions or witness-stripped
456 : : // transactions to the filter, as they can have been malleated;
457 : : // adding such txids to the reject filter would potentially
458 : : // interfere with relay of valid transactions from peers that
459 : : // do not support wtxid-based relay. See
460 : : // https://github.com/bitcoin/bitcoin/issues/8279 for details.
461 : : // We can remove this restriction (and always add wtxids to
462 : : // the filter even for witness stripped transactions) once
463 : : // wtxid-based relay is broadly deployed.
464 : : // See also comments in https://github.com/bitcoin/bitcoin/pull/18044#discussion_r443419034
465 : : // for concerns around weakening security of unupgraded nodes
466 : : // if we start doing this too early.
467 [ + + ]: 1638 : if (state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
468 : : // If the result is TX_RECONSIDERABLE, add it to m_lazy_recent_rejects_reconsiderable
469 : : // because we should not download or submit this transaction by itself again, but may
470 : : // submit it as part of a package later.
471 [ + - + - ]: 168 : RecentRejectsReconsiderableFilter().insert(ptx->GetWitnessHash().ToUint256());
472 : :
473 [ + + ]: 168 : if (first_time_failure) {
474 : : // When a transaction fails for TX_RECONSIDERABLE, look for a matching child in the
475 : : // orphanage, as it is possible that they succeed as a package.
476 [ + - - + : 151 : LogDebug(BCLog::TXPACKAGES, "tx %s (wtxid=%s) failed but reconsiderable, looking for child in orphanage\n",
- - - - -
- ]
477 : : ptx->GetHash().ToString(), ptx->GetWitnessHash().ToString());
478 [ + - - + ]: 453 : package_to_validate = Find1P1CPackage(ptx, nodeid);
479 : : }
480 : : } else {
481 [ + - + - ]: 1470 : RecentRejectsFilter().insert(ptx->GetWitnessHash().ToUint256());
482 : : }
483 [ + - ]: 1638 : m_txrequest.ForgetTxHash(ptx->GetWitnessHash());
484 : : // If the transaction failed for TX_INPUTS_NOT_STANDARD,
485 : : // then we know that the witness was irrelevant to the policy
486 : : // failure, since this check depends only on the txid
487 : : // (the scriptPubKey being spent is covered by the txid).
488 : : // Add the txid to the reject filter to prevent repeated
489 : : // processing of this transaction in the event that child
490 : : // transactions are later received (resulting in
491 : : // parent-fetching by txid via the orphan-handling logic).
492 : : // We only add the txid if it differs from the wtxid, to avoid wasting entries in the
493 : : // rolling bloom filter.
494 [ + + + + ]: 1638 : if (state.GetResult() == TxValidationResult::TX_INPUTS_NOT_STANDARD && ptx->HasWitness()) {
495 [ + - + - ]: 14 : RecentRejectsFilter().insert(ptx->GetHash().ToUint256());
496 [ + - ]: 14 : m_txrequest.ForgetTxHash(ptx->GetHash());
497 : : }
498 : : }
499 : :
500 : : // If the tx failed in ProcessOrphanTx, it should be removed from the orphanage unless the
501 : : // tx was still missing inputs. If the tx was not in the orphanage, EraseTx does nothing and returns 0.
502 [ + + + - : 6131 : if (state.GetResult() != TxValidationResult::TX_MISSING_INPUTS && m_orphanage.EraseTx(ptx->GetWitnessHash()) > 0) {
- + ]
503 [ # # # # : 0 : LogDebug(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s)\n", ptx->GetHash().ToString(), ptx->GetWitnessHash().ToString());
# # # # #
# ]
504 : : }
505 : :
506 [ - + - + ]: 6131 : return RejectedTxTodo{
507 : : .m_should_add_extra_compact_tx = add_extra_compact_tx,
508 : : .m_unique_parents = std::move(unique_parents),
509 : : .m_package_to_validate = std::move(package_to_validate)
510 : 6131 : };
511 : 6131 : }
512 : :
513 : 0 : void TxDownloadManagerImpl::MempoolRejectedPackage(const Package& package)
514 : : {
515 : 0 : RecentRejectsReconsiderableFilter().insert(GetPackageHash(package));
516 : 0 : }
517 : :
518 : 33016 : std::pair<bool, std::optional<PackageToValidate>> TxDownloadManagerImpl::ReceivedTx(NodeId nodeid, const CTransactionRef& ptx)
519 : : {
520 : 33016 : const uint256& txid = ptx->GetHash();
521 : 33016 : const uint256& wtxid = ptx->GetWitnessHash();
522 : :
523 : : // Mark that we have received a response
524 : 33016 : m_txrequest.ReceivedResponse(nodeid, txid);
525 [ + + ]: 33016 : if (ptx->HasWitness()) m_txrequest.ReceivedResponse(nodeid, wtxid);
526 : :
527 : : // First check if we should drop this tx.
528 : : // We do the AlreadyHaveTx() check using wtxid, rather than txid - in the
529 : : // absence of witness malleation, this is strictly better, because the
530 : : // recent rejects filter may contain the wtxid but rarely contains
531 : : // the txid of a segwit transaction that has been rejected.
532 : : // In the presence of witness malleation, it's possible that by only
533 : : // doing the check with wtxid, we could overlook a transaction which
534 : : // was confirmed with a different witness, or exists in our mempool
535 : : // with a different witness, but this has limited downside:
536 : : // mempool validation does its own lookup of whether we have the txid
537 : : // already; and an adversary can already relay us old transactions
538 : : // (older than our recency filter) if trying to DoS us, without any need
539 : : // for witness malleation.
540 [ + + ]: 33016 : if (AlreadyHaveTx(GenTxid::Wtxid(wtxid), /*include_reconsiderable=*/false)) {
541 : : // If a tx is detected by m_lazy_recent_rejects it is ignored. Because we haven't
542 : : // submitted the tx to our mempool, we won't have computed a DoS
543 : : // score for it or determined exactly why we consider it invalid.
544 : : //
545 : : // This means we won't penalize any peer subsequently relaying a DoSy
546 : : // tx (even if we penalized the first peer who gave it to us) because
547 : : // we have to account for m_lazy_recent_rejects showing false positives. In
548 : : // other words, we shouldn't penalize a peer if we aren't *sure* they
549 : : // submitted a DoSy tx.
550 : : //
551 : : // Note that m_lazy_recent_rejects doesn't just record DoSy or invalid
552 : : // transactions, but any tx not accepted by the mempool, which may be
553 : : // due to node policy (vs. consensus). So we can't blanket penalize a
554 : : // peer simply for relaying a tx that our m_lazy_recent_rejects has caught,
555 : : // regardless of false positives.
556 : 1760 : return {false, std::nullopt};
557 [ + + ]: 31256 : } else if (RecentRejectsReconsiderableFilter().contains(wtxid)) {
558 : : // When a transaction is already in m_lazy_recent_rejects_reconsiderable, we shouldn't submit
559 : : // it by itself again. However, look for a matching child in the orphanage, as it is
560 : : // possible that they succeed as a package.
561 [ - + - - : 152 : LogDebug(BCLog::TXPACKAGES, "found tx %s (wtxid=%s) in reconsiderable rejects, looking for child in orphanage\n",
- - ]
562 : : txid.ToString(), wtxid.ToString());
563 [ - + - + ]: 304 : return {false, Find1P1CPackage(ptx, nodeid)};
564 : : }
565 : :
566 : :
567 : 31104 : return {true, std::nullopt};
568 : : }
569 : :
570 : 98833 : bool TxDownloadManagerImpl::HaveMoreWork(NodeId nodeid)
571 : : {
572 : 98833 : return m_orphanage.HaveTxToReconsider(nodeid);
573 : : }
574 : :
575 : 1315326 : CTransactionRef TxDownloadManagerImpl::GetTxToReconsider(NodeId nodeid)
576 : : {
577 : 1315326 : return m_orphanage.GetTxToReconsider(nodeid);
578 : : }
579 : :
580 : 72616 : void TxDownloadManagerImpl::CheckIsEmpty(NodeId nodeid)
581 : : {
582 [ - + ]: 72616 : assert(m_txrequest.Count(nodeid) == 0);
583 : 72616 : }
584 : 13426 : void TxDownloadManagerImpl::CheckIsEmpty()
585 : : {
586 [ - + ]: 13426 : assert(m_orphanage.Size() == 0);
587 [ - + ]: 13426 : assert(m_txrequest.Size() == 0);
588 [ - + ]: 13426 : assert(m_num_wtxid_peers == 0);
589 : 13426 : }
590 : 6 : std::vector<TxOrphanage::OrphanTxBase> TxDownloadManagerImpl::GetOrphanTransactions() const
591 : : {
592 : 6 : return m_orphanage.GetOrphanTransactions();
593 : : }
594 : : } // namespace node
|