Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
txpool.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 The Bitcoin Core developers
2// Copyright (c) 2024 The Bitcoin developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <txpool.h>
7
9#include <logging.h>
10#include <policy/policy.h>
11#include <random.h>
12
13#include <cassert>
14
15bool TxPool::AddTx(const CTransactionRef &tx, NodeId peer) {
16 const TxId &txid = tx->GetId();
17 if (auto it{m_pool_txs.find(txid)}; it != m_pool_txs.end()) {
18 AddAnnouncer(txid, peer);
19 // No new tx entry was created. An announcer may have been added.
20 return false;
21 }
22
23 // Ignore big transactions, to avoid a memory exhaustion attack. If a peer
24 // has a legitimate large transaction then we assume it will rebroadcast it
25 // later.
26 unsigned int sz = tx->GetTotalSize();
27 if (sz > MAX_STANDARD_TX_SIZE) {
29 "ignoring large %s tx (size: %u, hash: %s)\n", txKind, sz,
30 txid.ToString());
31 return false;
32 }
33
34 auto ret = m_pool_txs.emplace(
35 txid,
36 PoolTx{tx, {peer}, Now<NodeSeconds>() + expireTime, m_txs_list.size()});
37 assert(ret.second);
38 m_txs_list.push_back(ret.first);
39 for (const CTxIn &txin : tx->vin) {
40 m_outpoint_to_tx_it[txin.prevout].insert(ret.first);
41 }
42
44 "stored %s tx %s, size: %u (mapsz %u outsz %u)\n", txKind,
45 txid.ToString(), sz, m_pool_txs.size(),
46 m_outpoint_to_tx_it.size());
47 return true;
48}
49
50bool TxPool::AddAnnouncer(const TxId &txid, NodeId peer) {
51 const auto it = m_pool_txs.find(txid);
52 if (it != m_pool_txs.end()) {
53 Assume(!it->second.announcers.empty());
54 const auto ret = it->second.announcers.insert(peer);
55 if (ret.second) {
57 "added peer=%d as announcer of %s tx %s\n", peer, txKind,
58 txid.ToString());
59 return true;
60 }
61 }
62 return false;
63}
64
65int TxPool::EraseTx(const TxId &txid) {
66 std::map<TxId, PoolTx>::iterator it = m_pool_txs.find(txid);
67 if (it == m_pool_txs.end()) {
68 return 0;
69 }
70 for (const CTxIn &txin : it->second.tx->vin) {
71 auto itPrev = m_outpoint_to_tx_it.find(txin.prevout);
72 if (itPrev == m_outpoint_to_tx_it.end()) {
73 continue;
74 }
75 itPrev->second.erase(it);
76 if (itPrev->second.empty()) {
77 m_outpoint_to_tx_it.erase(itPrev);
78 }
79 }
80
81 size_t old_pos = it->second.list_pos;
82 assert(m_txs_list[old_pos] == it);
83 if (old_pos + 1 != m_txs_list.size()) {
84 // Unless we're deleting the last entry in m_txs_list, move the last
85 // entry to the position we're deleting.
86 auto it_last = m_txs_list.back();
87 m_txs_list[old_pos] = it_last;
88 it_last->second.list_pos = old_pos;
89 }
90
91 // Time spent in pool = difference between current and entry time.
92 // Entry time is equal to expireTime earlier than entry's expiry.
93 LogDebug(BCLog::TXPACKAGES, " removed %s tx %s after %ds\n", txKind,
94 txid.ToString(),
95 Ticks<std::chrono::seconds>(NodeClock::now() + expireTime -
96 it->second.nTimeExpire));
97 m_txs_list.pop_back();
98
99 m_pool_txs.erase(it);
100 return 1;
101}
102
104 m_peer_work_set.erase(peer);
105
106 int nErased = 0;
107 std::map<TxId, PoolTx>::iterator iter = m_pool_txs.begin();
108 while (iter != m_pool_txs.end()) {
109 // increment to avoid iterator becoming invalid after erasure
110 auto &[txid, pooltx] = *iter++;
111 auto pooltx_it = pooltx.announcers.find(peer);
112 if (pooltx_it != pooltx.announcers.end()) {
113 pooltx.announcers.erase(peer);
114
115 // No remaining announcers: clean up entry
116 if (pooltx.announcers.empty()) {
117 nErased += EraseTx(pooltx.tx->GetId());
118 }
119 }
120 }
121 if (nErased > 0) {
123 "Erased %d %s transaction(s) from peer=%d\n", nErased, txKind,
124 peer);
125 }
126}
127
128unsigned int TxPool::LimitTxs(unsigned int max_txs, FastRandomContext &rng) {
129 unsigned int nEvicted = 0;
130 auto nNow{Now<NodeSeconds>()};
131 if (m_next_sweep <= nNow) {
132 // Sweep out expired orphan pool entries:
133 int nErased = 0;
134 auto nMinExpTime{nNow + expireTime - expireInterval};
135 std::map<TxId, PoolTx>::iterator iter = m_pool_txs.begin();
136 while (iter != m_pool_txs.end()) {
137 std::map<TxId, PoolTx>::iterator maybeErase = iter++;
138 if (maybeErase->second.nTimeExpire <= nNow) {
139 nErased += EraseTx(maybeErase->first);
140 } else {
141 nMinExpTime =
142 std::min(maybeErase->second.nTimeExpire, nMinExpTime);
143 }
144 }
145 // Sweep again 5 minutes after the next entry that expires in order to
146 // batch the linear scan.
147 m_next_sweep = nMinExpTime + expireInterval;
148 if (nErased > 0) {
149 LogDebug(BCLog::TXPACKAGES, "Erased %d %s tx due to expiration\n",
150 nErased, txKind);
151 }
152 }
153 while (m_pool_txs.size() > max_txs) {
154 // Evict a random tx:
155 size_t randompos = rng.randrange(m_txs_list.size());
156 EraseTx(m_txs_list[randompos]->first);
157 ++nEvicted;
158 }
159 return nEvicted;
160}
161
162void TxPool::AddChildrenToWorkSet(const CTransaction &tx,
163 FastRandomContext &rng) {
164 for (size_t i = 0; i < tx.vout.size(); i++) {
165 const auto it_by_prev =
166 m_outpoint_to_tx_it.find(COutPoint(tx.GetId(), i));
167 if (it_by_prev != m_outpoint_to_tx_it.end()) {
168 for (const auto &elem : it_by_prev->second) {
169 // Belt and suspenders, each tx should always have at least 1
170 // announcer.
171 if (!Assume(!elem->second.announcers.empty())) {
172 continue;
173 }
174
175 // Select a random peer to assign tx processing, reducing wasted
176 // work if the tx is still missing inputs. However, we don't
177 // want to create an issue in which the assigned peer can
178 // purposefully stop us from processing the tx by
179 // disconnecting.
180 auto announcer_iter = std::begin(elem->second.announcers);
181 std::advance(announcer_iter,
182 rng.randrange(elem->second.announcers.size()));
183 auto announcer = *(announcer_iter);
184
185 // Get this peer's work set, emplacing an empty set if it didn't
186 // exist
187 std::set<TxId> &work_set =
188 m_peer_work_set.try_emplace(announcer).first->second;
189 // Add this tx to the work set
190 work_set.insert(elem->first);
192 "added %s tx %s to peer %d workset\n", txKind,
193 tx.GetId().ToString(), announcer);
194 }
195 }
196 }
197}
198
199bool TxPool::HaveTx(const TxId &txid) const {
200 return m_pool_txs.count(txid);
201}
202
203bool TxPool::HaveTxFromPeer(const TxId &txid, NodeId peer) const {
204 auto it = m_pool_txs.find(txid);
205 return (it != m_pool_txs.end() && it->second.announcers.contains(peer));
206}
207
209 const auto tx_it = m_pool_txs.find(txid);
210 if (tx_it != m_pool_txs.end()) {
211 return tx_it->second.tx;
212 }
213
214 return nullptr;
215}
216
217std::vector<CTransactionRef>
219 std::vector<CTransactionRef> conflictingTxs;
220 for (const auto &txin : tx->vin) {
221 auto itByPrev = m_outpoint_to_tx_it.find(txin.prevout);
222 if (itByPrev == m_outpoint_to_tx_it.end()) {
223 continue;
224 }
225
226 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end();
227 ++mi) {
228 conflictingTxs.push_back((*mi)->second.tx);
229 }
230 }
231 return conflictingTxs;
232}
233
235 auto work_set_it = m_peer_work_set.find(peer);
236 if (work_set_it != m_peer_work_set.end()) {
237 auto &work_set = work_set_it->second;
238 while (!work_set.empty()) {
239 TxId txid = *work_set.begin();
240 work_set.erase(work_set.begin());
241
242 const auto tx_it = m_pool_txs.find(txid);
243 if (tx_it != m_pool_txs.end()) {
244 return tx_it->second.tx;
245 }
246 }
247 }
248 return nullptr;
249}
250
252 auto work_set_it = m_peer_work_set.find(peer);
253 if (work_set_it != m_peer_work_set.end()) {
254 auto &work_set = work_set_it->second;
255 return !work_set.empty();
256 }
257 return false;
258}
259
260void TxPool::EraseForBlock(const CBlock &block) {
261 if (m_pool_txs.empty()) {
262 return;
263 }
264
265 std::vector<TxId> vTxErase;
266
267 for (const CTransactionRef &ptx : block.vtx) {
268 const CTransaction &tx = *ptx;
269
270 // Which pool entries must we evict?
271 for (const auto &txin : tx.vin) {
272 auto itByPrev = m_outpoint_to_tx_it.find(txin.prevout);
273 if (itByPrev == m_outpoint_to_tx_it.end()) {
274 continue;
275 }
276
277 for (auto mi = itByPrev->second.begin();
278 mi != itByPrev->second.end(); ++mi) {
279 const CTransaction &orphanTx = *(*mi)->second.tx;
280 const TxId &txid = orphanTx.GetId();
281 vTxErase.push_back(txid);
282 }
283 }
284 }
285
286 // Erase transactions included or precluded by this block
287 if (vTxErase.size()) {
288 int nErased = 0;
289 for (const auto &txid : vTxErase) {
290 nErased += EraseTx(txid);
291 }
292 LogDebug(
294 "Erased %d %s transaction(s) included or conflicted by block\n",
295 nErased, txKind);
296 }
297}
298
299std::vector<CTransactionRef>
301 NodeId nodeid) const {
302 // First construct a vector of iterators to ensure we do not return
303 // duplicates of the same tx and so we can sort by nTimeExpire.
304 std::vector<PoolTxMap::iterator> iters;
305
306 // For each output, get all entries spending this prevout, filtering for
307 // ones from the specified peer.
308 for (unsigned int i = 0; i < parent->vout.size(); i++) {
309 const auto it_by_prev =
310 m_outpoint_to_tx_it.find(COutPoint(parent->GetId(), i));
311 if (it_by_prev != m_outpoint_to_tx_it.end()) {
312 for (const auto &elem : it_by_prev->second) {
313 if (elem->second.announcers.contains(nodeid)) {
314 iters.emplace_back(elem);
315 }
316 }
317 }
318 }
319
320 // Sort by address so that duplicates can be deleted. At the same time, sort
321 // so that more recent txs (which expire later) come first. Break ties
322 // based on address, as nTimeExpire is quantified in seconds and it is
323 // possible for txs to have the same expiry.
324 std::sort(iters.begin(), iters.end(), [](const auto &lhs, const auto &rhs) {
325 if (lhs->second.nTimeExpire == rhs->second.nTimeExpire) {
326 return &(*lhs) < &(*rhs);
327 }
328 return lhs->second.nTimeExpire > rhs->second.nTimeExpire;
329 });
330 // Erase duplicates
331 iters.erase(std::unique(iters.begin(), iters.end()), iters.end());
332
333 // Convert to a vector of CTransactionRef
334 std::vector<CTransactionRef> children_found;
335 children_found.reserve(iters.size());
336 for (const auto &child_iter : iters) {
337 children_found.emplace_back(child_iter->second.tx);
338 }
339 return children_found;
340}
341
342std::vector<TxPool::PoolTx> TxPool::GetPoolTransactions() const {
343 std::vector<PoolTx> ret;
344 ret.reserve(m_pool_txs.size());
345 for (const auto &o : m_pool_txs) {
346 ret.push_back({o.second.tx, o.second.announcers, o.second.nTimeExpire,
347 o.second.list_pos});
348 }
349 return ret;
350}
#define Assume(val)
Assume is the identity function.
Definition check.h:100
Definition block.h:60
std::vector< CTransactionRef > vtx
Definition block.h:63
Fast randomness source.
Definition random.h:411
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition random.h:266
void EraseForPeer(NodeId peer)
Maybe erase all txs announced by a peer (eg, after that peer disconnects).
Definition txpool.cpp:103
void EraseForBlock(const CBlock &block)
Erase all txs included in or invalidated by a new block.
Definition txpool.cpp:260
CTransactionRef GetTx(const TxId &txid) const
Definition txpool.cpp:208
const std::chrono::seconds expireInterval
Minimum time between transactions expire time checks.
Definition txpool.h:111
std::map< COutPoint, std::set< PoolTxMap ::iterator, IteratorComparator > > m_outpoint_to_tx_it
Index from the parents' COutPoint into the m_pool_txs.
Definition txpool.h:135
CTransactionRef GetTxToReconsider(NodeId peer)
Extract a transaction from a peer's work set.
Definition txpool.cpp:234
bool AddAnnouncer(const TxId &txid, NodeId peer)
Add an additional announcer to a tx if it exists.
Definition txpool.cpp:50
void AddChildrenToWorkSet(const CTransaction &tx, FastRandomContext &rng)
Add any tx that list a particular tx as a parent into the from peer's work set.
Definition txpool.cpp:162
const std::chrono::seconds expireTime
Expiration time for transactions.
Definition txpool.h:109
bool AddTx(const CTransactionRef &tx, NodeId peer)
Add a new transaction to the pool.
Definition txpool.cpp:15
NodeSeconds m_next_sweep
Timestamp for the next scheduled sweep of expired transactions.
Definition txpool.h:141
const std::string txKind
The transaction kind as string, used for logging.
Definition txpool.h:107
std::vector< CTransactionRef > GetConflictTxs(const CTransactionRef &tx) const
Definition txpool.cpp:218
std::map< NodeId, std::set< TxId > > m_peer_work_set
Which peer provided the transactions that need to be reconsidered.
Definition txpool.h:120
std::vector< PoolTxMap::iterator > m_txs_list
Pool transactions in vector for quick random eviction.
Definition txpool.h:138
unsigned int LimitTxs(unsigned int max_txs, FastRandomContext &rng)
Limit the txs to the given maximum.
Definition txpool.cpp:128
std::vector< CTransactionRef > GetChildrenFromSamePeer(const CTransactionRef &parent, NodeId nodeid) const
Get all children that spend from this tx and were received from nodeid.
Definition txpool.cpp:300
bool HaveTx(const TxId &txid) const
Check if we already have an the transaction.
Definition txpool.cpp:199
bool HaveTxToReconsider(NodeId peer)
Does this peer have any work to do?
Definition txpool.cpp:251
int EraseTx(const TxId &txid)
Erase a tx by txid.
Definition txpool.cpp:65
bool HaveTxFromPeer(const TxId &txid, NodeId peer) const
Check if a {tx, peer} exists in the pool.
Definition txpool.cpp:203
std::vector< PoolTx > GetPoolTransactions() const
Definition txpool.cpp:342
std::map< TxId, PoolTx > m_pool_txs
Map from txid to pool transaction record.
Definition txpool.h:117
constexpr uint8_t * begin()
Definition uint256.h:122
std::string ToString() const
Definition uint256.h:117
int64_t NodeId
Definition eviction.h:16
#define LogDebug(category,...)
Definition logging.h:446
@ TXPACKAGES
Definition logging.h:99
static constexpr unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
Definition policy.h:36
std::shared_ptr< const CTransaction > CTransactionRef
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition time.cpp:29
A TxId is the identifier of a transaction.
Definition txid.h:14
Allows providing pool transaction information externally.
Definition txpool.h:95
assert(!tx.IsCoinBase())