Bitcoin Core 28.99.0
P2P Digital Currency
txorphanage.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-2022 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 <txorphanage.h>
6
8#include <logging.h>
9#include <policy/policy.h>
11#include <util/time.h>
12
13#include <cassert>
14
16{
17 const Txid& hash = tx->GetHash();
18 const Wtxid& wtxid = tx->GetWitnessHash();
19 if (m_orphans.count(wtxid))
20 return false;
21
22 // Ignore big transactions, to avoid a
23 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
24 // large transaction with a missing parent then we assume
25 // it will rebroadcast it later, after the parent transaction(s)
26 // have been mined or received.
27 // 100 orphans, each of which is at most 100,000 bytes big is
28 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
29 unsigned int sz = GetTransactionWeight(*tx);
31 {
32 LogDebug(BCLog::TXPACKAGES, "ignoring large orphan tx (size: %u, txid: %s, wtxid: %s)\n", sz, hash.ToString(), wtxid.ToString());
33 return false;
34 }
35
36 auto ret = m_orphans.emplace(wtxid, OrphanTx{{tx, peer, Now<NodeSeconds>() + ORPHAN_TX_EXPIRE_TIME}, m_orphan_list.size()});
37 assert(ret.second);
38 m_orphan_list.push_back(ret.first);
39 for (const CTxIn& txin : tx->vin) {
40 m_outpoint_to_orphan_it[txin.prevout].insert(ret.first);
41 }
42
43 LogDebug(BCLog::TXPACKAGES, "stored orphan tx %s (wtxid=%s), weight: %u (mapsz %u outsz %u)\n", hash.ToString(), wtxid.ToString(), sz,
44 m_orphans.size(), m_outpoint_to_orphan_it.size());
45 return true;
46}
47
48int TxOrphanage::EraseTx(const Wtxid& wtxid)
49{
50 std::map<Wtxid, OrphanTx>::iterator it = m_orphans.find(wtxid);
51 if (it == m_orphans.end())
52 return 0;
53 for (const CTxIn& txin : it->second.tx->vin)
54 {
55 auto itPrev = m_outpoint_to_orphan_it.find(txin.prevout);
56 if (itPrev == m_outpoint_to_orphan_it.end())
57 continue;
58 itPrev->second.erase(it);
59 if (itPrev->second.empty())
60 m_outpoint_to_orphan_it.erase(itPrev);
61 }
62
63 size_t old_pos = it->second.list_pos;
64 assert(m_orphan_list[old_pos] == it);
65 if (old_pos + 1 != m_orphan_list.size()) {
66 // Unless we're deleting the last entry in m_orphan_list, move the last
67 // entry to the position we're deleting.
68 auto it_last = m_orphan_list.back();
69 m_orphan_list[old_pos] = it_last;
70 it_last->second.list_pos = old_pos;
71 }
72 const auto& txid = it->second.tx->GetHash();
73 // Time spent in orphanage = difference between current and entry time.
74 // Entry time is equal to ORPHAN_TX_EXPIRE_TIME earlier than entry's expiry.
75 LogDebug(BCLog::TXPACKAGES, " removed orphan tx %s (wtxid=%s) after %ds\n", txid.ToString(), wtxid.ToString(),
76 Ticks<std::chrono::seconds>(NodeClock::now() + ORPHAN_TX_EXPIRE_TIME - it->second.nTimeExpire));
77 m_orphan_list.pop_back();
78
79 m_orphans.erase(it);
80 return 1;
81}
82
84{
85 m_peer_work_set.erase(peer);
86
87 int nErased = 0;
88 std::map<Wtxid, OrphanTx>::iterator iter = m_orphans.begin();
89 while (iter != m_orphans.end())
90 {
91 // increment to avoid iterator becoming invalid after erasure
92 const auto& [wtxid, orphan] = *iter++;
93 if (orphan.fromPeer == peer) {
94 nErased += EraseTx(wtxid);
95 }
96 }
97 if (nErased > 0) LogDebug(BCLog::TXPACKAGES, "Erased %d orphan transaction(s) from peer=%d\n", nErased, peer);
98}
99
100void TxOrphanage::LimitOrphans(unsigned int max_orphans, FastRandomContext& rng)
101{
102 unsigned int nEvicted = 0;
103 auto nNow{Now<NodeSeconds>()};
104 if (m_next_sweep <= nNow) {
105 // Sweep out expired orphan pool entries:
106 int nErased = 0;
107 auto nMinExpTime{nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL};
108 std::map<Wtxid, OrphanTx>::iterator iter = m_orphans.begin();
109 while (iter != m_orphans.end())
110 {
111 std::map<Wtxid, OrphanTx>::iterator maybeErase = iter++;
112 if (maybeErase->second.nTimeExpire <= nNow) {
113 nErased += EraseTx(maybeErase->second.tx->GetWitnessHash());
114 } else {
115 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
116 }
117 }
118 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
120 if (nErased > 0) LogDebug(BCLog::TXPACKAGES, "Erased %d orphan tx due to expiration\n", nErased);
121 }
122 while (m_orphans.size() > max_orphans)
123 {
124 // Evict a random orphan:
125 size_t randompos = rng.randrange(m_orphan_list.size());
126 EraseTx(m_orphan_list[randompos]->second.tx->GetWitnessHash());
127 ++nEvicted;
128 }
129 if (nEvicted > 0) LogDebug(BCLog::TXPACKAGES, "orphanage overflow, removed %u tx\n", nEvicted);
130}
131
133{
134 for (unsigned int i = 0; i < tx.vout.size(); i++) {
135 const auto it_by_prev = m_outpoint_to_orphan_it.find(COutPoint(tx.GetHash(), i));
136 if (it_by_prev != m_outpoint_to_orphan_it.end()) {
137 for (const auto& elem : it_by_prev->second) {
138 // Get this source peer's work set, emplacing an empty set if it didn't exist
139 // (note: if this peer wasn't still connected, we would have removed the orphan tx already)
140 std::set<Wtxid>& orphan_work_set = m_peer_work_set.try_emplace(elem->second.fromPeer).first->second;
141 // Add this tx to the work set
142 orphan_work_set.insert(elem->first);
143 LogDebug(BCLog::TXPACKAGES, "added %s (wtxid=%s) to peer %d workset\n",
144 tx.GetHash().ToString(), tx.GetWitnessHash().ToString(), elem->second.fromPeer);
145 }
146 }
147 }
148}
149
150bool TxOrphanage::HaveTx(const Wtxid& wtxid) const
151{
152 return m_orphans.count(wtxid);
153}
154
156{
157 auto work_set_it = m_peer_work_set.find(peer);
158 if (work_set_it != m_peer_work_set.end()) {
159 auto& work_set = work_set_it->second;
160 while (!work_set.empty()) {
161 Wtxid wtxid = *work_set.begin();
162 work_set.erase(work_set.begin());
163
164 const auto orphan_it = m_orphans.find(wtxid);
165 if (orphan_it != m_orphans.end()) {
166 return orphan_it->second.tx;
167 }
168 }
169 }
170 return nullptr;
171}
172
174{
175 auto work_set_it = m_peer_work_set.find(peer);
176 if (work_set_it != m_peer_work_set.end()) {
177 auto& work_set = work_set_it->second;
178 return !work_set.empty();
179 }
180 return false;
181}
182
184{
185 std::vector<Wtxid> vOrphanErase;
186
187 for (const CTransactionRef& ptx : block.vtx) {
188 const CTransaction& tx = *ptx;
189
190 // Which orphan pool entries must we evict?
191 for (const auto& txin : tx.vin) {
192 auto itByPrev = m_outpoint_to_orphan_it.find(txin.prevout);
193 if (itByPrev == m_outpoint_to_orphan_it.end()) continue;
194 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
195 const CTransaction& orphanTx = *(*mi)->second.tx;
196 vOrphanErase.push_back(orphanTx.GetWitnessHash());
197 }
198 }
199 }
200
201 // Erase orphan transactions included or precluded by this block
202 if (vOrphanErase.size()) {
203 int nErased = 0;
204 for (const auto& orphanHash : vOrphanErase) {
205 nErased += EraseTx(orphanHash);
206 }
207 LogDebug(BCLog::TXPACKAGES, "Erased %d orphan transaction(s) included or conflicted by block\n", nErased);
208 }
209}
210
211std::vector<CTransactionRef> TxOrphanage::GetChildrenFromSamePeer(const CTransactionRef& parent, NodeId nodeid) const
212{
213 // First construct a vector of iterators to ensure we do not return duplicates of the same tx
214 // and so we can sort by nTimeExpire.
215 std::vector<OrphanMap::iterator> iters;
216
217 // For each output, get all entries spending this prevout, filtering for ones from the specified peer.
218 for (unsigned int i = 0; i < parent->vout.size(); i++) {
219 const auto it_by_prev = m_outpoint_to_orphan_it.find(COutPoint(parent->GetHash(), i));
220 if (it_by_prev != m_outpoint_to_orphan_it.end()) {
221 for (const auto& elem : it_by_prev->second) {
222 if (elem->second.fromPeer == nodeid) {
223 iters.emplace_back(elem);
224 }
225 }
226 }
227 }
228
229 // Sort by address so that duplicates can be deleted. At the same time, sort so that more recent
230 // orphans (which expire later) come first. Break ties based on address, as nTimeExpire is
231 // quantified in seconds and it is possible for orphans to have the same expiry.
232 std::sort(iters.begin(), iters.end(), [](const auto& lhs, const auto& rhs) {
233 if (lhs->second.nTimeExpire == rhs->second.nTimeExpire) {
234 return &(*lhs) < &(*rhs);
235 } else {
236 return lhs->second.nTimeExpire > rhs->second.nTimeExpire;
237 }
238 });
239 // Erase duplicates
240 iters.erase(std::unique(iters.begin(), iters.end()), iters.end());
241
242 // Convert to a vector of CTransactionRef
243 std::vector<CTransactionRef> children_found;
244 children_found.reserve(iters.size());
245 for (const auto& child_iter : iters) {
246 children_found.emplace_back(child_iter->second.tx);
247 }
248 return children_found;
249}
250
251std::vector<std::pair<CTransactionRef, NodeId>> TxOrphanage::GetChildrenFromDifferentPeer(const CTransactionRef& parent, NodeId nodeid) const
252{
253 // First construct vector of iterators to ensure we do not return duplicates of the same tx.
254 std::vector<OrphanMap::iterator> iters;
255
256 // For each output, get all entries spending this prevout, filtering for ones not from the specified peer.
257 for (unsigned int i = 0; i < parent->vout.size(); i++) {
258 const auto it_by_prev = m_outpoint_to_orphan_it.find(COutPoint(parent->GetHash(), i));
259 if (it_by_prev != m_outpoint_to_orphan_it.end()) {
260 for (const auto& elem : it_by_prev->second) {
261 if (elem->second.fromPeer != nodeid) {
262 iters.emplace_back(elem);
263 }
264 }
265 }
266 }
267
268 // Erase duplicates
269 std::sort(iters.begin(), iters.end(), IteratorComparator());
270 iters.erase(std::unique(iters.begin(), iters.end()), iters.end());
271
272 // Convert iterators to pair<CTransactionRef, NodeId>
273 std::vector<std::pair<CTransactionRef, NodeId>> children_found;
274 children_found.reserve(iters.size());
275 for (const auto& child_iter : iters) {
276 children_found.emplace_back(child_iter->second.tx, child_iter->second.fromPeer);
277 }
278 return children_found;
279}
280
281std::vector<TxOrphanage::OrphanTxBase> TxOrphanage::GetOrphanTransactions() const
282{
283 std::vector<OrphanTxBase> ret;
284 ret.reserve(m_orphans.size());
285 for (auto const& o : m_orphans) {
286 ret.push_back({o.second.tx, o.second.fromPeer, o.second.nTimeExpire});
287 }
288 return ret;
289}
int ret
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const std::vector< CTxOut > vout
Definition: transaction.h:307
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
const std::vector< CTxIn > vin
Definition: transaction.h:306
An input of a transaction.
Definition: transaction.h:67
COutPoint prevout
Definition: transaction.h:69
Fast randomness source.
Definition: random.h:377
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
bool AddTx(const CTransactionRef &tx, NodeId peer)
Add a new orphan transaction.
Definition: txorphanage.cpp:15
void EraseForPeer(NodeId peer)
Erase all orphans announced by a peer (eg, after that peer disconnects)
Definition: txorphanage.cpp:83
void AddChildrenToWorkSet(const CTransaction &tx)
Add any orphans that list a particular tx as a parent into the from peer's work set.
std::vector< OrphanTxBase > GetOrphanTransactions() const
void LimitOrphans(unsigned int max_orphans, FastRandomContext &rng)
Limit the orphanage to the given maximum.
int EraseTx(const Wtxid &wtxid)
Erase an orphan by wtxid.
Definition: txorphanage.cpp:48
void EraseForBlock(const CBlock &block)
Erase all orphans included in or invalidated by a new block.
std::map< NodeId, std::set< Wtxid > > m_peer_work_set
Which peer provided the orphans that need to be reconsidered.
Definition: txorphanage.h:94
std::map< COutPoint, std::set< OrphanMap::iterator, IteratorComparator > > m_outpoint_to_orphan_it
Index from the parents' COutPoint into the m_orphans.
Definition: txorphanage.h:109
std::vector< std::pair< CTransactionRef, NodeId > > GetChildrenFromDifferentPeer(const CTransactionRef &parent, NodeId nodeid) const
Get all children that spend from this tx but were not received from nodeid.
std::vector< OrphanMap::iterator > m_orphan_list
Orphan transactions in vector for quick random eviction.
Definition: txorphanage.h:112
std::vector< CTransactionRef > GetChildrenFromSamePeer(const CTransactionRef &parent, NodeId nodeid) const
Get all children that spend from this tx and were received from nodeid.
std::map< Wtxid, OrphanTx > m_orphans
Map from wtxid to orphan transaction record.
Definition: txorphanage.h:91
bool HaveTx(const Wtxid &wtxid) const
Check if we already have an orphan transaction (by wtxid only)
bool HaveTxToReconsider(NodeId peer)
Does this peer have any work to do?
CTransactionRef GetTxToReconsider(NodeId peer)
Extract a transaction from a peer's work set Returns nullptr if there are no transactions to work on.
NodeSeconds m_next_sweep
Timestamp for the next scheduled sweep of expired orphans.
Definition: txorphanage.h:115
std::string ToString() const
constexpr const std::byte * begin() const
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:133
#define LogDebug(category,...)
Definition: logging.h:280
@ TXPACKAGES
Definition: logging.h:73
int64_t NodeId
Definition: net.h:97
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Definition: policy.h:27
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:24
static constexpr auto ORPHAN_TX_EXPIRE_TIME
Expiration time for orphan transactions.
Definition: txorphanage.h:18
static constexpr auto ORPHAN_TX_EXPIRE_INTERVAL
Minimum time between orphan transactions expire time checks.
Definition: txorphanage.h:20
assert(!tx.IsCoinBase())