LCOV - code coverage report
Current view: top level - src/node - txdownloadman_impl.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 83.3 % 252 210
Test Date: 2026-11-13 06:50:46 Functions: 83.3 % 42 35
Branches: 46.4 % 364 169

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

Generated by: LCOV version 2.0-1