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