/tmp/bitcoin/src/txmempool.cpp
Line | Count | Source |
1 | | // Copyright (c) 2009-2010 Satoshi Nakamoto |
2 | | // Copyright (c) 2009-present The Bitcoin Core 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 <txmempool.h> |
7 | | |
8 | | #include <chain.h> |
9 | | #include <coins.h> |
10 | | #include <common/system.h> |
11 | | #include <consensus/consensus.h> |
12 | | #include <consensus/tx_verify.h> |
13 | | #include <consensus/validation.h> |
14 | | #include <policy/policy.h> |
15 | | #include <policy/settings.h> |
16 | | #include <random.h> |
17 | | #include <tinyformat.h> |
18 | | #include <util/check.h> |
19 | | #include <util/feefrac.h> |
20 | | #include <util/log.h> |
21 | | #include <util/moneystr.h> |
22 | | #include <util/overflow.h> |
23 | | #include <util/result.h> |
24 | | #include <util/time.h> |
25 | | #include <util/trace.h> |
26 | | #include <util/translation.h> |
27 | | #include <validationinterface.h> |
28 | | |
29 | | #include <algorithm> |
30 | | #include <cmath> |
31 | | #include <numeric> |
32 | | #include <optional> |
33 | | #include <ranges> |
34 | | #include <string_view> |
35 | | #include <utility> |
36 | | |
37 | | TRACEPOINT_SEMAPHORE(mempool, added); |
38 | | TRACEPOINT_SEMAPHORE(mempool, removed); |
39 | | |
40 | | bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) |
41 | 4.53k | { |
42 | 4.53k | AssertLockHeld(cs_main); |
43 | | // If there are relative lock times then the maxInputBlock will be set |
44 | | // If there are no relative lock times, the LockPoints don't depend on the chain |
45 | 4.53k | if (lp.maxInputBlock) { |
46 | | // Check whether active_chain is an extension of the block at which the LockPoints |
47 | | // calculation was valid. If not LockPoints are no longer valid |
48 | 4.53k | if (!active_chain.Contains(*lp.maxInputBlock)) { |
49 | 230 | return false; |
50 | 230 | } |
51 | 4.53k | } |
52 | | |
53 | | // LockPoints still valid |
54 | 4.30k | return true; |
55 | 4.53k | } |
56 | | |
57 | | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const |
58 | 8.71M | { |
59 | 8.71M | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret; |
60 | 8.71M | const auto& hash = entry.GetTx().GetHash(); |
61 | 8.71M | { |
62 | 8.71M | LOCK(cs); |
63 | 8.71M | auto iter = mapNextTx.lower_bound(COutPoint(hash, 0)); |
64 | 9.05M | for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) { |
65 | 341k | ret.emplace_back(*(iter->second)); |
66 | 341k | } |
67 | 8.71M | } |
68 | 8.71M | std::ranges::sort(ret, CompareIteratorByHash{}); |
69 | 8.71M | auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); }); |
70 | 8.71M | ret.erase(removed.begin(), removed.end()); |
71 | 8.71M | return ret; |
72 | 8.71M | } |
73 | | |
74 | | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const |
75 | 8.75M | { |
76 | 8.75M | LOCK(cs); |
77 | 8.75M | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret; |
78 | 8.75M | std::set<Txid> inputs; |
79 | 11.4M | for (const auto& txin : entry.GetTx().vin) { |
80 | 11.4M | inputs.insert(txin.prevout.hash); |
81 | 11.4M | } |
82 | 11.4M | for (const auto& hash : inputs) { |
83 | 11.4M | std::optional<txiter> piter = GetIter(hash); |
84 | 11.4M | if (piter) { |
85 | 341k | ret.emplace_back(**piter); |
86 | 341k | } |
87 | 11.4M | } |
88 | 8.75M | return ret; |
89 | 8.75M | } |
90 | | |
91 | | void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate) |
92 | 2.13k | { |
93 | 2.13k | AssertLockHeld(cs); |
94 | | |
95 | | // Iterate in reverse, so that whenever we are looking at a transaction |
96 | | // we are sure that all in-mempool descendants have already been processed. |
97 | 2.13k | for (const Txid& hash : vHashesToUpdate | std::views::reverse) { |
98 | | // calculate children from mapNextTx |
99 | 825 | txiter it = mapTx.find(hash); |
100 | 825 | if (it == mapTx.end()) { |
101 | 0 | continue; |
102 | 0 | } |
103 | 825 | auto iter = mapNextTx.lower_bound(COutPoint(hash, 0)); |
104 | 825 | { |
105 | 3.29k | for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) { |
106 | 2.46k | txiter childIter = iter->second; |
107 | 2.46k | assert(childIter != mapTx.end()); |
108 | | // Add dependencies that are discovered between transactions in the |
109 | | // block and transactions that were in the mempool to txgraph. |
110 | 2.46k | m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter); |
111 | 2.46k | } |
112 | 825 | } |
113 | 825 | } |
114 | | |
115 | 2.13k | auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits. |
116 | 2.13k | for (auto txptr : txs_to_remove) { |
117 | 0 | const CTxMemPoolEntry& entry = *(static_cast<const CTxMemPoolEntry*>(txptr)); |
118 | 0 | removeUnchecked(mapTx.iterator_to(entry), MemPoolRemovalReason::SIZELIMIT); |
119 | 0 | } |
120 | 2.13k | } |
121 | | |
122 | | bool CTxMemPool::HasDescendants(const Txid& txid) const |
123 | 244 | { |
124 | 244 | LOCK(cs); |
125 | 244 | auto entry = GetEntry(txid); |
126 | 244 | if (!entry) return false; |
127 | 230 | return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1; |
128 | 244 | } |
129 | | |
130 | | CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const |
131 | 1.94k | { |
132 | 1.94k | auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN); |
133 | 1.94k | setEntries ret; |
134 | 1.94k | if (ancestors.size() > 0) { |
135 | 14.1k | for (auto ancestor : ancestors) { |
136 | 14.1k | if (ancestor != &entry) { |
137 | 13.4k | ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor))); |
138 | 13.4k | } |
139 | 14.1k | } |
140 | 615 | return ret; |
141 | 615 | } |
142 | | |
143 | | // If we didn't get anything back, the transaction is not in the graph. |
144 | | // Find each parent and call GetAncestors on each. |
145 | 1.33k | setEntries staged_parents; |
146 | 1.33k | const CTransaction &tx = entry.GetTx(); |
147 | | |
148 | | // Get parents of this transaction that are in the mempool |
149 | 3.01k | for (unsigned int i = 0; i < tx.vin.size(); i++) { |
150 | 1.68k | std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash); |
151 | 1.68k | if (piter) { |
152 | 240 | staged_parents.insert(*piter); |
153 | 240 | } |
154 | 1.68k | } |
155 | | |
156 | 1.33k | for (const auto& parent : staged_parents) { |
157 | 214 | auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN); |
158 | 600 | for (auto ancestor : parent_ancestors) { |
159 | 600 | ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor))); |
160 | 600 | } |
161 | 214 | } |
162 | | |
163 | 1.33k | return ret; |
164 | 1.94k | } |
165 | | |
166 | | static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error) |
167 | 1.30k | { |
168 | 1.30k | opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000); |
169 | 1.30k | int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40; |
170 | 1.30k | if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) { |
171 | 1 | error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0)); |
172 | 1 | } |
173 | 1.30k | return std::move(opts); |
174 | 1.30k | } |
175 | | |
176 | | CTxMemPool::CTxMemPool(Options opts, bilingual_str& error) |
177 | 1.30k | : m_opts{Flatten(std::move(opts), error)} |
178 | 1.30k | { |
179 | 1.30k | m_txgraph = MakeTxGraph( |
180 | 1.30k | /*max_cluster_count=*/m_opts.limits.cluster_count, |
181 | 1.30k | /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR, |
182 | 1.30k | /*acceptable_cost=*/ACCEPTABLE_COST, |
183 | 57.3M | /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept { |
184 | 57.3M | const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash(); |
185 | 57.3M | const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash(); |
186 | 57.3M | return txid_a <=> txid_b; |
187 | 57.3M | }); |
188 | 1.30k | } |
189 | | |
190 | | bool CTxMemPool::isSpent(const COutPoint& outpoint) const |
191 | 54 | { |
192 | 54 | LOCK(cs); |
193 | 54 | return mapNextTx.count(outpoint); |
194 | 54 | } |
195 | | |
196 | | unsigned int CTxMemPool::GetTransactionsUpdated() const |
197 | 94 | { |
198 | 94 | return nTransactionsUpdated; |
199 | 94 | } |
200 | | |
201 | | void CTxMemPool::AddTransactionsUpdated(unsigned int n) |
202 | 116k | { |
203 | 116k | nTransactionsUpdated += n; |
204 | 116k | } |
205 | | |
206 | | void CTxMemPool::Apply(ChangeSet* changeset) |
207 | 45.7k | { |
208 | 45.7k | AssertLockHeld(cs); |
209 | 45.7k | m_txgraph->CommitStaging(); |
210 | | |
211 | 45.7k | RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED); |
212 | | |
213 | 91.5k | for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) { |
214 | 45.8k | auto tx_entry = changeset->m_entry_vec[i]; |
215 | | // First splice this entry into mapTx. |
216 | 45.8k | auto node_handle = changeset->m_to_add.extract(tx_entry); |
217 | 45.8k | auto result = mapTx.insert(std::move(node_handle)); |
218 | | |
219 | 45.8k | Assume(result.inserted); |
220 | 45.8k | txiter it = result.position; |
221 | | |
222 | 45.8k | addNewTransaction(it); |
223 | 45.8k | } |
224 | 45.7k | if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) { |
225 | 0 | LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s)."); |
226 | 0 | } |
227 | 45.7k | } |
228 | | |
229 | | void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit) |
230 | 45.8k | { |
231 | 45.8k | const CTxMemPoolEntry& entry = *newit; |
232 | | |
233 | | // Update cachedInnerUsage to include contained transaction's usage. |
234 | | // (When we update the entry for in-mempool parents, memory usage will be |
235 | | // further updated.) |
236 | 45.8k | cachedInnerUsage += entry.DynamicMemoryUsage(); |
237 | | |
238 | 45.8k | const CTransaction& tx = newit->GetTx(); |
239 | 104k | for (unsigned int i = 0; i < tx.vin.size(); i++) { |
240 | 59.0k | mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit)); |
241 | 59.0k | } |
242 | | // Don't bother worrying about child transactions of this one. |
243 | | // Normal case of a new transaction arriving is that there can't be any |
244 | | // children, because such children would be orphans. |
245 | | // An exception to that is if a transaction enters that used to be in a block. |
246 | | // In that case, our disconnect block logic will call UpdateTransactionsFromBlock |
247 | | // to clean up the mess we're leaving here. |
248 | | |
249 | 45.8k | nTransactionsUpdated++; |
250 | 45.8k | totalTxSize += entry.GetTxSize(); |
251 | 45.8k | m_total_fee += entry.GetFee(); |
252 | | |
253 | 45.8k | txns_randomized.emplace_back(tx.GetWitnessHash(), newit); |
254 | 45.8k | newit->idx_randomized = txns_randomized.size() - 1; |
255 | | |
256 | 45.8k | TRACEPOINT(mempool, added, |
257 | 45.8k | entry.GetTx().GetHash().data(), |
258 | 45.8k | entry.GetTxSize(), |
259 | 45.8k | entry.GetFee() |
260 | 45.8k | ); |
261 | 45.8k | } |
262 | | |
263 | | void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason) |
264 | 25.2k | { |
265 | | // We increment mempool sequence value no matter removal reason |
266 | | // even if not directly reported below. |
267 | 25.2k | uint64_t mempool_sequence = GetAndIncrementSequence(); |
268 | | |
269 | 25.2k | if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) { |
270 | | // Notify clients that a transaction has been removed from the mempool |
271 | | // for any reason except being included in a block. Clients interested |
272 | | // in transactions included in blocks can subscribe to the BlockConnected |
273 | | // notification. |
274 | 2.12k | m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence); |
275 | 2.12k | } |
276 | 25.2k | TRACEPOINT(mempool, removed, |
277 | 25.2k | it->GetTx().GetHash().data(), |
278 | 25.2k | RemovalReasonToString(reason).c_str(), |
279 | 25.2k | it->GetTxSize(), |
280 | 25.2k | it->GetFee(), |
281 | 25.2k | std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count() |
282 | 25.2k | ); |
283 | | |
284 | 25.2k | for (const CTxIn& txin : it->GetTx().vin) |
285 | 37.2k | mapNextTx.erase(txin.prevout); |
286 | | |
287 | 25.2k | RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */); |
288 | | |
289 | 25.2k | if (txns_randomized.size() > 1) { |
290 | | // Remove entry from txns_randomized by replacing it with the back and deleting the back. |
291 | 23.2k | txns_randomized[it->idx_randomized] = std::move(txns_randomized.back()); |
292 | 23.2k | txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized; |
293 | 23.2k | txns_randomized.pop_back(); |
294 | 23.2k | if (txns_randomized.size() * 2 < txns_randomized.capacity()) { |
295 | 1.36k | txns_randomized.shrink_to_fit(); |
296 | 1.36k | } |
297 | 23.2k | } else { |
298 | 1.91k | txns_randomized.clear(); |
299 | 1.91k | } |
300 | | |
301 | 25.2k | totalTxSize -= it->GetTxSize(); |
302 | 25.2k | m_total_fee -= it->GetFee(); |
303 | 25.2k | cachedInnerUsage -= it->DynamicMemoryUsage(); |
304 | 25.2k | mapTx.erase(it); |
305 | 25.2k | nTransactionsUpdated++; |
306 | 25.2k | } |
307 | | |
308 | | // Calculates descendants of given entry and adds to setDescendants. |
309 | | void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const |
310 | 80.0k | { |
311 | 80.0k | (void)CalculateDescendants(*entryit, setDescendants); |
312 | 80.0k | return; |
313 | 80.0k | } |
314 | | |
315 | | CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const |
316 | 80.1k | { |
317 | 286k | for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) { |
318 | 286k | setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx))); |
319 | 286k | } |
320 | 80.1k | return mapTx.iterator_to(entry); |
321 | 80.1k | } |
322 | | |
323 | | void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason) |
324 | 166 | { |
325 | 166 | AssertLockHeld(cs); |
326 | 166 | Assume(!m_have_changeset); |
327 | 166 | auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN); |
328 | 331 | for (auto tx: descendants) { |
329 | 331 | removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason); |
330 | 331 | } |
331 | 166 | } |
332 | | |
333 | | void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason) |
334 | 15.4k | { |
335 | | // Remove transaction from memory pool |
336 | 15.4k | AssertLockHeld(cs); |
337 | 15.4k | Assume(!m_have_changeset); |
338 | 15.4k | txiter origit = mapTx.find(origTx.GetHash()); |
339 | 15.4k | if (origit != mapTx.end()) { |
340 | 7 | removeRecursive(origit, reason); |
341 | 15.4k | } else { |
342 | | // When recursively removing but origTx isn't in the mempool |
343 | | // be sure to remove any descendants that are in the pool. This can |
344 | | // happen during chain re-orgs if origTx isn't re-accepted into |
345 | | // the mempool for any reason. |
346 | 15.4k | auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0)); |
347 | 15.4k | std::vector<const TxGraph::Ref*> to_remove; |
348 | 15.4k | while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) { |
349 | 74 | to_remove.emplace_back(&*(iter->second)); |
350 | 74 | ++iter; |
351 | 74 | } |
352 | 15.4k | auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN); |
353 | 15.4k | for (auto ref : all_removes) { |
354 | 77 | auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)); |
355 | 77 | removeUnchecked(tx, reason); |
356 | 77 | } |
357 | 15.4k | } |
358 | 15.4k | } |
359 | | |
360 | | void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature) |
361 | 2.13k | { |
362 | | // Remove transactions spending a coinbase which are now immature and no-longer-final transactions |
363 | 2.13k | AssertLockHeld(cs); |
364 | 2.13k | AssertLockHeld(::cs_main); |
365 | 2.13k | Assume(!m_have_changeset); |
366 | | |
367 | 2.13k | std::vector<const TxGraph::Ref*> to_remove; |
368 | 4.42k | for (txiter it = mapTx.begin(); it != mapTx.end(); it++) { |
369 | 2.28k | if (check_final_and_mature(it)) { |
370 | 15 | to_remove.emplace_back(&*it); |
371 | 15 | } |
372 | 2.28k | } |
373 | | |
374 | 2.13k | auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN); |
375 | | |
376 | 2.13k | for (auto ref : all_to_remove) { |
377 | 36 | auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)); |
378 | 36 | removeUnchecked(it, MemPoolRemovalReason::REORG); |
379 | 36 | } |
380 | 4.38k | for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) { |
381 | 2.24k | assert(TestLockPointValidity(chain, it->GetLockPoints())); |
382 | 2.24k | } |
383 | 2.13k | if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) { |
384 | 0 | LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg."); |
385 | 0 | } |
386 | 2.13k | } |
387 | | |
388 | | void CTxMemPool::removeConflicts(const CTransaction &tx) |
389 | 35.6k | { |
390 | | // Remove transactions which depend on inputs of tx, recursively |
391 | 35.6k | AssertLockHeld(cs); |
392 | 47.6k | for (const CTxIn &txin : tx.vin) { |
393 | 47.6k | auto it = mapNextTx.find(txin.prevout); |
394 | 47.6k | if (it != mapNextTx.end()) { |
395 | 159 | const CTransaction &txConflict = it->second->GetTx(); |
396 | 159 | if (Assume(txConflict.GetHash() != tx.GetHash())) |
397 | 159 | { |
398 | 159 | ClearPrioritisation(txConflict.GetHash()); |
399 | 159 | removeRecursive(it->second, MemPoolRemovalReason::CONFLICT); |
400 | 159 | } |
401 | 159 | } |
402 | 47.6k | } |
403 | 35.6k | } |
404 | | |
405 | | std::vector<RemovedMempoolTransactionInfo> CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx) |
406 | 105k | { |
407 | | // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic |
408 | 105k | AssertLockHeld(cs); |
409 | 105k | Assume(!m_have_changeset); |
410 | 105k | std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block; |
411 | 105k | if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) { |
412 | 7.38k | txs_removed_for_block.reserve(vtx.size()); |
413 | 35.6k | for (const auto& tx : vtx) { |
414 | 35.6k | txiter it = mapTx.find(tx->GetHash()); |
415 | 35.6k | if (it != mapTx.end()) { |
416 | 23.0k | txs_removed_for_block.emplace_back(*it); |
417 | 23.0k | removeUnchecked(it, MemPoolRemovalReason::BLOCK); |
418 | 23.0k | } |
419 | 35.6k | removeConflicts(*tx); |
420 | 35.6k | ClearPrioritisation(tx->GetHash()); |
421 | 35.6k | } |
422 | 7.38k | } |
423 | 105k | lastRollingFeeUpdate = GetTime(); |
424 | 105k | blockSinceLastRollingFeeBump = true; |
425 | 105k | if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) { |
426 | 0 | LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block."); |
427 | 0 | } |
428 | 105k | return txs_removed_for_block; |
429 | 105k | } |
430 | | |
431 | | void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const |
432 | 147k | { |
433 | 147k | if (m_opts.check_ratio == 0) return; |
434 | | |
435 | 145k | if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return; |
436 | | |
437 | 145k | AssertLockHeld(::cs_main); |
438 | 145k | LOCK(cs); |
439 | 145k | LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size()); |
440 | | |
441 | 145k | uint64_t checkTotal = 0; |
442 | 145k | CAmount check_total_fee{0}; |
443 | 145k | CAmount check_total_modified_fee{0}; |
444 | 145k | int64_t check_total_adjusted_weight{0}; |
445 | 145k | uint64_t innerUsage = 0; |
446 | | |
447 | 145k | assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN)); |
448 | 145k | m_txgraph->SanityCheck(); |
449 | | |
450 | 145k | CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip)); |
451 | | |
452 | 145k | const auto score_with_topo{GetSortedScoreWithTopology()}; |
453 | | |
454 | | // Number of chunks is bounded by number of transactions. |
455 | 145k | const auto diagram{GetFeerateDiagram()}; |
456 | 145k | assert(diagram.size() <= score_with_topo.size() + 1); |
457 | 145k | assert(diagram.size() >= 1); |
458 | | |
459 | 145k | std::optional<txiter> last_iter = std::nullopt; |
460 | 145k | auto diagram_iter = diagram.cbegin(); |
461 | | |
462 | 8.70M | for (const auto& it : score_with_topo) { |
463 | | // GetSortedScoreWithTopology() contains the same chunks as the feerate |
464 | | // diagram. We do not know where the chunk boundaries are, but we can |
465 | | // check that there are points at which they match the cumulative fee |
466 | | // and weight. |
467 | | // The feerate diagram should never get behind the current transaction |
468 | | // size totals. |
469 | 8.70M | assert(diagram_iter->size >= check_total_adjusted_weight); |
470 | 8.70M | if (diagram_iter->fee == check_total_modified_fee && |
471 | 8.70M | diagram_iter->size == check_total_adjusted_weight) { |
472 | 8.55M | ++diagram_iter; |
473 | 8.55M | } |
474 | 8.70M | checkTotal += it->GetTxSize(); |
475 | 8.70M | check_total_adjusted_weight += it->GetAdjustedWeight(); |
476 | 8.70M | check_total_fee += it->GetFee(); |
477 | 8.70M | check_total_modified_fee += it->GetModifiedFee(); |
478 | 8.70M | innerUsage += it->DynamicMemoryUsage(); |
479 | 8.70M | const CTransaction& tx = it->GetTx(); |
480 | | |
481 | 8.70M | if (last_iter) { |
482 | 8.67M | assert(m_txgraph->CompareMainOrder(**last_iter, *it) < 0); |
483 | 8.67M | } |
484 | 8.70M | last_iter = it; |
485 | | |
486 | 8.70M | std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck; |
487 | 8.70M | std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored; |
488 | 11.4M | for (const CTxIn &txin : tx.vin) { |
489 | | // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's. |
490 | 11.4M | indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash); |
491 | 11.4M | if (it2 != mapTx.end()) { |
492 | 333k | const CTransaction& tx2 = it2->GetTx(); |
493 | 333k | assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull()); |
494 | 333k | setParentCheck.insert(*it2); |
495 | 333k | } |
496 | | // We are iterating through the mempool entries sorted |
497 | | // topologically and by mining score. All parents must have been |
498 | | // checked before their children and their coins added to the |
499 | | // mempoolDuplicate coins cache. |
500 | 11.4M | assert(mempoolDuplicate.HaveCoin(txin.prevout)); |
501 | | // Check whether its inputs are marked in mapNextTx. |
502 | 11.4M | auto it3 = mapNextTx.find(txin.prevout); |
503 | 11.4M | assert(it3 != mapNextTx.end()); |
504 | 11.4M | assert(it3->first == &txin.prevout); |
505 | 11.4M | assert(&it3->second->GetTx() == &tx); |
506 | 11.4M | } |
507 | 8.70M | auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool { |
508 | 667k | return a.GetTx().GetHash() == b.GetTx().GetHash(); |
509 | 667k | }; |
510 | 8.70M | for (auto &txentry : GetParents(*it)) { |
511 | 333k | setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get())); |
512 | 333k | } |
513 | 8.70M | assert(setParentCheck.size() == setParentsStored.size()); |
514 | 8.70M | assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp)); |
515 | | |
516 | | // Check children against mapNextTx |
517 | 8.70M | std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck; |
518 | 8.70M | std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored; |
519 | 8.70M | auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0)); |
520 | 9.03M | for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) { |
521 | 333k | txiter childit = iter->second; |
522 | 333k | assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions |
523 | 333k | setChildrenCheck.insert(*childit); |
524 | 333k | } |
525 | 8.70M | for (auto &txentry : GetChildren(*it)) { |
526 | 333k | setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get())); |
527 | 333k | } |
528 | 8.70M | assert(setChildrenCheck.size() == setChildrenStored.size()); |
529 | 8.70M | assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp)); |
530 | | |
531 | 8.70M | TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass |
532 | 8.70M | CAmount txfee = 0; |
533 | 8.70M | assert(!tx.IsCoinBase()); |
534 | 8.70M | assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee)); |
535 | 11.4M | for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout); |
536 | 8.70M | AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max()); |
537 | 8.70M | } |
538 | 11.5M | for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) { |
539 | 11.4M | indexed_transaction_set::const_iterator it2 = it->second; |
540 | 11.4M | assert(it2 != mapTx.end()); |
541 | 11.4M | } |
542 | | |
543 | 145k | ++diagram_iter; |
544 | 145k | assert(diagram_iter == diagram.cend()); |
545 | | |
546 | 145k | assert(totalTxSize == checkTotal); |
547 | 145k | assert(m_total_fee == check_total_fee); |
548 | 145k | assert(diagram.back().fee == check_total_modified_fee); |
549 | 145k | assert(diagram.back().size == check_total_adjusted_weight); |
550 | 145k | assert(innerUsage == cachedInnerUsage); |
551 | 145k | } |
552 | | |
553 | | std::vector<CTxMemPool::txiter> CTxMemPool::ExtractBestByMiningScoreWithTopology(std::vector<Wtxid>& wtxids, size_t n_to_sort) const |
554 | 57.1k | { |
555 | | /* This function takes a vector of `wtxids`, and returns the |
556 | | * best mempool entries corresponding to those `wtxids` (by mining |
557 | | * score/topology). It updates the input `wtxids` so that multiple |
558 | | * calls with the same vector will drain that vector to empty. |
559 | | * |
560 | | * It operates under the following constraints: |
561 | | * - wtxids that do not correspond to a mempool entry are dropped |
562 | | * - the return vector contains no duplicates, either with itself |
563 | | * or with the updated `wtxids` input. |
564 | | * - the return vector will have `n_to_sort` entries (or `wtxids` |
565 | | will become empty). |
566 | | * - the `wtxids` vector will be reduced by at least `n_to_sort` |
567 | | * entries (or will become empty). |
568 | | */ |
569 | | |
570 | 318k | auto cmp = [&](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { return m_txgraph->CompareMainOrder(*a, *b) < 0; }; |
571 | | |
572 | 57.1k | std::vector<txiter> res; |
573 | | |
574 | 57.1k | n_to_sort = std::min(wtxids.size(), n_to_sort); |
575 | 57.1k | if (n_to_sort > 0) { |
576 | 57.1k | res.reserve(wtxids.size()); |
577 | 57.1k | std::sort(wtxids.begin(), wtxids.end()); |
578 | 188k | for (auto it = wtxids.begin(); it != wtxids.end(); ++it) { |
579 | | // skip duplicates |
580 | 131k | auto itnext = it + 1; |
581 | 131k | if (itnext != wtxids.end() && *it == *itnext) continue; |
582 | | |
583 | 124k | if (auto i{GetIter(*it)}; i.has_value()) { |
584 | 115k | res.push_back(i.value()); |
585 | 115k | } |
586 | 124k | } |
587 | 57.1k | wtxids.clear(); |
588 | | |
589 | 57.1k | if (!res.empty()) { |
590 | 56.8k | auto begin = res.begin(); |
591 | 56.8k | auto end = res.end(); |
592 | 56.8k | auto middle = end; |
593 | 56.8k | if (n_to_sort >= res.size()) { |
594 | | // use regular sort when sorting everything |
595 | 56.7k | std::sort(begin, end, cmp); |
596 | 56.7k | } else { |
597 | 133 | middle = begin + n_to_sort; |
598 | 133 | std::partial_sort(begin, middle, end, cmp); |
599 | 133 | } |
600 | 56.8k | auto it = middle; |
601 | 77.0k | while (it != end) { |
602 | 20.1k | wtxids.push_back((*it)->GetTx().GetWitnessHash()); |
603 | 20.1k | ++it; |
604 | 20.1k | } |
605 | 56.8k | res.erase(middle, end); |
606 | 56.8k | } |
607 | 57.1k | } |
608 | 57.1k | return res; |
609 | 57.1k | } |
610 | | |
611 | | std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const |
612 | 156k | { |
613 | 156k | std::vector<indexed_transaction_set::const_iterator> iters; |
614 | 156k | AssertLockHeld(cs); |
615 | | |
616 | 156k | iters.reserve(mapTx.size()); |
617 | | |
618 | 9.11M | for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) { |
619 | 8.96M | iters.push_back(mi); |
620 | 8.96M | } |
621 | 99.5M | std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { |
622 | 99.5M | return m_txgraph->CompareMainOrder(*a, *b) < 0; |
623 | 99.5M | }); |
624 | 156k | return iters; |
625 | 156k | } |
626 | | |
627 | | std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const |
628 | 9.45k | { |
629 | 9.45k | AssertLockHeld(cs); |
630 | | |
631 | 9.45k | std::vector<CTxMemPoolEntryRef> ret; |
632 | 9.45k | ret.reserve(mapTx.size()); |
633 | 255k | for (const auto& it : GetSortedScoreWithTopology()) { |
634 | 255k | ret.emplace_back(*it); |
635 | 255k | } |
636 | 9.45k | return ret; |
637 | 9.45k | } |
638 | | |
639 | | std::vector<TxMempoolInfo> CTxMemPool::infoAll() const |
640 | 989 | { |
641 | 989 | LOCK(cs); |
642 | 989 | auto iters = GetSortedScoreWithTopology(); |
643 | | |
644 | 989 | std::vector<TxMempoolInfo> ret; |
645 | 989 | ret.reserve(mapTx.size()); |
646 | 1.34k | for (auto it : iters) { |
647 | 1.34k | ret.push_back(GetInfo(it)); |
648 | 1.34k | } |
649 | | |
650 | 989 | return ret; |
651 | 989 | } |
652 | | |
653 | | const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const |
654 | 2.94k | { |
655 | 2.94k | AssertLockHeld(cs); |
656 | 2.94k | const auto i = mapTx.find(txid); |
657 | 2.94k | return i == mapTx.end() ? nullptr : &(*i); |
658 | 2.94k | } |
659 | | |
660 | | CTransactionRef CTxMemPool::get(const Txid& hash) const |
661 | 235k | { |
662 | 235k | LOCK(cs); |
663 | 235k | indexed_transaction_set::const_iterator i = mapTx.find(hash); |
664 | 235k | if (i == mapTx.end()) |
665 | 199k | return nullptr; |
666 | 36.2k | return i->GetSharedTx(); |
667 | 235k | } |
668 | | |
669 | | CTransactionRef CTxMemPool::get(const Wtxid& hash) const |
670 | 8 | { |
671 | 8 | LOCK(cs); |
672 | 8 | const auto& wtxid_map{mapTx.get<index_by_wtxid>()}; |
673 | 8 | const auto it{wtxid_map.find(hash)}; |
674 | 8 | if (it == wtxid_map.end()) return nullptr; |
675 | 4 | return it->GetSharedTx(); |
676 | 8 | } |
677 | | |
678 | | void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta) |
679 | 769 | { |
680 | 769 | { |
681 | 769 | LOCK(cs); |
682 | 769 | CAmount &delta = mapDeltas[hash]; |
683 | 769 | delta = SaturatingAdd(delta, nFeeDelta); |
684 | 769 | txiter it = mapTx.find(hash); |
685 | 769 | if (it != mapTx.end()) { |
686 | | // PrioritiseTransaction calls stack on previous ones. Set the new |
687 | | // transaction fee to be current modified fee + feedelta. |
688 | 262 | it->UpdateModifiedFee(nFeeDelta); |
689 | 262 | m_txgraph->SetTransactionFee(*it, it->GetModifiedFee()); |
690 | 262 | ++nTransactionsUpdated; |
691 | 262 | } |
692 | 769 | if (delta == 0) { |
693 | 9 | mapDeltas.erase(hash); |
694 | 9 | LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : ""); |
695 | 760 | } else { |
696 | 760 | LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n", |
697 | 760 | hash.ToString(), |
698 | 760 | it == mapTx.end() ? "not " : "", |
699 | 760 | FormatMoney(nFeeDelta), |
700 | 760 | FormatMoney(delta)); |
701 | 760 | } |
702 | 769 | } |
703 | 769 | } |
704 | | |
705 | | void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const |
706 | 68.7k | { |
707 | 68.7k | AssertLockHeld(cs); |
708 | 68.7k | std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash); |
709 | 68.7k | if (pos == mapDeltas.end()) |
710 | 68.6k | return; |
711 | 41 | const CAmount &delta = pos->second; |
712 | 41 | nFeeDelta += delta; |
713 | 41 | } |
714 | | |
715 | | void CTxMemPool::ClearPrioritisation(const Txid& hash) |
716 | 35.7k | { |
717 | 35.7k | AssertLockHeld(cs); |
718 | 35.7k | mapDeltas.erase(hash); |
719 | 35.7k | } |
720 | | |
721 | | std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const |
722 | 31 | { |
723 | 31 | AssertLockNotHeld(cs); |
724 | 31 | LOCK(cs); |
725 | 31 | std::vector<delta_info> result; |
726 | 31 | result.reserve(mapDeltas.size()); |
727 | 31 | for (const auto& [txid, delta] : mapDeltas) { |
728 | 30 | const auto iter{mapTx.find(txid)}; |
729 | 30 | const bool in_mempool{iter != mapTx.end()}; |
730 | 30 | std::optional<CAmount> modified_fee; |
731 | 30 | if (in_mempool) modified_fee = iter->GetModifiedFee(); |
732 | 30 | result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid}); |
733 | 30 | } |
734 | 31 | return result; |
735 | 31 | } |
736 | | |
737 | | const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const |
738 | 118k | { |
739 | 118k | const auto it = mapNextTx.find(prevout); |
740 | 118k | return it == mapNextTx.end() ? nullptr : &(it->second->GetTx()); |
741 | 118k | } |
742 | | |
743 | | std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const |
744 | 11.6M | { |
745 | 11.6M | AssertLockHeld(cs); |
746 | 11.6M | auto it = mapTx.find(txid); |
747 | 11.6M | return it != mapTx.end() ? std::make_optional(it) : std::nullopt; |
748 | 11.6M | } |
749 | | |
750 | | std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const |
751 | 138k | { |
752 | 138k | AssertLockHeld(cs); |
753 | 138k | auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))}; |
754 | 138k | return it != mapTx.end() ? std::make_optional(it) : std::nullopt; |
755 | 138k | } |
756 | | |
757 | | CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const |
758 | 45.9k | { |
759 | 45.9k | CTxMemPool::setEntries ret; |
760 | 45.9k | for (const auto& h : hashes) { |
761 | 2.35k | const auto mi = GetIter(h); |
762 | 2.35k | if (mi) ret.insert(*mi); |
763 | 2.35k | } |
764 | 45.9k | return ret; |
765 | 45.9k | } |
766 | | |
767 | | std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const |
768 | 2 | { |
769 | 2 | AssertLockHeld(cs); |
770 | 2 | std::vector<txiter> ret; |
771 | 2 | ret.reserve(txids.size()); |
772 | 563 | for (const auto& txid : txids) { |
773 | 563 | const auto it{GetIter(txid)}; |
774 | 563 | if (!it) return {}; |
775 | 563 | ret.push_back(*it); |
776 | 563 | } |
777 | 2 | return ret; |
778 | 2 | } |
779 | | |
780 | | bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const |
781 | 26.8k | { |
782 | 60.7k | for (unsigned int i = 0; i < tx.vin.size(); i++) |
783 | 37.6k | if (exists(tx.vin[i].prevout.hash)) |
784 | 3.78k | return false; |
785 | 23.1k | return true; |
786 | 26.8k | } |
787 | | |
788 | 54.3k | CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { } |
789 | | |
790 | | std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const |
791 | 74.8k | { |
792 | | // Check to see if the inputs are made available by another tx in the package. |
793 | | // These Coins would not be available in the underlying CoinsView. |
794 | 74.8k | if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) { |
795 | 614 | return it->second; |
796 | 614 | } |
797 | | |
798 | | // If an entry in the mempool exists, always return that one, as it's guaranteed to never |
799 | | // conflict with the underlying cache, and it cannot have pruned entries (as it contains full) |
800 | | // transactions. First checking the underlying cache risks returning a pruned entry instead. |
801 | 74.2k | CTransactionRef ptx = mempool.get(outpoint.hash); |
802 | 74.2k | if (ptx) { |
803 | 9.06k | if (outpoint.n < ptx->vout.size()) { |
804 | 9.06k | Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false); |
805 | 9.06k | m_non_base_coins.emplace(outpoint); |
806 | 9.06k | return coin; |
807 | 9.06k | } |
808 | 0 | return std::nullopt; |
809 | 9.06k | } |
810 | 65.2k | return base->GetCoin(outpoint); |
811 | 74.2k | } |
812 | | |
813 | | void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx) |
814 | 779 | { |
815 | 1.59k | for (unsigned int n = 0; n < tx->vout.size(); ++n) { |
816 | 816 | m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false)); |
817 | 816 | m_non_base_coins.emplace(tx->GetHash(), n); |
818 | 816 | } |
819 | 779 | } |
820 | | void CCoinsViewMemPool::Reset() |
821 | 79.0k | { |
822 | 79.0k | m_temp_added.clear(); |
823 | 79.0k | m_non_base_coins.clear(); |
824 | 79.0k | } |
825 | | |
826 | 473k | size_t CTxMemPool::DynamicMemoryUsage() const { |
827 | 473k | LOCK(cs); |
828 | | // Estimate the overhead of mapTx to be 9 pointers (3 pointers per index) + an allocation, as no exact formula for boost::multi_index_contained is implemented. |
829 | 473k | return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage; |
830 | 473k | } |
831 | | |
832 | 38.8k | void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) { |
833 | 38.8k | LOCK(cs); |
834 | | |
835 | 38.8k | if (m_unbroadcast_txids.erase(txid)) |
836 | 12.8k | { |
837 | 12.8k | LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : "")); |
838 | 12.8k | } |
839 | 38.8k | } |
840 | | |
841 | 73.8k | void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) { |
842 | 73.8k | AssertLockHeld(cs); |
843 | 73.8k | for (txiter it : stage) { |
844 | 1.63k | removeUnchecked(it, reason); |
845 | 1.63k | } |
846 | 73.8k | } |
847 | | |
848 | | bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx) |
849 | 3.61k | { |
850 | 3.61k | LOCK(cs); |
851 | | // Use ChangeSet interface to check whether the cluster count |
852 | | // limits would be violated. Note that the changeset will be destroyed |
853 | | // when it goes out of scope. |
854 | 3.61k | auto changeset = GetChangeSet(); |
855 | 3.61k | (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{}); |
856 | 3.61k | return changeset->CheckMemPoolPolicyLimits(); |
857 | 3.61k | } |
858 | | |
859 | | int CTxMemPool::Expire(std::chrono::seconds time) |
860 | 28.0k | { |
861 | 28.0k | AssertLockHeld(cs); |
862 | 28.0k | Assume(!m_have_changeset); |
863 | 28.0k | indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin(); |
864 | 28.0k | setEntries toremove; |
865 | 28.1k | while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) { |
866 | 22 | toremove.insert(mapTx.project<0>(it)); |
867 | 22 | it++; |
868 | 22 | } |
869 | 28.0k | setEntries stage; |
870 | 28.0k | for (txiter removeit : toremove) { |
871 | 22 | CalculateDescendants(removeit, stage); |
872 | 22 | } |
873 | 28.0k | RemoveStaged(stage, MemPoolRemovalReason::EXPIRY); |
874 | 28.0k | return stage.size(); |
875 | 28.0k | } |
876 | | |
877 | 386k | CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const { |
878 | 386k | LOCK(cs); |
879 | 386k | if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0) |
880 | 386k | return CFeeRate(llround(rollingMinimumFeeRate)); |
881 | | |
882 | 142 | int64_t time = GetTime(); |
883 | 142 | if (time > lastRollingFeeUpdate + 10) { |
884 | 6 | double halflife = ROLLING_FEE_HALFLIFE; |
885 | 6 | if (DynamicMemoryUsage() < sizelimit / 4) |
886 | 1 | halflife /= 4; |
887 | 5 | else if (DynamicMemoryUsage() < sizelimit / 2) |
888 | 1 | halflife /= 2; |
889 | | |
890 | 6 | rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife); |
891 | 6 | lastRollingFeeUpdate = time; |
892 | | |
893 | 6 | if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) { |
894 | 1 | rollingMinimumFeeRate = 0; |
895 | 1 | return CFeeRate(0); |
896 | 1 | } |
897 | 6 | } |
898 | 141 | return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate); |
899 | 142 | } |
900 | | |
901 | 39 | void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) { |
902 | 39 | AssertLockHeld(cs); |
903 | 39 | if (rate.GetFeePerK() > rollingMinimumFeeRate) { |
904 | 37 | rollingMinimumFeeRate = rate.GetFeePerK(); |
905 | 37 | blockSinceLastRollingFeeBump = false; |
906 | 37 | } |
907 | 39 | } |
908 | | |
909 | 28.0k | void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) { |
910 | 28.0k | AssertLockHeld(cs); |
911 | 28.0k | Assume(!m_have_changeset); |
912 | | |
913 | 28.0k | unsigned nTxnRemoved = 0; |
914 | 28.0k | CFeeRate maxFeeRateRemoved(0); |
915 | | |
916 | 28.1k | while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) { |
917 | 39 | const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk(); |
918 | 39 | FeePerVSize feerate = ToFeePerVSize(feeperweight); |
919 | 39 | CFeeRate removed{feerate.fee, feerate.size}; |
920 | | |
921 | | // We set the new mempool min fee to the feerate of the removed set, plus the |
922 | | // "minimum reasonable fee rate" (ie some value under which we consider txn |
923 | | // to have 0 fee). This way, we don't allow txn to enter mempool with feerate |
924 | | // equal to txn which were removed with no block in between. |
925 | 39 | removed += m_opts.incremental_relay_feerate; |
926 | 39 | trackPackageRemoved(removed); |
927 | 39 | maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed); |
928 | | |
929 | 39 | nTxnRemoved += worst_chunk.size(); |
930 | | |
931 | 39 | std::vector<CTransaction> txn; |
932 | 39 | if (pvNoSpendsRemaining) { |
933 | 31 | txn.reserve(worst_chunk.size()); |
934 | 32 | for (auto ref : worst_chunk) { |
935 | 32 | txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx()); |
936 | 32 | } |
937 | 31 | } |
938 | | |
939 | 39 | setEntries stage; |
940 | 45 | for (auto ref : worst_chunk) { |
941 | 45 | stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref))); |
942 | 45 | } |
943 | 45 | for (auto e : stage) { |
944 | 45 | removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT); |
945 | 45 | } |
946 | 39 | if (pvNoSpendsRemaining) { |
947 | 32 | for (const CTransaction& tx : txn) { |
948 | 32 | for (const CTxIn& txin : tx.vin) { |
949 | 32 | if (exists(txin.prevout.hash)) continue; |
950 | 31 | pvNoSpendsRemaining->push_back(txin.prevout); |
951 | 31 | } |
952 | 32 | } |
953 | 31 | } |
954 | 39 | } |
955 | | |
956 | 28.0k | if (maxFeeRateRemoved > CFeeRate(0)) { |
957 | 32 | LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString()); |
958 | 32 | } |
959 | 28.0k | } |
960 | | |
961 | | std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const |
962 | 123k | { |
963 | 123k | auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN); |
964 | | |
965 | 123k | size_t ancestor_count = ancestors.size(); |
966 | 123k | size_t ancestor_size = 0; |
967 | 123k | CAmount ancestor_fees = 0; |
968 | 324k | for (auto tx: ancestors) { |
969 | 324k | const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx); |
970 | 324k | ancestor_size += anc.GetTxSize(); |
971 | 324k | ancestor_fees += anc.GetModifiedFee(); |
972 | 324k | } |
973 | 123k | return {ancestor_count, ancestor_size, ancestor_fees}; |
974 | 123k | } |
975 | | |
976 | | std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const |
977 | 8.65k | { |
978 | 8.65k | auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN); |
979 | 8.65k | size_t descendant_count = descendants.size(); |
980 | 8.65k | size_t descendant_size = 0; |
981 | 8.65k | CAmount descendant_fees = 0; |
982 | | |
983 | 154k | for (auto tx: descendants) { |
984 | 154k | const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx); |
985 | 154k | descendant_size += desc.GetTxSize(); |
986 | 154k | descendant_fees += desc.GetModifiedFee(); |
987 | 154k | } |
988 | 8.65k | return {descendant_count, descendant_size, descendant_fees}; |
989 | 8.65k | } |
990 | | |
991 | 578k | void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const { |
992 | 578k | LOCK(cs); |
993 | 578k | auto it = mapTx.find(txid); |
994 | 578k | ancestors = cluster_count = 0; |
995 | 578k | if (it != mapTx.end()) { |
996 | 46.7k | auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it); |
997 | 46.7k | ancestors = ancestor_count; |
998 | 46.7k | if (ancestorsize) *ancestorsize = ancestor_size; |
999 | 46.7k | if (ancestorfees) *ancestorfees = ancestor_fees; |
1000 | 46.7k | cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size(); |
1001 | 46.7k | } |
1002 | 578k | } |
1003 | | |
1004 | | bool CTxMemPool::GetLoadTried() const |
1005 | 5.63k | { |
1006 | 5.63k | LOCK(cs); |
1007 | 5.63k | return m_load_tried; |
1008 | 5.63k | } |
1009 | | |
1010 | | void CTxMemPool::SetLoadTried(bool load_tried) |
1011 | 1.07k | { |
1012 | 1.07k | LOCK(cs); |
1013 | 1.07k | m_load_tried = load_tried; |
1014 | 1.07k | } |
1015 | | |
1016 | | std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const |
1017 | 3.19k | { |
1018 | 3.19k | AssertLockHeld(cs); |
1019 | | |
1020 | 3.19k | std::vector<CTxMemPool::txiter> ret; |
1021 | 3.19k | std::set<const CTxMemPoolEntry*> unique_cluster_representatives; |
1022 | 48.4k | for (auto txid : txids) { |
1023 | 48.4k | auto it = mapTx.find(txid); |
1024 | 48.4k | if (it != mapTx.end()) { |
1025 | | // Note that TxGraph::GetCluster will return results in graph |
1026 | | // order, which is deterministic (as long as we are not modifying |
1027 | | // the graph). |
1028 | 48.4k | auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN); |
1029 | 48.4k | if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) { |
1030 | 70.0k | for (auto tx : cluster) { |
1031 | 70.0k | ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx))); |
1032 | 70.0k | } |
1033 | 48.2k | } |
1034 | 48.4k | } |
1035 | 48.4k | } |
1036 | 3.19k | if (ret.size() > 500) { |
1037 | 2 | return {}; |
1038 | 2 | } |
1039 | 3.19k | return ret; |
1040 | 3.19k | } |
1041 | | |
1042 | | util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF() |
1043 | 1.35k | { |
1044 | 1.35k | LOCK(m_pool->cs); |
1045 | | |
1046 | 1.35k | if (!CheckMemPoolPolicyLimits()) { |
1047 | 0 | return util::Error{Untranslated("cluster size limit exceeded")}; |
1048 | 0 | } |
1049 | | |
1050 | 1.35k | return m_pool->m_txgraph->GetMainStagingDiagrams(); |
1051 | 1.35k | } |
1052 | | |
1053 | | CTxMemPool::ChangeSet::TxHandle CTxMemPool::ChangeSet::StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp) |
1054 | 68.7k | { |
1055 | 68.7k | LOCK(m_pool->cs); |
1056 | 68.7k | Assume(m_to_add.find(tx->GetHash()) == m_to_add.end()); |
1057 | 68.7k | Assume(!m_dependencies_processed); |
1058 | | |
1059 | | // We need to process dependencies after adding a new transaction. |
1060 | 68.7k | m_dependencies_processed = false; |
1061 | | |
1062 | 68.7k | CAmount delta{0}; |
1063 | 68.7k | m_pool->ApplyDelta(tx->GetHash(), delta); |
1064 | | |
1065 | 68.7k | FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp)); |
1066 | 68.7k | auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first; |
1067 | 68.7k | m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate); |
1068 | 68.7k | if (delta) { |
1069 | 41 | newit->UpdateModifiedFee(delta); |
1070 | 41 | m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee()); |
1071 | 41 | } |
1072 | | |
1073 | 68.7k | m_entry_vec.push_back(newit); |
1074 | | |
1075 | 68.7k | return newit; |
1076 | 68.7k | } |
1077 | | |
1078 | | void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it) |
1079 | 2.20k | { |
1080 | 2.20k | LOCK(m_pool->cs); |
1081 | 2.20k | m_pool->m_txgraph->RemoveTransaction(*it); |
1082 | 2.20k | m_to_remove.insert(it); |
1083 | 2.20k | } |
1084 | | |
1085 | | void CTxMemPool::ChangeSet::Apply() |
1086 | 45.7k | { |
1087 | 45.7k | LOCK(m_pool->cs); |
1088 | 45.7k | if (!m_dependencies_processed) { |
1089 | 3 | ProcessDependencies(); |
1090 | 3 | } |
1091 | 45.7k | m_pool->Apply(this); |
1092 | 45.7k | m_to_add.clear(); |
1093 | 45.7k | m_to_remove.clear(); |
1094 | 45.7k | m_entry_vec.clear(); |
1095 | 45.7k | m_ancestors.clear(); |
1096 | 45.7k | } |
1097 | | |
1098 | | void CTxMemPool::ChangeSet::ProcessDependencies() |
1099 | 67.7k | { |
1100 | 67.7k | LOCK(m_pool->cs); |
1101 | 67.7k | Assume(!m_dependencies_processed); // should only call this once. |
1102 | 68.3k | for (const auto& entryptr : m_entry_vec) { |
1103 | 96.6k | for (const auto &txin : entryptr->GetSharedTx()->vin) { |
1104 | 96.6k | std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash); |
1105 | 96.6k | if (!piter) { |
1106 | 86.3k | auto it = m_to_add.find(txin.prevout.hash); |
1107 | 86.3k | if (it != m_to_add.end()) { |
1108 | 584 | piter = std::make_optional(it); |
1109 | 584 | } |
1110 | 86.3k | } |
1111 | 96.6k | if (piter) { |
1112 | 10.8k | m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr); |
1113 | 10.8k | } |
1114 | 96.6k | } |
1115 | 68.3k | } |
1116 | 67.7k | m_dependencies_processed = true; |
1117 | 67.7k | return; |
1118 | 67.7k | } |
1119 | | |
1120 | | bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits() |
1121 | 70.4k | { |
1122 | 70.4k | LOCK(m_pool->cs); |
1123 | 70.4k | if (!m_dependencies_processed) { |
1124 | 67.7k | ProcessDependencies(); |
1125 | 67.7k | } |
1126 | | |
1127 | 70.4k | return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP); |
1128 | 70.4k | } |
1129 | | |
1130 | | std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const |
1131 | 145k | { |
1132 | 145k | FeePerWeight zero{}; |
1133 | 145k | std::vector<FeePerWeight> ret; |
1134 | | |
1135 | 145k | ret.emplace_back(zero); |
1136 | | |
1137 | 145k | StartBlockBuilding(); |
1138 | | |
1139 | 145k | std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy; |
1140 | | |
1141 | 145k | FeePerWeight last_selection = GetBlockBuilderChunk(dummy); |
1142 | 8.70M | while (last_selection != FeePerWeight{}) { |
1143 | 8.55M | last_selection += ret.back(); |
1144 | 8.55M | ret.emplace_back(last_selection); |
1145 | 8.55M | IncludeBuilderChunk(); |
1146 | 8.55M | last_selection = GetBlockBuilderChunk(dummy); |
1147 | 8.55M | } |
1148 | 145k | StopBlockBuilding(); |
1149 | 145k | return ret; |
1150 | 145k | } |