2013-08-27 07:51:57 +02:00
|
|
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
2023-04-25 13:51:26 +02:00
|
|
|
// Copyright (c) 2009-2020 The Bitcoin Core developers
|
2014-11-17 03:29:09 +01:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
2013-08-27 07:51:57 +02:00
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
2014-08-28 22:21:03 +02:00
|
|
|
|
2013-08-27 07:51:57 +02:00
|
|
|
#ifndef BITCOIN_TXMEMPOOL_H
|
|
|
|
#define BITCOIN_TXMEMPOOL_H
|
|
|
|
|
2022-05-05 16:24:51 +02:00
|
|
|
#include <atomic>
|
2016-10-25 14:00:27 +02:00
|
|
|
#include <map>
|
2022-10-15 22:11:49 +02:00
|
|
|
#include <optional>
|
2022-05-05 16:24:51 +02:00
|
|
|
#include <set>
|
2016-10-25 14:00:27 +02:00
|
|
|
#include <string>
|
2022-05-05 16:24:51 +02:00
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2014-02-15 22:38:28 +01:00
|
|
|
|
2020-03-19 23:46:56 +01:00
|
|
|
#include <addressindex.h>
|
|
|
|
#include <coins.h>
|
2024-10-21 19:59:23 +02:00
|
|
|
#include <consensus/amount.h>
|
2024-05-28 17:24:36 +02:00
|
|
|
#include <gsl/pointers.h>
|
2020-03-19 23:46:56 +01:00
|
|
|
#include <indirectmap.h>
|
2024-10-21 19:59:23 +02:00
|
|
|
#include <netaddress.h>
|
2020-03-19 23:46:56 +01:00
|
|
|
#include <policy/feerate.h>
|
Merge bitcoin/bitcoin#21800: mempool/validation: mempool ancestor/descendant limits for packages
accf3d5868460b4b14ab607fd66ac985b086fbb3 [test] mempool package ancestor/descendant limits (glozow)
2b6b26e57c24d2f0abd442c1c33098e3121572ce [test] parameterizable fee for make_chain and create_child_with_parents (glozow)
313c09f7b7beddfdb74c284720d209c81dfdb94f [test] helper function to increase transaction weight (glozow)
f8253d69d6f02850995a11eeb71fedc22e6f6575 extract/rename helper functions from rpc_packages.py (glozow)
3cd663a5d33aa7ef87994e452bced7f192d021a0 [policy] ancestor/descendant limits for packages (glozow)
c6e016aa139c8363e9b38bbc1ba0dca55700b8a7 [mempool] check ancestor/descendant limits for packages (glozow)
f551841d3ec080a2d7a7988c7b35088dff6c5830 [refactor] pass size/count instead of entry to CalculateAncestorsAndCheckLimits (glozow)
97dd1c729d2bbedf9527b914c0cc8267b8a7c21b MOVEONLY: add helper function for calculating ancestors and checking limits (glozow)
f95bbf58aaf72aab8a9c5827b1f162f3b8ac38f4 misc package validation doc improvements (glozow)
Pull request description:
This PR implements a function to calculate mempool ancestors for a package and enforces ancestor/descendant limits on them as a whole. It reuses a portion of `CalculateMemPoolAncestors()`; there's also a small refactor to move the reused code into a generic helper function. Instead of calculating ancestors and descendants on every single transaction in the package and their ancestors, we use a "worst case" heuristic, treating every transaction in the package as each other's ancestor and descendant. This may overestimate everyone's counts, but is still pretty accurate in the our main package use cases, in which at least one of the transactions in the package is directly related to all the others (e.g. 1 parent + 1 child, multiple parents with 1 child, or chains).
Note on Terminology: While "package" is often used to describe groups of related transactions _within_ the mempool, here, I only use package to mean the group of not-in-mempool transactions we are currently validating.
#### Motivation
It would be a potential DoS vector to allow submission of packages to mempool without a proper guard for mempool ancestors/descendants. In general, the purpose of mempool ancestor/descendant limits is to limit the computational complexity of dealing with families during removals and additions. We want to be able to validate multiple transactions on top of the mempool, but also avoid these scenarios:
- We underestimate the ancestors/descendants during package validation and end up with extremely complex families in our mempool (potentially a DoS vector).
- We expend an unreasonable amount of resources calculating everyone's ancestors and descendants during package validation.
ACKs for top commit:
JeremyRubin:
utACK accf3d5
ariard:
ACK accf3d5.
Tree-SHA512: 0d18ce4b77398fe872e0b7c2cc66d3aac2135e561b64029584339e1f4de2a6a16ebab3dd5784f376e119cbafc4d50168b28d3bd95d0b3d01158714ade2e3624d
Signed-off-by: Vijay <vijaydas.mp@gmail.com>
2021-08-09 05:53:10 +02:00
|
|
|
#include <policy/packages.h>
|
2020-03-19 23:46:56 +01:00
|
|
|
#include <primitives/transaction.h>
|
|
|
|
#include <pubkey.h>
|
2024-10-21 19:59:23 +02:00
|
|
|
#include <random.h>
|
|
|
|
#include <spentindex.h>
|
2021-02-08 20:36:33 +01:00
|
|
|
#include <sync.h>
|
2021-02-24 09:07:10 +01:00
|
|
|
#include <util/epochguard.h>
|
2023-08-23 20:55:19 +02:00
|
|
|
#include <util/hasher.h>
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2017-09-05 22:25:42 +02:00
|
|
|
#include <boost/multi_index/hashed_index.hpp>
|
2024-10-05 01:28:12 +02:00
|
|
|
#include <boost/multi_index/identity.hpp>
|
|
|
|
#include <boost/multi_index/indexed_by.hpp>
|
2017-09-05 22:25:42 +02:00
|
|
|
#include <boost/multi_index/ordered_index.hpp>
|
2017-05-30 18:42:22 +02:00
|
|
|
#include <boost/multi_index/sequenced_index.hpp>
|
2024-10-05 01:28:12 +02:00
|
|
|
#include <boost/multi_index/tag.hpp>
|
2021-12-02 12:47:20 +01:00
|
|
|
#include <boost/multi_index_container.hpp>
|
2017-01-24 10:07:50 +01:00
|
|
|
|
2015-12-04 21:01:22 +01:00
|
|
|
class CBlockIndex;
|
2021-12-02 12:47:20 +01:00
|
|
|
class CChain;
|
2023-03-23 08:47:33 +01:00
|
|
|
class CChainState;
|
2023-04-25 13:51:26 +02:00
|
|
|
extern RecursiveMutex cs_main;
|
2014-10-22 21:08:30 +02:00
|
|
|
|
2023-07-01 02:27:39 +02:00
|
|
|
// Forward declation for CBLSLazyPublicKey:
|
|
|
|
template<typename T> class CBLSLazyWrapper;
|
|
|
|
class CBLSPublicKey;
|
|
|
|
using CBLSLazyPublicKey = CBLSLazyWrapper<CBLSPublicKey>;
|
|
|
|
|
2017-06-02 00:47:58 +02:00
|
|
|
/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
|
|
|
|
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
|
2013-11-05 02:47:07 +01:00
|
|
|
|
2024-09-08 18:08:41 +02:00
|
|
|
struct LockPoints {
|
2015-12-04 21:01:22 +01:00
|
|
|
// Will be set to the blockchain height and median time past
|
|
|
|
// values that would be necessary to satisfy all relative locktime
|
|
|
|
// constraints (BIP68) of this tx given our view of block chain history
|
2024-09-08 18:08:41 +02:00
|
|
|
int height{0};
|
|
|
|
int64_t time{0};
|
2015-12-04 21:01:22 +01:00
|
|
|
// As long as the current chain descends from the highest height block
|
|
|
|
// containing one of the inputs used in the calculation, then the cached
|
|
|
|
// values are still valid even after a reorg.
|
2024-09-08 18:08:41 +02:00
|
|
|
CBlockIndex* maxInputBlock{nullptr};
|
2015-12-04 21:01:22 +01:00
|
|
|
};
|
|
|
|
|
2024-10-03 21:51:30 +02:00
|
|
|
/**
|
|
|
|
* Test whether the LockPoints height and time are still valid on the current chain
|
|
|
|
*/
|
2021-12-02 12:47:20 +01:00
|
|
|
bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2024-10-03 21:51:30 +02:00
|
|
|
|
Merge #19478: Remove CTxMempool::mapLinks data structure member
296be8f58e02b39a58f017c52294aceed22c3ffd Get rid of unused functions CTxMemPool::GetMemPoolChildren, CTxMemPool::GetMemPoolParents (Jeremy Rubin)
46d955d196043cc297834baeebce31ff778dff80 Remove mapLinks in favor of entry inlined structs with iterator type erasure (Jeremy Rubin)
Pull request description:
Currently we have a peculiar data structure in the mempool called maplinks. Maplinks job is to track the in-pool children and parents of each transaction. This PR can be primarily understood and reviewed as a simple refactoring to remove this extra data structure, although it comes with a nice memory and performance improvement for free.
Maplinks is particularly peculiar because removing it is not as simple as just moving it's inner structure to the owning CTxMempoolEntry. Because TxLinks (the class storing the setEntries for parents and children) store txiters to each entry in the mempool corresponding to the parent or child, it means that the TxLinks type is "aware" of the boost multiindex (mapTx) it's coming from, which is in turn, aware of the entry type stored in mapTx. Thus we used maplinks to store this entry associated data we in an entirely separate data structure just to avoid a circular type reference caused by storing a txiter inside a CTxMempoolEntry.
It turns out, we can kill this circular reference by making use of iterator_to multiindex function and std::reference_wrapper. This allows us to get rid of the maplinks data structure and move the ownership of the parents/child sets to the entries themselves.
The benefit of this good all around, for any of the reasons given below the change would be acceptable, and it doesn't make the code harder to reason about or worse in any respect (as far as I can tell, there's no tradeoff).
### Simpler ownership model
No longer having to consistency check that mapLinks did have records for our CTxMempoolEntry, impossible to have a mapLinks entry outlive or incorrectly die before a CTxMempoolEntry.
### Memory Usage
We get rid of a O(Transactions) sized map in the mempool, which is a long lived data structure.
### Performance
If you have a CTxMemPoolEntry, you immediately know the address of it's children/parents, rather than having to do a O(log(Transactions)) lookup via maplinks (which we do very often). We do it in *so many* places that a true benchmark has to look at a full running node, but it is easy enough to show an improvement in this case.
The ComplexMemPool shows a good coherence check that we see the expected result of it being 12.5% faster / 1.14x faster.
```
Before:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.40462, 0.277222, 0.285339, 0.279793
After:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.22586, 0.243831, 0.247076, 0.244596
```
The ComplexMemPool benchmark only checks doing addUnchecked and TrimToSize for 800 transactions. While this bench does a good job of hammering the relevant types of function, it doesn't test everything.
Subbing in 5000 transactions shows a that the advantage isn't completely wiped out by other asymptotic factors (this isn't the only bottleneck in growing the mempool), but it's only a bit proportionally slower (10.8%, 1.12x), which adds evidence that this will be a good change for performance minded users.
```
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 59.1321, 11.5919, 12.235, 11.7068
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 52.1307, 10.2641, 10.5206, 10.4306
```
I don't think it's possible to come up with an example of where a maplinks based design would have better performance, but it's something for reviewers to consider.
# Discussion
## Why maplinks in the first place?
I spoke with the author of mapLinks (sdaftuar) a while back, and my recollection from our conversation was that it was implemented because he did not know how to resolve the circular dependency at the time, and there was no other reason for making it a separate map.
## Is iterator_to weird?
iterator_to is expressly for this purpose, see https://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to
> iterator_to provides a way to retrieve an iterator to an element from a pointer to the element, thus making iterators and pointers interchangeable for the purposes of element pointing (not so for traversal) in many situations. This notwithstanding, it is not the aim of iterator_to to promote the usage of pointers as substitutes for real iterators: the latter are specifically designed for handling the elements of a container, and not only benefit from the iterator orientation of container interfaces, but are also capable of exposing many more programming bugs than raw pointers, both at compile and run time. iterator_to is thus meant to be used in scenarios where access via iterators is not suitable or desireable:
>
> - Interoperability with preexisting APIs based on pointers or references.
> - Publication of pointer-based interfaces (for instance, when designing a C-compatible library).
> - The exposure of pointers in place of iterators can act as a type erasure barrier effectively decoupling the user of the code from the implementation detail of which particular container is being used. Similar techniques, like the famous Pimpl idiom, are used in large projects to reduce dependencies and build times.
> - Self-referencing contexts where an element acts upon its owner container and no iterator to itself is available.
In other words, iterator_to is the perfect tool for the job by the last reason given. Under the hood it should just be a simple pointer cast and have no major runtime overhead (depending on if the function call is inlined).
Edit by laanwj: removed at sign from the description
ACKs for top commit:
jonatack:
re-ACK 296be8f per `git range-diff ab338a19 3ba1665 296be8f`, sanity check gcc 10.2 debug build is clean.
hebasto:
re-ACK 296be8f58e02b39a58f017c52294aceed22c3ffd, only rebased since my [previous](https://github.com/bitcoin/bitcoin/pull/19478#pullrequestreview-482400727) review (verified with `git range-diff`).
Tree-SHA512: f5c30a4936fcde6ae32a02823c303b3568a747c2681d11f87df88a149f984a6d3b4c81f391859afbeb68864ef7f6a3d8779f74a58e3de701b3d51f78e498682e
2020-09-07 12:06:38 +02:00
|
|
|
struct CompareIteratorByHash {
|
|
|
|
// SFINAE for T where T is either a pointer type (e.g., a txiter) or a reference_wrapper<T>
|
|
|
|
// (e.g. a wrapped CTxMemPoolEntry&)
|
|
|
|
template <typename T>
|
|
|
|
bool operator()(const std::reference_wrapper<T>& a, const std::reference_wrapper<T>& b) const
|
|
|
|
{
|
|
|
|
return a.get().GetTx().GetHash() < b.get().GetTx().GetHash();
|
|
|
|
}
|
|
|
|
template <typename T>
|
|
|
|
bool operator()(const T& a, const T& b) const
|
|
|
|
{
|
|
|
|
return a->GetTx().GetHash() < b->GetTx().GetHash();
|
|
|
|
}
|
|
|
|
};
|
2015-07-15 20:47:45 +02:00
|
|
|
/** \class CTxMemPoolEntry
|
|
|
|
*
|
2016-11-29 11:12:39 +01:00
|
|
|
* CTxMemPoolEntry stores data about the corresponding transaction, as well
|
2015-07-15 20:47:45 +02:00
|
|
|
* as data about all in-mempool transactions that depend on the transaction
|
|
|
|
* ("descendant" transactions).
|
|
|
|
*
|
|
|
|
* When a new entry is added to the mempool, we update the descendant state
|
2015-11-19 17:18:28 +01:00
|
|
|
* (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
|
2015-07-15 20:47:45 +02:00
|
|
|
* all ancestors of the newly added transaction.
|
|
|
|
*
|
2013-11-11 08:35:14 +01:00
|
|
|
*/
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2013-11-11 08:35:14 +01:00
|
|
|
class CTxMemPoolEntry
|
|
|
|
{
|
Merge #19478: Remove CTxMempool::mapLinks data structure member
296be8f58e02b39a58f017c52294aceed22c3ffd Get rid of unused functions CTxMemPool::GetMemPoolChildren, CTxMemPool::GetMemPoolParents (Jeremy Rubin)
46d955d196043cc297834baeebce31ff778dff80 Remove mapLinks in favor of entry inlined structs with iterator type erasure (Jeremy Rubin)
Pull request description:
Currently we have a peculiar data structure in the mempool called maplinks. Maplinks job is to track the in-pool children and parents of each transaction. This PR can be primarily understood and reviewed as a simple refactoring to remove this extra data structure, although it comes with a nice memory and performance improvement for free.
Maplinks is particularly peculiar because removing it is not as simple as just moving it's inner structure to the owning CTxMempoolEntry. Because TxLinks (the class storing the setEntries for parents and children) store txiters to each entry in the mempool corresponding to the parent or child, it means that the TxLinks type is "aware" of the boost multiindex (mapTx) it's coming from, which is in turn, aware of the entry type stored in mapTx. Thus we used maplinks to store this entry associated data we in an entirely separate data structure just to avoid a circular type reference caused by storing a txiter inside a CTxMempoolEntry.
It turns out, we can kill this circular reference by making use of iterator_to multiindex function and std::reference_wrapper. This allows us to get rid of the maplinks data structure and move the ownership of the parents/child sets to the entries themselves.
The benefit of this good all around, for any of the reasons given below the change would be acceptable, and it doesn't make the code harder to reason about or worse in any respect (as far as I can tell, there's no tradeoff).
### Simpler ownership model
No longer having to consistency check that mapLinks did have records for our CTxMempoolEntry, impossible to have a mapLinks entry outlive or incorrectly die before a CTxMempoolEntry.
### Memory Usage
We get rid of a O(Transactions) sized map in the mempool, which is a long lived data structure.
### Performance
If you have a CTxMemPoolEntry, you immediately know the address of it's children/parents, rather than having to do a O(log(Transactions)) lookup via maplinks (which we do very often). We do it in *so many* places that a true benchmark has to look at a full running node, but it is easy enough to show an improvement in this case.
The ComplexMemPool shows a good coherence check that we see the expected result of it being 12.5% faster / 1.14x faster.
```
Before:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.40462, 0.277222, 0.285339, 0.279793
After:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.22586, 0.243831, 0.247076, 0.244596
```
The ComplexMemPool benchmark only checks doing addUnchecked and TrimToSize for 800 transactions. While this bench does a good job of hammering the relevant types of function, it doesn't test everything.
Subbing in 5000 transactions shows a that the advantage isn't completely wiped out by other asymptotic factors (this isn't the only bottleneck in growing the mempool), but it's only a bit proportionally slower (10.8%, 1.12x), which adds evidence that this will be a good change for performance minded users.
```
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 59.1321, 11.5919, 12.235, 11.7068
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 52.1307, 10.2641, 10.5206, 10.4306
```
I don't think it's possible to come up with an example of where a maplinks based design would have better performance, but it's something for reviewers to consider.
# Discussion
## Why maplinks in the first place?
I spoke with the author of mapLinks (sdaftuar) a while back, and my recollection from our conversation was that it was implemented because he did not know how to resolve the circular dependency at the time, and there was no other reason for making it a separate map.
## Is iterator_to weird?
iterator_to is expressly for this purpose, see https://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to
> iterator_to provides a way to retrieve an iterator to an element from a pointer to the element, thus making iterators and pointers interchangeable for the purposes of element pointing (not so for traversal) in many situations. This notwithstanding, it is not the aim of iterator_to to promote the usage of pointers as substitutes for real iterators: the latter are specifically designed for handling the elements of a container, and not only benefit from the iterator orientation of container interfaces, but are also capable of exposing many more programming bugs than raw pointers, both at compile and run time. iterator_to is thus meant to be used in scenarios where access via iterators is not suitable or desireable:
>
> - Interoperability with preexisting APIs based on pointers or references.
> - Publication of pointer-based interfaces (for instance, when designing a C-compatible library).
> - The exposure of pointers in place of iterators can act as a type erasure barrier effectively decoupling the user of the code from the implementation detail of which particular container is being used. Similar techniques, like the famous Pimpl idiom, are used in large projects to reduce dependencies and build times.
> - Self-referencing contexts where an element acts upon its owner container and no iterator to itself is available.
In other words, iterator_to is the perfect tool for the job by the last reason given. Under the hood it should just be a simple pointer cast and have no major runtime overhead (depending on if the function call is inlined).
Edit by laanwj: removed at sign from the description
ACKs for top commit:
jonatack:
re-ACK 296be8f per `git range-diff ab338a19 3ba1665 296be8f`, sanity check gcc 10.2 debug build is clean.
hebasto:
re-ACK 296be8f58e02b39a58f017c52294aceed22c3ffd, only rebased since my [previous](https://github.com/bitcoin/bitcoin/pull/19478#pullrequestreview-482400727) review (verified with `git range-diff`).
Tree-SHA512: f5c30a4936fcde6ae32a02823c303b3568a747c2681d11f87df88a149f984a6d3b4c81f391859afbeb68864ef7f6a3d8779f74a58e3de701b3d51f78e498682e
2020-09-07 12:06:38 +02:00
|
|
|
public:
|
|
|
|
typedef std::reference_wrapper<const CTxMemPoolEntry> CTxMemPoolEntryRef;
|
|
|
|
// two aliases, should the types ever diverge
|
|
|
|
typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Parents;
|
|
|
|
typedef std::set<CTxMemPoolEntryRef, CompareIteratorByHash> Children;
|
|
|
|
|
2013-11-11 08:35:14 +01:00
|
|
|
private:
|
2018-07-29 02:55:32 +02:00
|
|
|
const CTransactionRef tx;
|
Merge #19478: Remove CTxMempool::mapLinks data structure member
296be8f58e02b39a58f017c52294aceed22c3ffd Get rid of unused functions CTxMemPool::GetMemPoolChildren, CTxMemPool::GetMemPoolParents (Jeremy Rubin)
46d955d196043cc297834baeebce31ff778dff80 Remove mapLinks in favor of entry inlined structs with iterator type erasure (Jeremy Rubin)
Pull request description:
Currently we have a peculiar data structure in the mempool called maplinks. Maplinks job is to track the in-pool children and parents of each transaction. This PR can be primarily understood and reviewed as a simple refactoring to remove this extra data structure, although it comes with a nice memory and performance improvement for free.
Maplinks is particularly peculiar because removing it is not as simple as just moving it's inner structure to the owning CTxMempoolEntry. Because TxLinks (the class storing the setEntries for parents and children) store txiters to each entry in the mempool corresponding to the parent or child, it means that the TxLinks type is "aware" of the boost multiindex (mapTx) it's coming from, which is in turn, aware of the entry type stored in mapTx. Thus we used maplinks to store this entry associated data we in an entirely separate data structure just to avoid a circular type reference caused by storing a txiter inside a CTxMempoolEntry.
It turns out, we can kill this circular reference by making use of iterator_to multiindex function and std::reference_wrapper. This allows us to get rid of the maplinks data structure and move the ownership of the parents/child sets to the entries themselves.
The benefit of this good all around, for any of the reasons given below the change would be acceptable, and it doesn't make the code harder to reason about or worse in any respect (as far as I can tell, there's no tradeoff).
### Simpler ownership model
No longer having to consistency check that mapLinks did have records for our CTxMempoolEntry, impossible to have a mapLinks entry outlive or incorrectly die before a CTxMempoolEntry.
### Memory Usage
We get rid of a O(Transactions) sized map in the mempool, which is a long lived data structure.
### Performance
If you have a CTxMemPoolEntry, you immediately know the address of it's children/parents, rather than having to do a O(log(Transactions)) lookup via maplinks (which we do very often). We do it in *so many* places that a true benchmark has to look at a full running node, but it is easy enough to show an improvement in this case.
The ComplexMemPool shows a good coherence check that we see the expected result of it being 12.5% faster / 1.14x faster.
```
Before:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.40462, 0.277222, 0.285339, 0.279793
After:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.22586, 0.243831, 0.247076, 0.244596
```
The ComplexMemPool benchmark only checks doing addUnchecked and TrimToSize for 800 transactions. While this bench does a good job of hammering the relevant types of function, it doesn't test everything.
Subbing in 5000 transactions shows a that the advantage isn't completely wiped out by other asymptotic factors (this isn't the only bottleneck in growing the mempool), but it's only a bit proportionally slower (10.8%, 1.12x), which adds evidence that this will be a good change for performance minded users.
```
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 59.1321, 11.5919, 12.235, 11.7068
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 52.1307, 10.2641, 10.5206, 10.4306
```
I don't think it's possible to come up with an example of where a maplinks based design would have better performance, but it's something for reviewers to consider.
# Discussion
## Why maplinks in the first place?
I spoke with the author of mapLinks (sdaftuar) a while back, and my recollection from our conversation was that it was implemented because he did not know how to resolve the circular dependency at the time, and there was no other reason for making it a separate map.
## Is iterator_to weird?
iterator_to is expressly for this purpose, see https://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to
> iterator_to provides a way to retrieve an iterator to an element from a pointer to the element, thus making iterators and pointers interchangeable for the purposes of element pointing (not so for traversal) in many situations. This notwithstanding, it is not the aim of iterator_to to promote the usage of pointers as substitutes for real iterators: the latter are specifically designed for handling the elements of a container, and not only benefit from the iterator orientation of container interfaces, but are also capable of exposing many more programming bugs than raw pointers, both at compile and run time. iterator_to is thus meant to be used in scenarios where access via iterators is not suitable or desireable:
>
> - Interoperability with preexisting APIs based on pointers or references.
> - Publication of pointer-based interfaces (for instance, when designing a C-compatible library).
> - The exposure of pointers in place of iterators can act as a type erasure barrier effectively decoupling the user of the code from the implementation detail of which particular container is being used. Similar techniques, like the famous Pimpl idiom, are used in large projects to reduce dependencies and build times.
> - Self-referencing contexts where an element acts upon its owner container and no iterator to itself is available.
In other words, iterator_to is the perfect tool for the job by the last reason given. Under the hood it should just be a simple pointer cast and have no major runtime overhead (depending on if the function call is inlined).
Edit by laanwj: removed at sign from the description
ACKs for top commit:
jonatack:
re-ACK 296be8f per `git range-diff ab338a19 3ba1665 296be8f`, sanity check gcc 10.2 debug build is clean.
hebasto:
re-ACK 296be8f58e02b39a58f017c52294aceed22c3ffd, only rebased since my [previous](https://github.com/bitcoin/bitcoin/pull/19478#pullrequestreview-482400727) review (verified with `git range-diff`).
Tree-SHA512: f5c30a4936fcde6ae32a02823c303b3568a747c2681d11f87df88a149f984a6d3b4c81f391859afbeb68864ef7f6a3d8779f74a58e3de701b3d51f78e498682e
2020-09-07 12:06:38 +02:00
|
|
|
mutable Parents m_parents;
|
|
|
|
mutable Children m_children;
|
2018-07-29 02:55:32 +02:00
|
|
|
const CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
|
|
|
|
const size_t nTxSize; //!< ... and avoid recomputing tx size
|
|
|
|
const size_t nUsageSize; //!< ... and total memory usage
|
|
|
|
const int64_t nTime; //!< Local time when entering the mempool
|
|
|
|
const unsigned int entryHeight; //!< Chain height when entering the mempool
|
|
|
|
const bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
|
2024-09-08 18:08:41 +02:00
|
|
|
const int64_t sigOpCount; //!< Legacy sig ops plus P2SH sig op count
|
|
|
|
int64_t feeDelta{0}; //!< Used for determining the priority of the transaction for mining in a block
|
|
|
|
LockPoints lockPoints; //!< Track the height and time at which tx was final
|
2013-11-11 08:35:14 +01:00
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
// Information about descendants of this transaction that are in the
|
|
|
|
// mempool; if we remove this transaction we must remove all of these
|
2017-05-16 00:34:47 +02:00
|
|
|
// descendants as well.
|
2024-09-08 18:08:41 +02:00
|
|
|
uint64_t nCountWithDescendants{1}; //!< number of descendant transactions
|
2016-04-05 17:49:42 +02:00
|
|
|
uint64_t nSizeWithDescendants; //!< ... and size
|
|
|
|
CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
|
2013-11-11 08:35:14 +01:00
|
|
|
|
2016-03-17 13:33:31 +01:00
|
|
|
// Analogous statistics for ancestor transactions
|
2024-09-08 18:08:41 +02:00
|
|
|
uint64_t nCountWithAncestors{1};
|
2016-03-17 13:33:31 +01:00
|
|
|
uint64_t nSizeWithAncestors;
|
|
|
|
CAmount nModFeesWithAncestors;
|
2024-09-08 18:08:41 +02:00
|
|
|
int64_t nSigOpCountWithAncestors;
|
2016-03-17 13:33:31 +01:00
|
|
|
|
2013-11-11 08:35:14 +01:00
|
|
|
public:
|
2024-09-08 18:08:41 +02:00
|
|
|
CTxMemPoolEntry(const CTransactionRef& tx, CAmount fee,
|
|
|
|
int64_t time, unsigned int entry_height,
|
|
|
|
bool spends_coinbase,
|
|
|
|
int64_t sigops_count, LockPoints lp);
|
2017-01-04 12:22:49 +01:00
|
|
|
|
2016-06-08 14:01:05 +02:00
|
|
|
const CTransaction& GetTx() const { return *this->tx; }
|
2016-11-21 10:51:32 +01:00
|
|
|
CTransactionRef GetSharedTx() const { return this->tx; }
|
2015-10-02 23:17:27 +02:00
|
|
|
const CAmount& GetFee() const { return nFee; }
|
2021-11-08 19:43:24 +01:00
|
|
|
size_t GetTxSize() const;
|
2019-10-02 16:55:03 +02:00
|
|
|
std::chrono::seconds GetTime() const { return std::chrono::seconds{nTime}; }
|
2015-06-30 17:14:24 +02:00
|
|
|
unsigned int GetHeight() const { return entryHeight; }
|
2024-09-08 18:08:41 +02:00
|
|
|
int64_t GetSigOpCount() const { return sigOpCount; }
|
2015-10-26 19:06:06 +01:00
|
|
|
int64_t GetModifiedFee() const { return nFee + feeDelta; }
|
2015-07-09 19:56:31 +02:00
|
|
|
size_t DynamicMemoryUsage() const { return nUsageSize; }
|
2015-12-04 21:01:22 +01:00
|
|
|
const LockPoints& GetLockPoints() const { return lockPoints; }
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2017-05-16 00:34:47 +02:00
|
|
|
// Adjusts the descendant state.
|
2016-03-17 13:33:31 +01:00
|
|
|
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
|
|
|
|
// Adjusts the ancestor state
|
2017-11-10 21:33:28 +01:00
|
|
|
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps);
|
2015-11-19 17:18:28 +01:00
|
|
|
// Updates the fee delta used for mining priority score, and the
|
|
|
|
// modified fees with descendants.
|
2015-10-26 19:06:06 +01:00
|
|
|
void UpdateFeeDelta(int64_t feeDelta);
|
2015-12-04 21:01:22 +01:00
|
|
|
// Update the LockPoints after a reorg
|
|
|
|
void UpdateLockPoints(const LockPoints& lp);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
|
|
|
uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
|
|
|
|
uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
|
2015-11-19 17:18:28 +01:00
|
|
|
CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
|
2015-10-29 19:06:13 +01:00
|
|
|
|
|
|
|
bool GetSpendsCoinbase() const { return spendsCoinbase; }
|
2016-03-17 13:33:31 +01:00
|
|
|
|
|
|
|
uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
|
|
|
|
uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
|
|
|
|
CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
|
2024-09-08 18:08:41 +02:00
|
|
|
int64_t GetSigOpCountWithAncestors() const { return nSigOpCountWithAncestors; }
|
Backport compact blocks functionality from bitcoin (#1966)
* Merge #8068: Compact Blocks
48efec8 Fix some minor compact block issues that came up in review (Matt Corallo)
ccd06b9 Elaborate bucket size math (Pieter Wuille)
0d4cb48 Use vTxHashes to optimize InitData significantly (Matt Corallo)
8119026 Provide a flat list of txid/terators to txn in CTxMemPool (Matt Corallo)
678ee97 Add BIP 152 to implemented BIPs list (Matt Corallo)
56ba516 Add reconstruction debug logging (Matt Corallo)
2f34a2e Get our "best three" peers to announce blocks using cmpctblocks (Matt Corallo)
927f8ee Add ability to fetch CNode by NodeId (Matt Corallo)
d25cd3e Add receiver-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
9c837d5 Add sender-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
00c4078 Add protocol messages for short-ids blocks (Matt Corallo)
e3b2222 Add some blockencodings tests (Matt Corallo)
f4f8f14 Add TestMemPoolEntryHelper::FromTx version for CTransaction (Matt Corallo)
85ad31e Add partial-block block encodings API (Matt Corallo)
5249dac Add COMPACTSIZE wrapper similar to VARINT for serialization (Matt Corallo)
cbda71c Move context-required checks from CheckBlockHeader to Contextual... (Matt Corallo)
7c29ec9 If AcceptBlockHeader returns true, pindex will be set. (Matt Corallo)
96806c3 Stop trimming when mapTx is empty (Pieter Wuille)
* Merge #8408: Prevent fingerprinting, disk-DoS with compact blocks
1d06e49 Ignore CMPCTBLOCK messages for pruned blocks (Suhas Daftuar)
1de2a46 Ignore GETBLOCKTXN requests for unknown blocks (Suhas Daftuar)
* Merge #8418: Add tests for compact blocks
45c7ddd Add p2p test for BIP 152 (compact blocks) (Suhas Daftuar)
9a22a6c Add support for compactblocks to mininode (Suhas Daftuar)
a8689fd Tests: refactor compact size serialization in mininode (Suhas Daftuar)
9c8593d Implement SipHash in Python (Pieter Wuille)
56c87e9 Allow changing BIP9 parameters on regtest (Suhas Daftuar)
* Merge #8505: Trivial: Fix typos in various files
1aacfc2 various typos (leijurv)
* Merge #8449: [Trivial] Do not shadow local variable, cleanup
a159f25 Remove redundand (and shadowing) declaration (Pavel Janík)
cce3024 Do not shadow local variable, cleanup (Pavel Janík)
* Merge #8739: [qa] Fix broken sendcmpct test in p2p-compactblocks.py
157254a Fix broken sendcmpct test in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8854: [qa] Fix race condition in p2p-compactblocks test
b5fd666 [qa] Fix race condition in p2p-compactblocks test (Suhas Daftuar)
* Merge #8393: Support for compact blocks together with segwit
27acfc1 [qa] Update p2p-compactblocks.py for compactblocks v2 (Suhas Daftuar)
422fac6 [qa] Add support for compactblocks v2 to mininode (Suhas Daftuar)
f5b9b8f [qa] Fix bug in mininode witness deserialization (Suhas Daftuar)
6aa28ab Use cmpctblock type 2 for segwit-enabled transfer (Pieter Wuille)
be7555f Fix overly-prescriptive p2p-segwit test for new fetch logic (Matt Corallo)
06128da Make GetFetchFlags always request witness objects from witness peers (Matt Corallo)
* Merge #8882: [qa] Fix race conditions in p2p-compactblocks.py and sendheaders.py
b55d941 [qa] Fix race condition in sendheaders.py (Suhas Daftuar)
6976db2 [qa] Another attempt to fix race condition in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8904: [qa] Fix compact block shortids for a test case
4cdece4 [qa] Fix compact block shortids for a test case (Dagur Valberg Johannsson)
* Merge #8637: Compact Block Tweaks (rebase of #8235)
3ac6de0 Align constant names for maximum compact block / blocktxn depth (Pieter Wuille)
b2e93a3 Add cmpctblock to debug help list (instagibbs)
fe998e9 More agressively filter compact block requests (Matt Corallo)
02a337d Dont remove a "preferred" cmpctblock peer if they provide a block (Matt Corallo)
* Merge #8975: Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/
6f2f639 Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/ (Jorge Timón)
* Merge #8968: Don't hold cs_main when calling ProcessNewBlock from a cmpctblock
72ca7d9 Don't hold cs_main when calling ProcessNewBlock from a cmpctblock (Matt Corallo)
* Merge #8995: Add missing cs_main lock to ::GETBLOCKTXN processing
dfe7906 Add missing cs_main lock to ::GETBLOCKTXN processing (Matt Corallo)
* Merge #8515: A few mempool removal optimizations
0334430 Add some missing includes (Pieter Wuille)
4100499 Return shared_ptr<CTransaction> from mempool removes (Pieter Wuille)
51f2783 Make removed and conflicted arguments optional to remove (Pieter Wuille)
f48211b Bypass removeRecursive in removeForReorg (Pieter Wuille)
* Merge #9026: Fix handling of invalid compact blocks
d4833ff Bump the protocol version to distinguish new banning behavior. (Suhas Daftuar)
88c3549 Fix compact block handling to not ban if block is invalid (Suhas Daftuar)
c93beac [qa] Test that invalid compactblocks don't result in ban (Suhas Daftuar)
* Merge #9039: Various serialization simplifcations and optimizations
d59a518 Use fixed preallocation instead of costly GetSerializeSize (Pieter Wuille)
25a211a Add optimized CSizeComputer serializers (Pieter Wuille)
a2929a2 Make CSerAction's ForRead() constexpr (Pieter Wuille)
a603925 Avoid -Wshadow errors (Pieter Wuille)
5284721 Get rid of nType and nVersion (Pieter Wuille)
657e05a Make GetSerializeSize a wrapper on top of CSizeComputer (Pieter Wuille)
fad9b66 Make nType and nVersion private and sometimes const (Pieter Wuille)
c2c5d42 Make streams' read and write return void (Pieter Wuille)
50e8a9c Remove unused ReadVersion and WriteVersion (Pieter Wuille)
* Merge #9058: Fixes for p2p-compactblocks.py test timeouts on travis (#8842)
dac53b5 Modify getblocktxn handler not to drop requests for old blocks (Russell Yanofsky)
55bfddc [qa] Fix stale data bug in test_compactblocks_not_at_tip (Russell Yanofsky)
47e9659 [qa] Fix bug in compactblocks v2 merge (Russell Yanofsky)
* Merge #9160: [trivial] Fix hungarian variable name
ec34648 [trivial] Fix hungarian variable name (Russell Yanofsky)
* Merge #9159: [qa] Wait for specific block announcement in p2p-compactblocks
dfa44d1 [qa] Wait for specific block announcement in p2p-compactblocks (Russell Yanofsky)
* Merge #9125: Make CBlock a vector of shared_ptr of CTransactions
b4e4ba4 Introduce convenience type CTransactionRef (Pieter Wuille)
1662b43 Make CBlock::vtx a vector of shared_ptr<CTransaction> (Pieter Wuille)
da60506 Add deserializing constructors to CTransaction and CMutableTransaction (Pieter Wuille)
0e85204 Add serialization for unique_ptr and shared_ptr (Pieter Wuille)
* Merge #8872: Remove block-request logic from INV message processing
037159c Remove block-request logic from INV message processing (Matt Corallo)
3451203 [qa] Respond to getheaders and do not assume a getdata on inv (Matt Corallo)
d768f15 [qa] Make comptool push blocks instead of relying on inv-fetch (mrbandrews)
* Merge #9199: Always drop the least preferred HB peer when adding a new one.
ca8549d Always drop the least preferred HB peer when adding a new one. (Gregory Maxwell)
* Merge #9233: Fix some typos
15fa95d Fix some typos (fsb4000)
* Merge #9260: Mrs Peacock in The Library with The Candlestick (killed main.{h,cpp})
76faa3c Rename the remaining main.{h,cpp} to validation.{h,cpp} (Matt Corallo)
e736772 Move network-msg-processing code out of main to its own file (Matt Corallo)
87c35f5 Remove orphan state wipe from UnloadBlockIndex. (Matt Corallo)
* Merge #9014: Fix block-connection performance regression
dd0df81 Document ConnectBlock connectTrace postconditions (Matt Corallo)
2d6e561 Switch pblock in ProcessNewBlock to a shared_ptr (Matt Corallo)
2736c44 Make the optional pblock in ActivateBestChain a shared_ptr (Matt Corallo)
ae4db44 Create a shared_ptr for the block we're connecting in ActivateBCS (Matt Corallo)
fd9d890 Keep blocks as shared_ptrs, instead of copying txn in ConnectTip (Matt Corallo)
6fdd43b Add struct to track block-connect-time-generated info for callbacks (Matt Corallo)
* Merge #9240: Remove txConflicted
a874ab5 remove internal tracking of mempool conflicts for reporting to wallet (Alex Morcos)
bf663f8 remove external usage of mempool conflict tracking (Alex Morcos)
* Merge #9344: Do not run functions with necessary side-effects in assert()
da9cdd2 Do not run functions with necessary side-effects in assert() (Gregory Maxwell)
* Merge #9273: Remove unused CDiskBlockPos* argument from ProcessNewBlock
a13fa4c Remove unused CDiskBlockPos* argument from ProcessNewBlock (Matt Corallo)
* Merge #9352: Attempt reconstruction from all compact block announcements
813ede9 [qa] Update compactblocks test for multi-peer reconstruction (Suhas Daftuar)
7017298 Allow compactblock reconstruction when block is in flight (Suhas Daftuar)
* Merge #9252: Release cs_main before calling ProcessNewBlock, or processing headers (cmpctblock handling)
bd02bdd Release cs_main before processing cmpctblock as header (Suhas Daftuar)
680b0c0 Release cs_main before calling ProcessNewBlock (cmpctblock handling) (Suhas Daftuar)
* Merge #9283: A few more CTransactionRef optimizations
91335ba Remove unused MakeTransactionRef overloads (Pieter Wuille)
6713f0f Make FillBlock consume txn_available to avoid shared_ptr copies (Pieter Wuille)
62607d7 Convert COrphanTx to keep a CTransactionRef (Pieter Wuille)
c44e4c4 Make AcceptToMemoryPool take CTransactionRef (Pieter Wuille)
* Merge #9375: Relay compact block messages prior to full block connection
02ee4eb Make most_recent_compact_block a pointer to a const (Matt Corallo)
73666ad Add comment to describe callers to ActivateBestChain (Matt Corallo)
962f7f0 Call ActivateBestChain without cs_main/with most_recent_block (Matt Corallo)
0df777d Use a temp pindex to avoid a const_cast in ProcessNewBlockHeaders (Matt Corallo)
c1ae4fc Avoid holding cs_most_recent_block while calling ReadBlockFromDisk (Matt Corallo)
9eb67f5 Ensure we meet the BIP 152 old-relay-types response requirements (Matt Corallo)
5749a85 Cache most-recently-connected compact block (Matt Corallo)
9eaec08 Cache most-recently-announced block's shared_ptr (Matt Corallo)
c802092 Relay compact block messages prior to full block connection (Matt Corallo)
6987219 Add a CValidationInterface::NewPoWValidBlock callback (Matt Corallo)
180586f Call AcceptBlock with the block's shared_ptr instead of CBlock& (Matt Corallo)
8baaba6 [qa] Avoid race in preciousblock test. (Matt Corallo)
9a0b2f4 [qa] Make compact blocks test construction using fetch methods (Matt Corallo)
8017547 Make CBlockIndex*es in net_processing const (Matt Corallo)
* Merge #9486: Make peer=%d log prints consistent
e6111b2 Make peer id logging consistent ("peer=%d" instead of "peer %d") (Matt Corallo)
* Merge #9400: Set peers as HB peers upon full block validation
d4781ac Set peers as HB peers upon full block validation (Gregory Sanders)
* Merge #9499: Use recent-rejects, orphans, and recently-replaced txn for compact-block-reconstruction
c594580 Add braces around AddToCompactExtraTransactions (Matt Corallo)
1ccfe9b Clarify comment about mempool/extra conflicts (Matt Corallo)
fac4c78 Make PartiallyDownloadedBlock::InitData's second param const (Matt Corallo)
b55b416 Add extra_count lower bound to compact reconstruction debug print (Matt Corallo)
863edb4 Consider all (<100k memusage) txn for compact-block-extra-txn cache (Matt Corallo)
7f8c8ca Consider all orphan txn for compact-block-extra-txn cache (Matt Corallo)
93380c5 Use replaced transactions in compact block reconstruction (Matt Corallo)
1531652 Keep shared_ptrs to recently-replaced txn for compact blocks (Matt Corallo)
edded80 Make ATMP optionally return the CTransactionRefs it replaced (Matt Corallo)
c735540 Move ORPHAN constants from validation.h to net_processing.h (Matt Corallo)
* Merge #9587: Do not shadow local variable named `tx`.
44f2baa Do not shadow local variable named `tx`. (Pavel Janík)
* Merge #9510: [trivial] Fix typos in comments
cc16d99 [trivial] Fix typos in comments (practicalswift)
* Merge #9604: [Trivial] add comment about setting peer as HB peer.
dd5b011 [Trivial] add comment about setting peer as HB peer. (John Newbery)
* Fix using of AcceptToMemoryPool in PrivateSend code
* add `override`
* fSupportsDesiredCmpctVersion
* bring back tx ressurection in DisconnectTip
* Fix delayed headers
* Remove unused CConnman::FindNode overload
* Fix typos and comments
* Fix minor code differences
* Don't use rejection cache for corrupted transactions
Partly based on https://github.com/bitcoin/bitcoin/pull/8525
* Backport missed cs_main locking changes
Missed from https://github.com/bitcoin/bitcoin/commit/58a215ce8c13b900cf982c39f8ee4879290d1a95
* Backport missed comments and mapBlockSource.emplace call
Missed from two commits:
https://github.com/bitcoin/bitcoin/commit/88c35491ab19f9afdf9b3fa9356a072f70ef2f55
https://github.com/bitcoin/bitcoin/commit/7c98ce584ec23bcddcba8cdb33efa6547212f6ef
* Add CheckPeerHeaders() helper and check in (nCount == 0) too
2018-04-11 13:06:01 +02:00
|
|
|
|
Merge #19478: Remove CTxMempool::mapLinks data structure member
296be8f58e02b39a58f017c52294aceed22c3ffd Get rid of unused functions CTxMemPool::GetMemPoolChildren, CTxMemPool::GetMemPoolParents (Jeremy Rubin)
46d955d196043cc297834baeebce31ff778dff80 Remove mapLinks in favor of entry inlined structs with iterator type erasure (Jeremy Rubin)
Pull request description:
Currently we have a peculiar data structure in the mempool called maplinks. Maplinks job is to track the in-pool children and parents of each transaction. This PR can be primarily understood and reviewed as a simple refactoring to remove this extra data structure, although it comes with a nice memory and performance improvement for free.
Maplinks is particularly peculiar because removing it is not as simple as just moving it's inner structure to the owning CTxMempoolEntry. Because TxLinks (the class storing the setEntries for parents and children) store txiters to each entry in the mempool corresponding to the parent or child, it means that the TxLinks type is "aware" of the boost multiindex (mapTx) it's coming from, which is in turn, aware of the entry type stored in mapTx. Thus we used maplinks to store this entry associated data we in an entirely separate data structure just to avoid a circular type reference caused by storing a txiter inside a CTxMempoolEntry.
It turns out, we can kill this circular reference by making use of iterator_to multiindex function and std::reference_wrapper. This allows us to get rid of the maplinks data structure and move the ownership of the parents/child sets to the entries themselves.
The benefit of this good all around, for any of the reasons given below the change would be acceptable, and it doesn't make the code harder to reason about or worse in any respect (as far as I can tell, there's no tradeoff).
### Simpler ownership model
No longer having to consistency check that mapLinks did have records for our CTxMempoolEntry, impossible to have a mapLinks entry outlive or incorrectly die before a CTxMempoolEntry.
### Memory Usage
We get rid of a O(Transactions) sized map in the mempool, which is a long lived data structure.
### Performance
If you have a CTxMemPoolEntry, you immediately know the address of it's children/parents, rather than having to do a O(log(Transactions)) lookup via maplinks (which we do very often). We do it in *so many* places that a true benchmark has to look at a full running node, but it is easy enough to show an improvement in this case.
The ComplexMemPool shows a good coherence check that we see the expected result of it being 12.5% faster / 1.14x faster.
```
Before:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.40462, 0.277222, 0.285339, 0.279793
After:
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 1.22586, 0.243831, 0.247076, 0.244596
```
The ComplexMemPool benchmark only checks doing addUnchecked and TrimToSize for 800 transactions. While this bench does a good job of hammering the relevant types of function, it doesn't test everything.
Subbing in 5000 transactions shows a that the advantage isn't completely wiped out by other asymptotic factors (this isn't the only bottleneck in growing the mempool), but it's only a bit proportionally slower (10.8%, 1.12x), which adds evidence that this will be a good change for performance minded users.
```
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 59.1321, 11.5919, 12.235, 11.7068
# Benchmark, evals, iterations, total, min, max, median
ComplexMemPool, 5, 1, 52.1307, 10.2641, 10.5206, 10.4306
```
I don't think it's possible to come up with an example of where a maplinks based design would have better performance, but it's something for reviewers to consider.
# Discussion
## Why maplinks in the first place?
I spoke with the author of mapLinks (sdaftuar) a while back, and my recollection from our conversation was that it was implemented because he did not know how to resolve the circular dependency at the time, and there was no other reason for making it a separate map.
## Is iterator_to weird?
iterator_to is expressly for this purpose, see https://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to
> iterator_to provides a way to retrieve an iterator to an element from a pointer to the element, thus making iterators and pointers interchangeable for the purposes of element pointing (not so for traversal) in many situations. This notwithstanding, it is not the aim of iterator_to to promote the usage of pointers as substitutes for real iterators: the latter are specifically designed for handling the elements of a container, and not only benefit from the iterator orientation of container interfaces, but are also capable of exposing many more programming bugs than raw pointers, both at compile and run time. iterator_to is thus meant to be used in scenarios where access via iterators is not suitable or desireable:
>
> - Interoperability with preexisting APIs based on pointers or references.
> - Publication of pointer-based interfaces (for instance, when designing a C-compatible library).
> - The exposure of pointers in place of iterators can act as a type erasure barrier effectively decoupling the user of the code from the implementation detail of which particular container is being used. Similar techniques, like the famous Pimpl idiom, are used in large projects to reduce dependencies and build times.
> - Self-referencing contexts where an element acts upon its owner container and no iterator to itself is available.
In other words, iterator_to is the perfect tool for the job by the last reason given. Under the hood it should just be a simple pointer cast and have no major runtime overhead (depending on if the function call is inlined).
Edit by laanwj: removed at sign from the description
ACKs for top commit:
jonatack:
re-ACK 296be8f per `git range-diff ab338a19 3ba1665 296be8f`, sanity check gcc 10.2 debug build is clean.
hebasto:
re-ACK 296be8f58e02b39a58f017c52294aceed22c3ffd, only rebased since my [previous](https://github.com/bitcoin/bitcoin/pull/19478#pullrequestreview-482400727) review (verified with `git range-diff`).
Tree-SHA512: f5c30a4936fcde6ae32a02823c303b3568a747c2681d11f87df88a149f984a6d3b4c81f391859afbeb68864ef7f6a3d8779f74a58e3de701b3d51f78e498682e
2020-09-07 12:06:38 +02:00
|
|
|
const Parents& GetMemPoolParentsConst() const { return m_parents; }
|
|
|
|
const Children& GetMemPoolChildrenConst() const { return m_children; }
|
|
|
|
Parents& GetMemPoolParents() const { return m_parents; }
|
|
|
|
Children& GetMemPoolChildren() const { return m_children; }
|
|
|
|
|
Backport compact blocks functionality from bitcoin (#1966)
* Merge #8068: Compact Blocks
48efec8 Fix some minor compact block issues that came up in review (Matt Corallo)
ccd06b9 Elaborate bucket size math (Pieter Wuille)
0d4cb48 Use vTxHashes to optimize InitData significantly (Matt Corallo)
8119026 Provide a flat list of txid/terators to txn in CTxMemPool (Matt Corallo)
678ee97 Add BIP 152 to implemented BIPs list (Matt Corallo)
56ba516 Add reconstruction debug logging (Matt Corallo)
2f34a2e Get our "best three" peers to announce blocks using cmpctblocks (Matt Corallo)
927f8ee Add ability to fetch CNode by NodeId (Matt Corallo)
d25cd3e Add receiver-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
9c837d5 Add sender-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
00c4078 Add protocol messages for short-ids blocks (Matt Corallo)
e3b2222 Add some blockencodings tests (Matt Corallo)
f4f8f14 Add TestMemPoolEntryHelper::FromTx version for CTransaction (Matt Corallo)
85ad31e Add partial-block block encodings API (Matt Corallo)
5249dac Add COMPACTSIZE wrapper similar to VARINT for serialization (Matt Corallo)
cbda71c Move context-required checks from CheckBlockHeader to Contextual... (Matt Corallo)
7c29ec9 If AcceptBlockHeader returns true, pindex will be set. (Matt Corallo)
96806c3 Stop trimming when mapTx is empty (Pieter Wuille)
* Merge #8408: Prevent fingerprinting, disk-DoS with compact blocks
1d06e49 Ignore CMPCTBLOCK messages for pruned blocks (Suhas Daftuar)
1de2a46 Ignore GETBLOCKTXN requests for unknown blocks (Suhas Daftuar)
* Merge #8418: Add tests for compact blocks
45c7ddd Add p2p test for BIP 152 (compact blocks) (Suhas Daftuar)
9a22a6c Add support for compactblocks to mininode (Suhas Daftuar)
a8689fd Tests: refactor compact size serialization in mininode (Suhas Daftuar)
9c8593d Implement SipHash in Python (Pieter Wuille)
56c87e9 Allow changing BIP9 parameters on regtest (Suhas Daftuar)
* Merge #8505: Trivial: Fix typos in various files
1aacfc2 various typos (leijurv)
* Merge #8449: [Trivial] Do not shadow local variable, cleanup
a159f25 Remove redundand (and shadowing) declaration (Pavel Janík)
cce3024 Do not shadow local variable, cleanup (Pavel Janík)
* Merge #8739: [qa] Fix broken sendcmpct test in p2p-compactblocks.py
157254a Fix broken sendcmpct test in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8854: [qa] Fix race condition in p2p-compactblocks test
b5fd666 [qa] Fix race condition in p2p-compactblocks test (Suhas Daftuar)
* Merge #8393: Support for compact blocks together with segwit
27acfc1 [qa] Update p2p-compactblocks.py for compactblocks v2 (Suhas Daftuar)
422fac6 [qa] Add support for compactblocks v2 to mininode (Suhas Daftuar)
f5b9b8f [qa] Fix bug in mininode witness deserialization (Suhas Daftuar)
6aa28ab Use cmpctblock type 2 for segwit-enabled transfer (Pieter Wuille)
be7555f Fix overly-prescriptive p2p-segwit test for new fetch logic (Matt Corallo)
06128da Make GetFetchFlags always request witness objects from witness peers (Matt Corallo)
* Merge #8882: [qa] Fix race conditions in p2p-compactblocks.py and sendheaders.py
b55d941 [qa] Fix race condition in sendheaders.py (Suhas Daftuar)
6976db2 [qa] Another attempt to fix race condition in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8904: [qa] Fix compact block shortids for a test case
4cdece4 [qa] Fix compact block shortids for a test case (Dagur Valberg Johannsson)
* Merge #8637: Compact Block Tweaks (rebase of #8235)
3ac6de0 Align constant names for maximum compact block / blocktxn depth (Pieter Wuille)
b2e93a3 Add cmpctblock to debug help list (instagibbs)
fe998e9 More agressively filter compact block requests (Matt Corallo)
02a337d Dont remove a "preferred" cmpctblock peer if they provide a block (Matt Corallo)
* Merge #8975: Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/
6f2f639 Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/ (Jorge Timón)
* Merge #8968: Don't hold cs_main when calling ProcessNewBlock from a cmpctblock
72ca7d9 Don't hold cs_main when calling ProcessNewBlock from a cmpctblock (Matt Corallo)
* Merge #8995: Add missing cs_main lock to ::GETBLOCKTXN processing
dfe7906 Add missing cs_main lock to ::GETBLOCKTXN processing (Matt Corallo)
* Merge #8515: A few mempool removal optimizations
0334430 Add some missing includes (Pieter Wuille)
4100499 Return shared_ptr<CTransaction> from mempool removes (Pieter Wuille)
51f2783 Make removed and conflicted arguments optional to remove (Pieter Wuille)
f48211b Bypass removeRecursive in removeForReorg (Pieter Wuille)
* Merge #9026: Fix handling of invalid compact blocks
d4833ff Bump the protocol version to distinguish new banning behavior. (Suhas Daftuar)
88c3549 Fix compact block handling to not ban if block is invalid (Suhas Daftuar)
c93beac [qa] Test that invalid compactblocks don't result in ban (Suhas Daftuar)
* Merge #9039: Various serialization simplifcations and optimizations
d59a518 Use fixed preallocation instead of costly GetSerializeSize (Pieter Wuille)
25a211a Add optimized CSizeComputer serializers (Pieter Wuille)
a2929a2 Make CSerAction's ForRead() constexpr (Pieter Wuille)
a603925 Avoid -Wshadow errors (Pieter Wuille)
5284721 Get rid of nType and nVersion (Pieter Wuille)
657e05a Make GetSerializeSize a wrapper on top of CSizeComputer (Pieter Wuille)
fad9b66 Make nType and nVersion private and sometimes const (Pieter Wuille)
c2c5d42 Make streams' read and write return void (Pieter Wuille)
50e8a9c Remove unused ReadVersion and WriteVersion (Pieter Wuille)
* Merge #9058: Fixes for p2p-compactblocks.py test timeouts on travis (#8842)
dac53b5 Modify getblocktxn handler not to drop requests for old blocks (Russell Yanofsky)
55bfddc [qa] Fix stale data bug in test_compactblocks_not_at_tip (Russell Yanofsky)
47e9659 [qa] Fix bug in compactblocks v2 merge (Russell Yanofsky)
* Merge #9160: [trivial] Fix hungarian variable name
ec34648 [trivial] Fix hungarian variable name (Russell Yanofsky)
* Merge #9159: [qa] Wait for specific block announcement in p2p-compactblocks
dfa44d1 [qa] Wait for specific block announcement in p2p-compactblocks (Russell Yanofsky)
* Merge #9125: Make CBlock a vector of shared_ptr of CTransactions
b4e4ba4 Introduce convenience type CTransactionRef (Pieter Wuille)
1662b43 Make CBlock::vtx a vector of shared_ptr<CTransaction> (Pieter Wuille)
da60506 Add deserializing constructors to CTransaction and CMutableTransaction (Pieter Wuille)
0e85204 Add serialization for unique_ptr and shared_ptr (Pieter Wuille)
* Merge #8872: Remove block-request logic from INV message processing
037159c Remove block-request logic from INV message processing (Matt Corallo)
3451203 [qa] Respond to getheaders and do not assume a getdata on inv (Matt Corallo)
d768f15 [qa] Make comptool push blocks instead of relying on inv-fetch (mrbandrews)
* Merge #9199: Always drop the least preferred HB peer when adding a new one.
ca8549d Always drop the least preferred HB peer when adding a new one. (Gregory Maxwell)
* Merge #9233: Fix some typos
15fa95d Fix some typos (fsb4000)
* Merge #9260: Mrs Peacock in The Library with The Candlestick (killed main.{h,cpp})
76faa3c Rename the remaining main.{h,cpp} to validation.{h,cpp} (Matt Corallo)
e736772 Move network-msg-processing code out of main to its own file (Matt Corallo)
87c35f5 Remove orphan state wipe from UnloadBlockIndex. (Matt Corallo)
* Merge #9014: Fix block-connection performance regression
dd0df81 Document ConnectBlock connectTrace postconditions (Matt Corallo)
2d6e561 Switch pblock in ProcessNewBlock to a shared_ptr (Matt Corallo)
2736c44 Make the optional pblock in ActivateBestChain a shared_ptr (Matt Corallo)
ae4db44 Create a shared_ptr for the block we're connecting in ActivateBCS (Matt Corallo)
fd9d890 Keep blocks as shared_ptrs, instead of copying txn in ConnectTip (Matt Corallo)
6fdd43b Add struct to track block-connect-time-generated info for callbacks (Matt Corallo)
* Merge #9240: Remove txConflicted
a874ab5 remove internal tracking of mempool conflicts for reporting to wallet (Alex Morcos)
bf663f8 remove external usage of mempool conflict tracking (Alex Morcos)
* Merge #9344: Do not run functions with necessary side-effects in assert()
da9cdd2 Do not run functions with necessary side-effects in assert() (Gregory Maxwell)
* Merge #9273: Remove unused CDiskBlockPos* argument from ProcessNewBlock
a13fa4c Remove unused CDiskBlockPos* argument from ProcessNewBlock (Matt Corallo)
* Merge #9352: Attempt reconstruction from all compact block announcements
813ede9 [qa] Update compactblocks test for multi-peer reconstruction (Suhas Daftuar)
7017298 Allow compactblock reconstruction when block is in flight (Suhas Daftuar)
* Merge #9252: Release cs_main before calling ProcessNewBlock, or processing headers (cmpctblock handling)
bd02bdd Release cs_main before processing cmpctblock as header (Suhas Daftuar)
680b0c0 Release cs_main before calling ProcessNewBlock (cmpctblock handling) (Suhas Daftuar)
* Merge #9283: A few more CTransactionRef optimizations
91335ba Remove unused MakeTransactionRef overloads (Pieter Wuille)
6713f0f Make FillBlock consume txn_available to avoid shared_ptr copies (Pieter Wuille)
62607d7 Convert COrphanTx to keep a CTransactionRef (Pieter Wuille)
c44e4c4 Make AcceptToMemoryPool take CTransactionRef (Pieter Wuille)
* Merge #9375: Relay compact block messages prior to full block connection
02ee4eb Make most_recent_compact_block a pointer to a const (Matt Corallo)
73666ad Add comment to describe callers to ActivateBestChain (Matt Corallo)
962f7f0 Call ActivateBestChain without cs_main/with most_recent_block (Matt Corallo)
0df777d Use a temp pindex to avoid a const_cast in ProcessNewBlockHeaders (Matt Corallo)
c1ae4fc Avoid holding cs_most_recent_block while calling ReadBlockFromDisk (Matt Corallo)
9eb67f5 Ensure we meet the BIP 152 old-relay-types response requirements (Matt Corallo)
5749a85 Cache most-recently-connected compact block (Matt Corallo)
9eaec08 Cache most-recently-announced block's shared_ptr (Matt Corallo)
c802092 Relay compact block messages prior to full block connection (Matt Corallo)
6987219 Add a CValidationInterface::NewPoWValidBlock callback (Matt Corallo)
180586f Call AcceptBlock with the block's shared_ptr instead of CBlock& (Matt Corallo)
8baaba6 [qa] Avoid race in preciousblock test. (Matt Corallo)
9a0b2f4 [qa] Make compact blocks test construction using fetch methods (Matt Corallo)
8017547 Make CBlockIndex*es in net_processing const (Matt Corallo)
* Merge #9486: Make peer=%d log prints consistent
e6111b2 Make peer id logging consistent ("peer=%d" instead of "peer %d") (Matt Corallo)
* Merge #9400: Set peers as HB peers upon full block validation
d4781ac Set peers as HB peers upon full block validation (Gregory Sanders)
* Merge #9499: Use recent-rejects, orphans, and recently-replaced txn for compact-block-reconstruction
c594580 Add braces around AddToCompactExtraTransactions (Matt Corallo)
1ccfe9b Clarify comment about mempool/extra conflicts (Matt Corallo)
fac4c78 Make PartiallyDownloadedBlock::InitData's second param const (Matt Corallo)
b55b416 Add extra_count lower bound to compact reconstruction debug print (Matt Corallo)
863edb4 Consider all (<100k memusage) txn for compact-block-extra-txn cache (Matt Corallo)
7f8c8ca Consider all orphan txn for compact-block-extra-txn cache (Matt Corallo)
93380c5 Use replaced transactions in compact block reconstruction (Matt Corallo)
1531652 Keep shared_ptrs to recently-replaced txn for compact blocks (Matt Corallo)
edded80 Make ATMP optionally return the CTransactionRefs it replaced (Matt Corallo)
c735540 Move ORPHAN constants from validation.h to net_processing.h (Matt Corallo)
* Merge #9587: Do not shadow local variable named `tx`.
44f2baa Do not shadow local variable named `tx`. (Pavel Janík)
* Merge #9510: [trivial] Fix typos in comments
cc16d99 [trivial] Fix typos in comments (practicalswift)
* Merge #9604: [Trivial] add comment about setting peer as HB peer.
dd5b011 [Trivial] add comment about setting peer as HB peer. (John Newbery)
* Fix using of AcceptToMemoryPool in PrivateSend code
* add `override`
* fSupportsDesiredCmpctVersion
* bring back tx ressurection in DisconnectTip
* Fix delayed headers
* Remove unused CConnman::FindNode overload
* Fix typos and comments
* Fix minor code differences
* Don't use rejection cache for corrupted transactions
Partly based on https://github.com/bitcoin/bitcoin/pull/8525
* Backport missed cs_main locking changes
Missed from https://github.com/bitcoin/bitcoin/commit/58a215ce8c13b900cf982c39f8ee4879290d1a95
* Backport missed comments and mapBlockSource.emplace call
Missed from two commits:
https://github.com/bitcoin/bitcoin/commit/88c35491ab19f9afdf9b3fa9356a072f70ef2f55
https://github.com/bitcoin/bitcoin/commit/7c98ce584ec23bcddcba8cdb33efa6547212f6ef
* Add CheckPeerHeaders() helper and check in (nCount == 0) too
2018-04-11 13:06:01 +02:00
|
|
|
mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
|
2018-12-10 09:14:19 +01:00
|
|
|
|
|
|
|
// If this is a proTx, this will be the hash of the key for which this ProTx was valid
|
|
|
|
mutable uint256 validForProTxKey;
|
|
|
|
mutable bool isKeyChangeProTx{false};
|
2021-02-24 09:07:10 +01:00
|
|
|
mutable Epoch::Marker m_epoch_marker; //!< epoch when last touched, useful for graph algorithms
|
2015-07-15 20:47:45 +02:00
|
|
|
};
|
|
|
|
|
2019-02-23 17:04:20 +01:00
|
|
|
// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
|
2015-06-24 10:32:20 +02:00
|
|
|
struct mempoolentry_txid
|
|
|
|
{
|
|
|
|
typedef uint256 result_type;
|
|
|
|
result_type operator() (const CTxMemPoolEntry &entry) const
|
|
|
|
{
|
|
|
|
return entry.GetTx().GetHash();
|
|
|
|
}
|
2017-05-30 18:42:22 +02:00
|
|
|
|
|
|
|
result_type operator() (const CTransactionRef& tx) const
|
|
|
|
{
|
|
|
|
return tx->GetHash();
|
|
|
|
}
|
2015-06-24 10:32:20 +02:00
|
|
|
};
|
|
|
|
|
2015-11-19 17:18:28 +01:00
|
|
|
/** \class CompareTxMemPoolEntryByDescendantScore
|
2015-07-15 20:47:45 +02:00
|
|
|
*
|
2015-11-19 17:18:28 +01:00
|
|
|
* Sort an entry by max(score/size of entry's tx, score/size with all descendants).
|
2015-07-15 20:47:45 +02:00
|
|
|
*/
|
2015-11-19 17:18:28 +01:00
|
|
|
class CompareTxMemPoolEntryByDescendantScore
|
2015-06-24 10:32:20 +02:00
|
|
|
{
|
|
|
|
public:
|
2017-12-07 18:01:22 +01:00
|
|
|
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
|
2015-06-24 10:32:20 +02:00
|
|
|
{
|
2018-01-15 15:36:25 +01:00
|
|
|
double a_mod_fee, a_size, b_mod_fee, b_size;
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2018-01-15 15:36:25 +01:00
|
|
|
GetModFeeAndSize(a, a_mod_fee, a_size);
|
|
|
|
GetModFeeAndSize(b, b_mod_fee, b_size);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
|
|
|
// Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
|
2018-01-15 15:36:25 +01:00
|
|
|
double f1 = a_mod_fee * b_size;
|
|
|
|
double f2 = a_size * b_mod_fee;
|
2015-07-15 20:47:45 +02:00
|
|
|
|
|
|
|
if (f1 == f2) {
|
2015-09-24 19:21:31 +02:00
|
|
|
return a.GetTime() >= b.GetTime();
|
2015-07-15 20:47:45 +02:00
|
|
|
}
|
2015-09-24 19:21:31 +02:00
|
|
|
return f1 < f2;
|
2015-07-15 20:47:45 +02:00
|
|
|
}
|
|
|
|
|
2018-01-15 15:36:25 +01:00
|
|
|
// Return the fee/size we're using for sorting this entry.
|
|
|
|
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
|
2015-07-15 20:47:45 +02:00
|
|
|
{
|
2018-01-15 15:36:25 +01:00
|
|
|
// Compare feerate with descendants to feerate of the transaction, and
|
|
|
|
// return the fee/size for the max.
|
2015-11-19 17:18:28 +01:00
|
|
|
double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
|
|
|
|
double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
|
2018-01-15 15:36:25 +01:00
|
|
|
|
|
|
|
if (f2 > f1) {
|
|
|
|
mod_fee = a.GetModFeesWithDescendants();
|
|
|
|
size = a.GetSizeWithDescendants();
|
|
|
|
} else {
|
|
|
|
mod_fee = a.GetModifiedFee();
|
|
|
|
size = a.GetTxSize();
|
|
|
|
}
|
2015-07-15 20:47:45 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-10-26 19:06:06 +01:00
|
|
|
/** \class CompareTxMemPoolEntryByScore
|
|
|
|
*
|
2018-02-08 22:05:00 +01:00
|
|
|
* Sort by feerate of entry (fee/size) in descending order
|
|
|
|
* This is only used for transaction relay, so we use GetFee()
|
|
|
|
* instead of GetModifiedFee() to avoid leaking prioritization
|
|
|
|
* information via the sort order.
|
2015-10-26 19:06:06 +01:00
|
|
|
*/
|
|
|
|
class CompareTxMemPoolEntryByScore
|
|
|
|
{
|
|
|
|
public:
|
2017-12-07 18:01:22 +01:00
|
|
|
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
|
2015-10-26 19:06:06 +01:00
|
|
|
{
|
2018-02-08 22:05:00 +01:00
|
|
|
double f1 = (double)a.GetFee() * b.GetTxSize();
|
|
|
|
double f2 = (double)b.GetFee() * a.GetTxSize();
|
2015-10-26 19:06:06 +01:00
|
|
|
if (f1 == f2) {
|
|
|
|
return b.GetTx().GetHash() < a.GetTx().GetHash();
|
|
|
|
}
|
|
|
|
return f1 > f2;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
class CompareTxMemPoolEntryByEntryTime
|
|
|
|
{
|
|
|
|
public:
|
2017-12-07 18:01:22 +01:00
|
|
|
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
|
2015-07-15 20:47:45 +02:00
|
|
|
{
|
|
|
|
return a.GetTime() < b.GetTime();
|
2015-06-24 10:32:20 +02:00
|
|
|
}
|
2013-11-11 08:35:14 +01:00
|
|
|
};
|
|
|
|
|
2018-01-15 15:36:25 +01:00
|
|
|
/** \class CompareTxMemPoolEntryByAncestorScore
|
|
|
|
*
|
|
|
|
* Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
|
|
|
|
*/
|
2016-03-17 13:33:31 +01:00
|
|
|
class CompareTxMemPoolEntryByAncestorFee
|
|
|
|
{
|
|
|
|
public:
|
2018-01-15 15:36:25 +01:00
|
|
|
template<typename T>
|
|
|
|
bool operator()(const T& a, const T& b) const
|
2016-03-17 13:33:31 +01:00
|
|
|
{
|
2018-01-15 15:36:25 +01:00
|
|
|
double a_mod_fee, a_size, b_mod_fee, b_size;
|
2016-03-17 13:33:31 +01:00
|
|
|
|
2018-01-15 15:36:25 +01:00
|
|
|
GetModFeeAndSize(a, a_mod_fee, a_size);
|
|
|
|
GetModFeeAndSize(b, b_mod_fee, b_size);
|
2016-03-17 13:33:31 +01:00
|
|
|
|
|
|
|
// Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
|
2018-01-15 15:36:25 +01:00
|
|
|
double f1 = a_mod_fee * b_size;
|
|
|
|
double f2 = a_size * b_mod_fee;
|
2016-03-17 13:33:31 +01:00
|
|
|
|
|
|
|
if (f1 == f2) {
|
|
|
|
return a.GetTx().GetHash() < b.GetTx().GetHash();
|
|
|
|
}
|
|
|
|
return f1 > f2;
|
|
|
|
}
|
2018-01-15 15:36:25 +01:00
|
|
|
|
|
|
|
// Return the fee/size we're using for sorting this entry.
|
|
|
|
template <typename T>
|
|
|
|
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
|
|
|
|
{
|
|
|
|
// Compare feerate with ancestors to feerate of the transaction, and
|
|
|
|
// return the fee/size for the min.
|
|
|
|
double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
|
|
|
|
double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
|
|
|
|
|
|
|
|
if (f1 > f2) {
|
|
|
|
mod_fee = a.GetModFeesWithAncestors();
|
|
|
|
size = a.GetSizeWithAncestors();
|
|
|
|
} else {
|
|
|
|
mod_fee = a.GetModifiedFee();
|
|
|
|
size = a.GetTxSize();
|
|
|
|
}
|
|
|
|
}
|
2016-03-17 13:33:31 +01:00
|
|
|
};
|
|
|
|
|
2016-03-05 06:49:47 +01:00
|
|
|
// Multi_index tag names
|
|
|
|
struct descendant_score {};
|
|
|
|
struct entry_time {};
|
2016-03-17 13:33:31 +01:00
|
|
|
struct ancestor_score {};
|
2016-03-05 06:49:47 +01:00
|
|
|
|
2014-08-26 22:28:32 +02:00
|
|
|
class CBlockPolicyEstimator;
|
2024-04-04 12:27:33 +02:00
|
|
|
class CDeterministicMNManager;
|
2014-03-17 13:19:54 +01:00
|
|
|
|
2016-06-08 14:01:05 +02:00
|
|
|
/**
|
|
|
|
* Information about a mempool transaction.
|
|
|
|
*/
|
|
|
|
struct TxMempoolInfo
|
|
|
|
{
|
|
|
|
/** The transaction itself */
|
2016-11-21 10:51:32 +01:00
|
|
|
CTransactionRef tx;
|
2016-06-08 14:01:05 +02:00
|
|
|
|
|
|
|
/** Time the transaction entered the mempool. */
|
2019-10-02 16:55:03 +02:00
|
|
|
std::chrono::seconds m_time;
|
2016-06-08 14:01:05 +02:00
|
|
|
|
2019-10-04 19:27:52 +02:00
|
|
|
/** Fee of the transaction. */
|
|
|
|
CAmount fee;
|
|
|
|
|
|
|
|
/** Virtual size of the transaction. */
|
|
|
|
size_t vsize;
|
2016-11-02 11:12:48 +01:00
|
|
|
|
|
|
|
/** The fee delta. */
|
|
|
|
int64_t nFeeDelta;
|
2016-06-08 14:01:05 +02:00
|
|
|
};
|
|
|
|
|
2017-01-24 10:07:50 +01:00
|
|
|
/** Reason why a transaction was removed from the mempool,
|
|
|
|
* this is passed to the notification signal.
|
|
|
|
*/
|
|
|
|
enum class MemPoolRemovalReason {
|
2018-10-01 03:13:42 +02:00
|
|
|
EXPIRY, //!< Expired from mempool
|
|
|
|
SIZELIMIT, //!< Removed in size limiting
|
|
|
|
REORG, //!< Removed for reorganization
|
|
|
|
BLOCK, //!< Removed for block
|
|
|
|
CONFLICT, //!< Removed for conflict with in-block transaction
|
2019-07-30 22:01:06 +02:00
|
|
|
MANUAL //!< Removed manually
|
2017-01-24 10:07:50 +01:00
|
|
|
};
|
|
|
|
|
2014-11-17 03:29:09 +01:00
|
|
|
/**
|
2016-09-26 15:10:10 +02:00
|
|
|
* CTxMemPool stores valid-according-to-the-current-best-chain transactions
|
|
|
|
* that may be included in the next block.
|
2013-08-27 07:51:57 +02:00
|
|
|
*
|
2016-09-26 15:10:10 +02:00
|
|
|
* Transactions are added when they are seen on the network (or created by the
|
|
|
|
* local node), but not all transactions seen are added to the pool. For
|
|
|
|
* example, the following new transactions will not be added to the mempool:
|
2017-01-29 16:05:06 +01:00
|
|
|
* - a transaction which doesn't meet the minimum fee requirements.
|
2016-09-26 15:10:10 +02:00
|
|
|
* - a new transaction that double-spends an input of a transaction already in
|
2018-09-20 14:39:34 +02:00
|
|
|
* the pool.
|
2016-09-26 15:10:10 +02:00
|
|
|
* - a non-standard transaction.
|
2015-07-15 20:47:45 +02:00
|
|
|
*
|
|
|
|
* CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
|
|
|
|
*
|
2015-10-26 19:06:06 +01:00
|
|
|
* mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
|
2015-07-15 20:47:45 +02:00
|
|
|
* - transaction hash
|
2018-02-08 22:05:00 +01:00
|
|
|
* - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)]
|
2015-10-02 23:43:30 +02:00
|
|
|
* - time in mempool
|
2018-02-08 22:05:00 +01:00
|
|
|
* - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)]
|
2015-07-15 20:47:45 +02:00
|
|
|
*
|
|
|
|
* Note: the term "descendant" refers to in-mempool transactions that depend on
|
|
|
|
* this one, while "ancestor" refers to in-mempool transactions that a given
|
|
|
|
* transaction depends on.
|
|
|
|
*
|
|
|
|
* In order for the feerate sort to remain correct, we must update transactions
|
|
|
|
* in the mempool when new descendants arrive. To facilitate this, we track
|
|
|
|
* the set of in-mempool direct parents and direct children in mapLinks. Within
|
|
|
|
* each CTxMemPoolEntry, we track the size and fees of all descendants.
|
|
|
|
*
|
|
|
|
* Usually when a new transaction is added to the mempool, it has no in-mempool
|
|
|
|
* children (because any such children would be an orphan). So in
|
|
|
|
* addUnchecked(), we:
|
|
|
|
* - update a new entry's setMemPoolParents to include all in-mempool parents
|
|
|
|
* - update the new entry's direct parents to include the new tx as a child
|
|
|
|
* - update all ancestors of the transaction to include the new tx's size/fee
|
|
|
|
*
|
|
|
|
* When a transaction is removed from the mempool, we must:
|
|
|
|
* - update all in-mempool parents to not track the tx in setMemPoolChildren
|
|
|
|
* - update all ancestors to not include the tx's size/fees in descendant state
|
|
|
|
* - update all in-mempool children to not include it as a parent
|
|
|
|
*
|
|
|
|
* These happen in UpdateForRemoveFromMempool(). (Note that when removing a
|
|
|
|
* transaction along with its descendants, we must calculate that set of
|
|
|
|
* transactions to be removed before doing the removal, or else the mempool can
|
|
|
|
* be in an inconsistent state where it's impossible to walk the ancestors of
|
|
|
|
* a transaction.)
|
|
|
|
*
|
|
|
|
* In the event of a reorg, the assumption that a newly added tx has no
|
|
|
|
* in-mempool children is false. In particular, the mempool is in an
|
|
|
|
* inconsistent state while new transactions are being added, because there may
|
|
|
|
* be descendant transactions of a tx coming from a disconnected block that are
|
|
|
|
* unreachable from just looking at transactions in the mempool (the linking
|
|
|
|
* transactions may also be in the disconnected block, waiting to be added).
|
|
|
|
* Because of this, there's not much benefit in trying to search for in-mempool
|
|
|
|
* children in addUnchecked(). Instead, in the special case of transactions
|
|
|
|
* being added from a disconnected block, we require the caller to clean up the
|
|
|
|
* state, to account for in-mempool, out-of-block descendants for all the
|
|
|
|
* in-block transactions by calling UpdateTransactionsFromBlock(). Note that
|
|
|
|
* until this is called, the mempool state is not consistent, and in particular
|
|
|
|
* mapLinks may not be correct (and therefore functions like
|
|
|
|
* CalculateMemPoolAncestors() and CalculateDescendants() that rely
|
|
|
|
* on them to walk the mempool are not generally safe to use).
|
|
|
|
*
|
|
|
|
* Computational limits:
|
|
|
|
*
|
|
|
|
* Updating all in-mempool ancestors of a newly added transaction can be slow,
|
|
|
|
* if no bound exists on how many in-mempool ancestors there may be.
|
|
|
|
* CalculateMemPoolAncestors() takes configurable limits that are designed to
|
|
|
|
* prevent these calculations from being too CPU intensive.
|
|
|
|
*
|
2013-08-27 07:51:57 +02:00
|
|
|
*/
|
|
|
|
class CTxMemPool
|
|
|
|
{
|
2024-01-18 21:58:39 +01:00
|
|
|
protected:
|
2023-02-20 20:31:40 +01:00
|
|
|
const int m_check_ratio; //!< Value n means that 1 times in n we check.
|
|
|
|
std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
|
2021-05-21 08:27:52 +02:00
|
|
|
CBlockPolicyEstimator* const minerPolicyEstimator;
|
2024-04-04 12:27:33 +02:00
|
|
|
CDeterministicMNManager* m_dmnman{nullptr};
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2021-02-08 20:36:33 +01:00
|
|
|
uint64_t totalTxSize GUARDED_BY(cs); //!< sum of all mempool tx' byte sizes
|
|
|
|
CAmount m_total_fee GUARDED_BY(cs); //!< sum of all mempool tx's fees (NOT modified fee)
|
|
|
|
uint64_t cachedInnerUsage GUARDED_BY(cs); //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
|
2014-07-03 20:25:32 +02:00
|
|
|
|
2021-05-21 08:27:52 +02:00
|
|
|
mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs);
|
|
|
|
mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs);
|
|
|
|
mutable double rollingMinimumFeeRate GUARDED_BY(cs); //!< minimum fee to get into the pool, decreases exponentially
|
2021-02-24 09:07:10 +01:00
|
|
|
mutable Epoch m_epoch GUARDED_BY(cs);
|
2015-10-02 23:19:55 +02:00
|
|
|
|
2024-08-26 17:35:12 +02:00
|
|
|
// In-memory counter for external mempool tracking purposes.
|
|
|
|
// This number is incremented once every time a transaction
|
|
|
|
// is added or removed from the mempool for any reason.
|
|
|
|
mutable uint64_t m_sequence_number{1};
|
|
|
|
|
2018-05-05 16:32:19 +02:00
|
|
|
void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2019-05-01 16:06:11 +02:00
|
|
|
bool m_is_loaded GUARDED_BY(cs){false};
|
|
|
|
|
2013-08-27 07:51:57 +02:00
|
|
|
public:
|
2015-10-13 09:43:15 +02:00
|
|
|
|
|
|
|
static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
|
|
|
|
|
2015-06-24 10:32:20 +02:00
|
|
|
typedef boost::multi_index_container<
|
|
|
|
CTxMemPoolEntry,
|
|
|
|
boost::multi_index::indexed_by<
|
|
|
|
// sorted by txid
|
2016-05-18 10:59:00 +02:00
|
|
|
boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
|
2015-06-24 10:32:20 +02:00
|
|
|
// sorted by fee rate
|
|
|
|
boost::multi_index::ordered_non_unique<
|
2016-03-05 06:49:47 +01:00
|
|
|
boost::multi_index::tag<descendant_score>,
|
2015-06-24 10:32:20 +02:00
|
|
|
boost::multi_index::identity<CTxMemPoolEntry>,
|
2015-11-19 17:18:28 +01:00
|
|
|
CompareTxMemPoolEntryByDescendantScore
|
2015-10-02 23:43:30 +02:00
|
|
|
>,
|
|
|
|
// sorted by entry time
|
|
|
|
boost::multi_index::ordered_non_unique<
|
2016-03-05 06:49:47 +01:00
|
|
|
boost::multi_index::tag<entry_time>,
|
2015-10-02 23:43:30 +02:00
|
|
|
boost::multi_index::identity<CTxMemPoolEntry>,
|
|
|
|
CompareTxMemPoolEntryByEntryTime
|
2016-03-17 13:33:31 +01:00
|
|
|
>,
|
|
|
|
// sorted by fee rate with ancestors
|
|
|
|
boost::multi_index::ordered_non_unique<
|
|
|
|
boost::multi_index::tag<ancestor_score>,
|
|
|
|
boost::multi_index::identity<CTxMemPoolEntry>,
|
|
|
|
CompareTxMemPoolEntryByAncestorFee
|
2015-06-24 10:32:20 +02:00
|
|
|
>
|
|
|
|
>
|
|
|
|
> indexed_transaction_set;
|
|
|
|
|
2019-01-15 19:41:59 +01:00
|
|
|
/**
|
|
|
|
* This mutex needs to be locked when accessing `mapTx` or other members
|
|
|
|
* that are guarded by it.
|
|
|
|
*
|
|
|
|
* @par Consistency guarantees
|
|
|
|
* By design, it is guaranteed that:
|
|
|
|
* 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
|
2021-10-20 07:13:44 +02:00
|
|
|
* that is consistent with current chain tip (`ActiveChain()` and
|
2019-07-24 17:45:04 +02:00
|
|
|
* `CoinsTip()`) and is fully populated. Fully populated means that if the
|
2019-01-15 19:41:59 +01:00
|
|
|
* current active chain is missing transactions that were present in a
|
|
|
|
* previously active chain, all the missing transactions will have been
|
|
|
|
* re-added to the mempool and should be present if they meet size and
|
|
|
|
* consistency constraints.
|
|
|
|
* 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
|
|
|
|
* consistent with some chain that was active since `cs_main` was last
|
|
|
|
* locked, and that is fully populated as described above. It is ok for
|
|
|
|
* code that only needs to query or remove transactions from the mempool
|
|
|
|
* to lock just `mempool.cs` without `cs_main`.
|
|
|
|
*
|
|
|
|
* To provide these guarantees, it is necessary to lock both `cs_main` and
|
|
|
|
* `mempool.cs` whenever adding transactions to the mempool and whenever
|
|
|
|
* changing the chain tip. It's necessary to keep both mutexes locked until
|
|
|
|
* the mempool is consistent with the new chain tip and fully populated.
|
|
|
|
*/
|
|
|
|
mutable RecursiveMutex cs;
|
2018-05-14 16:29:17 +02:00
|
|
|
indexed_transaction_set mapTx GUARDED_BY(cs);
|
Backport compact blocks functionality from bitcoin (#1966)
* Merge #8068: Compact Blocks
48efec8 Fix some minor compact block issues that came up in review (Matt Corallo)
ccd06b9 Elaborate bucket size math (Pieter Wuille)
0d4cb48 Use vTxHashes to optimize InitData significantly (Matt Corallo)
8119026 Provide a flat list of txid/terators to txn in CTxMemPool (Matt Corallo)
678ee97 Add BIP 152 to implemented BIPs list (Matt Corallo)
56ba516 Add reconstruction debug logging (Matt Corallo)
2f34a2e Get our "best three" peers to announce blocks using cmpctblocks (Matt Corallo)
927f8ee Add ability to fetch CNode by NodeId (Matt Corallo)
d25cd3e Add receiver-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
9c837d5 Add sender-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
00c4078 Add protocol messages for short-ids blocks (Matt Corallo)
e3b2222 Add some blockencodings tests (Matt Corallo)
f4f8f14 Add TestMemPoolEntryHelper::FromTx version for CTransaction (Matt Corallo)
85ad31e Add partial-block block encodings API (Matt Corallo)
5249dac Add COMPACTSIZE wrapper similar to VARINT for serialization (Matt Corallo)
cbda71c Move context-required checks from CheckBlockHeader to Contextual... (Matt Corallo)
7c29ec9 If AcceptBlockHeader returns true, pindex will be set. (Matt Corallo)
96806c3 Stop trimming when mapTx is empty (Pieter Wuille)
* Merge #8408: Prevent fingerprinting, disk-DoS with compact blocks
1d06e49 Ignore CMPCTBLOCK messages for pruned blocks (Suhas Daftuar)
1de2a46 Ignore GETBLOCKTXN requests for unknown blocks (Suhas Daftuar)
* Merge #8418: Add tests for compact blocks
45c7ddd Add p2p test for BIP 152 (compact blocks) (Suhas Daftuar)
9a22a6c Add support for compactblocks to mininode (Suhas Daftuar)
a8689fd Tests: refactor compact size serialization in mininode (Suhas Daftuar)
9c8593d Implement SipHash in Python (Pieter Wuille)
56c87e9 Allow changing BIP9 parameters on regtest (Suhas Daftuar)
* Merge #8505: Trivial: Fix typos in various files
1aacfc2 various typos (leijurv)
* Merge #8449: [Trivial] Do not shadow local variable, cleanup
a159f25 Remove redundand (and shadowing) declaration (Pavel Janík)
cce3024 Do not shadow local variable, cleanup (Pavel Janík)
* Merge #8739: [qa] Fix broken sendcmpct test in p2p-compactblocks.py
157254a Fix broken sendcmpct test in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8854: [qa] Fix race condition in p2p-compactblocks test
b5fd666 [qa] Fix race condition in p2p-compactblocks test (Suhas Daftuar)
* Merge #8393: Support for compact blocks together with segwit
27acfc1 [qa] Update p2p-compactblocks.py for compactblocks v2 (Suhas Daftuar)
422fac6 [qa] Add support for compactblocks v2 to mininode (Suhas Daftuar)
f5b9b8f [qa] Fix bug in mininode witness deserialization (Suhas Daftuar)
6aa28ab Use cmpctblock type 2 for segwit-enabled transfer (Pieter Wuille)
be7555f Fix overly-prescriptive p2p-segwit test for new fetch logic (Matt Corallo)
06128da Make GetFetchFlags always request witness objects from witness peers (Matt Corallo)
* Merge #8882: [qa] Fix race conditions in p2p-compactblocks.py and sendheaders.py
b55d941 [qa] Fix race condition in sendheaders.py (Suhas Daftuar)
6976db2 [qa] Another attempt to fix race condition in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8904: [qa] Fix compact block shortids for a test case
4cdece4 [qa] Fix compact block shortids for a test case (Dagur Valberg Johannsson)
* Merge #8637: Compact Block Tweaks (rebase of #8235)
3ac6de0 Align constant names for maximum compact block / blocktxn depth (Pieter Wuille)
b2e93a3 Add cmpctblock to debug help list (instagibbs)
fe998e9 More agressively filter compact block requests (Matt Corallo)
02a337d Dont remove a "preferred" cmpctblock peer if they provide a block (Matt Corallo)
* Merge #8975: Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/
6f2f639 Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/ (Jorge Timón)
* Merge #8968: Don't hold cs_main when calling ProcessNewBlock from a cmpctblock
72ca7d9 Don't hold cs_main when calling ProcessNewBlock from a cmpctblock (Matt Corallo)
* Merge #8995: Add missing cs_main lock to ::GETBLOCKTXN processing
dfe7906 Add missing cs_main lock to ::GETBLOCKTXN processing (Matt Corallo)
* Merge #8515: A few mempool removal optimizations
0334430 Add some missing includes (Pieter Wuille)
4100499 Return shared_ptr<CTransaction> from mempool removes (Pieter Wuille)
51f2783 Make removed and conflicted arguments optional to remove (Pieter Wuille)
f48211b Bypass removeRecursive in removeForReorg (Pieter Wuille)
* Merge #9026: Fix handling of invalid compact blocks
d4833ff Bump the protocol version to distinguish new banning behavior. (Suhas Daftuar)
88c3549 Fix compact block handling to not ban if block is invalid (Suhas Daftuar)
c93beac [qa] Test that invalid compactblocks don't result in ban (Suhas Daftuar)
* Merge #9039: Various serialization simplifcations and optimizations
d59a518 Use fixed preallocation instead of costly GetSerializeSize (Pieter Wuille)
25a211a Add optimized CSizeComputer serializers (Pieter Wuille)
a2929a2 Make CSerAction's ForRead() constexpr (Pieter Wuille)
a603925 Avoid -Wshadow errors (Pieter Wuille)
5284721 Get rid of nType and nVersion (Pieter Wuille)
657e05a Make GetSerializeSize a wrapper on top of CSizeComputer (Pieter Wuille)
fad9b66 Make nType and nVersion private and sometimes const (Pieter Wuille)
c2c5d42 Make streams' read and write return void (Pieter Wuille)
50e8a9c Remove unused ReadVersion and WriteVersion (Pieter Wuille)
* Merge #9058: Fixes for p2p-compactblocks.py test timeouts on travis (#8842)
dac53b5 Modify getblocktxn handler not to drop requests for old blocks (Russell Yanofsky)
55bfddc [qa] Fix stale data bug in test_compactblocks_not_at_tip (Russell Yanofsky)
47e9659 [qa] Fix bug in compactblocks v2 merge (Russell Yanofsky)
* Merge #9160: [trivial] Fix hungarian variable name
ec34648 [trivial] Fix hungarian variable name (Russell Yanofsky)
* Merge #9159: [qa] Wait for specific block announcement in p2p-compactblocks
dfa44d1 [qa] Wait for specific block announcement in p2p-compactblocks (Russell Yanofsky)
* Merge #9125: Make CBlock a vector of shared_ptr of CTransactions
b4e4ba4 Introduce convenience type CTransactionRef (Pieter Wuille)
1662b43 Make CBlock::vtx a vector of shared_ptr<CTransaction> (Pieter Wuille)
da60506 Add deserializing constructors to CTransaction and CMutableTransaction (Pieter Wuille)
0e85204 Add serialization for unique_ptr and shared_ptr (Pieter Wuille)
* Merge #8872: Remove block-request logic from INV message processing
037159c Remove block-request logic from INV message processing (Matt Corallo)
3451203 [qa] Respond to getheaders and do not assume a getdata on inv (Matt Corallo)
d768f15 [qa] Make comptool push blocks instead of relying on inv-fetch (mrbandrews)
* Merge #9199: Always drop the least preferred HB peer when adding a new one.
ca8549d Always drop the least preferred HB peer when adding a new one. (Gregory Maxwell)
* Merge #9233: Fix some typos
15fa95d Fix some typos (fsb4000)
* Merge #9260: Mrs Peacock in The Library with The Candlestick (killed main.{h,cpp})
76faa3c Rename the remaining main.{h,cpp} to validation.{h,cpp} (Matt Corallo)
e736772 Move network-msg-processing code out of main to its own file (Matt Corallo)
87c35f5 Remove orphan state wipe from UnloadBlockIndex. (Matt Corallo)
* Merge #9014: Fix block-connection performance regression
dd0df81 Document ConnectBlock connectTrace postconditions (Matt Corallo)
2d6e561 Switch pblock in ProcessNewBlock to a shared_ptr (Matt Corallo)
2736c44 Make the optional pblock in ActivateBestChain a shared_ptr (Matt Corallo)
ae4db44 Create a shared_ptr for the block we're connecting in ActivateBCS (Matt Corallo)
fd9d890 Keep blocks as shared_ptrs, instead of copying txn in ConnectTip (Matt Corallo)
6fdd43b Add struct to track block-connect-time-generated info for callbacks (Matt Corallo)
* Merge #9240: Remove txConflicted
a874ab5 remove internal tracking of mempool conflicts for reporting to wallet (Alex Morcos)
bf663f8 remove external usage of mempool conflict tracking (Alex Morcos)
* Merge #9344: Do not run functions with necessary side-effects in assert()
da9cdd2 Do not run functions with necessary side-effects in assert() (Gregory Maxwell)
* Merge #9273: Remove unused CDiskBlockPos* argument from ProcessNewBlock
a13fa4c Remove unused CDiskBlockPos* argument from ProcessNewBlock (Matt Corallo)
* Merge #9352: Attempt reconstruction from all compact block announcements
813ede9 [qa] Update compactblocks test for multi-peer reconstruction (Suhas Daftuar)
7017298 Allow compactblock reconstruction when block is in flight (Suhas Daftuar)
* Merge #9252: Release cs_main before calling ProcessNewBlock, or processing headers (cmpctblock handling)
bd02bdd Release cs_main before processing cmpctblock as header (Suhas Daftuar)
680b0c0 Release cs_main before calling ProcessNewBlock (cmpctblock handling) (Suhas Daftuar)
* Merge #9283: A few more CTransactionRef optimizations
91335ba Remove unused MakeTransactionRef overloads (Pieter Wuille)
6713f0f Make FillBlock consume txn_available to avoid shared_ptr copies (Pieter Wuille)
62607d7 Convert COrphanTx to keep a CTransactionRef (Pieter Wuille)
c44e4c4 Make AcceptToMemoryPool take CTransactionRef (Pieter Wuille)
* Merge #9375: Relay compact block messages prior to full block connection
02ee4eb Make most_recent_compact_block a pointer to a const (Matt Corallo)
73666ad Add comment to describe callers to ActivateBestChain (Matt Corallo)
962f7f0 Call ActivateBestChain without cs_main/with most_recent_block (Matt Corallo)
0df777d Use a temp pindex to avoid a const_cast in ProcessNewBlockHeaders (Matt Corallo)
c1ae4fc Avoid holding cs_most_recent_block while calling ReadBlockFromDisk (Matt Corallo)
9eb67f5 Ensure we meet the BIP 152 old-relay-types response requirements (Matt Corallo)
5749a85 Cache most-recently-connected compact block (Matt Corallo)
9eaec08 Cache most-recently-announced block's shared_ptr (Matt Corallo)
c802092 Relay compact block messages prior to full block connection (Matt Corallo)
6987219 Add a CValidationInterface::NewPoWValidBlock callback (Matt Corallo)
180586f Call AcceptBlock with the block's shared_ptr instead of CBlock& (Matt Corallo)
8baaba6 [qa] Avoid race in preciousblock test. (Matt Corallo)
9a0b2f4 [qa] Make compact blocks test construction using fetch methods (Matt Corallo)
8017547 Make CBlockIndex*es in net_processing const (Matt Corallo)
* Merge #9486: Make peer=%d log prints consistent
e6111b2 Make peer id logging consistent ("peer=%d" instead of "peer %d") (Matt Corallo)
* Merge #9400: Set peers as HB peers upon full block validation
d4781ac Set peers as HB peers upon full block validation (Gregory Sanders)
* Merge #9499: Use recent-rejects, orphans, and recently-replaced txn for compact-block-reconstruction
c594580 Add braces around AddToCompactExtraTransactions (Matt Corallo)
1ccfe9b Clarify comment about mempool/extra conflicts (Matt Corallo)
fac4c78 Make PartiallyDownloadedBlock::InitData's second param const (Matt Corallo)
b55b416 Add extra_count lower bound to compact reconstruction debug print (Matt Corallo)
863edb4 Consider all (<100k memusage) txn for compact-block-extra-txn cache (Matt Corallo)
7f8c8ca Consider all orphan txn for compact-block-extra-txn cache (Matt Corallo)
93380c5 Use replaced transactions in compact block reconstruction (Matt Corallo)
1531652 Keep shared_ptrs to recently-replaced txn for compact blocks (Matt Corallo)
edded80 Make ATMP optionally return the CTransactionRefs it replaced (Matt Corallo)
c735540 Move ORPHAN constants from validation.h to net_processing.h (Matt Corallo)
* Merge #9587: Do not shadow local variable named `tx`.
44f2baa Do not shadow local variable named `tx`. (Pavel Janík)
* Merge #9510: [trivial] Fix typos in comments
cc16d99 [trivial] Fix typos in comments (practicalswift)
* Merge #9604: [Trivial] add comment about setting peer as HB peer.
dd5b011 [Trivial] add comment about setting peer as HB peer. (John Newbery)
* Fix using of AcceptToMemoryPool in PrivateSend code
* add `override`
* fSupportsDesiredCmpctVersion
* bring back tx ressurection in DisconnectTip
* Fix delayed headers
* Remove unused CConnman::FindNode overload
* Fix typos and comments
* Fix minor code differences
* Don't use rejection cache for corrupted transactions
Partly based on https://github.com/bitcoin/bitcoin/pull/8525
* Backport missed cs_main locking changes
Missed from https://github.com/bitcoin/bitcoin/commit/58a215ce8c13b900cf982c39f8ee4879290d1a95
* Backport missed comments and mapBlockSource.emplace call
Missed from two commits:
https://github.com/bitcoin/bitcoin/commit/88c35491ab19f9afdf9b3fa9356a072f70ef2f55
https://github.com/bitcoin/bitcoin/commit/7c98ce584ec23bcddcba8cdb33efa6547212f6ef
* Add CheckPeerHeaders() helper and check in (nCount == 0) too
2018-04-11 13:06:01 +02:00
|
|
|
|
2018-06-26 13:05:01 +02:00
|
|
|
using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
|
2022-05-05 16:24:51 +02:00
|
|
|
std::vector<std::pair<uint256, txiter> > vTxHashes GUARDED_BY(cs); //!< All tx hashes/entries in mapTx, in random order
|
Backport compact blocks functionality from bitcoin (#1966)
* Merge #8068: Compact Blocks
48efec8 Fix some minor compact block issues that came up in review (Matt Corallo)
ccd06b9 Elaborate bucket size math (Pieter Wuille)
0d4cb48 Use vTxHashes to optimize InitData significantly (Matt Corallo)
8119026 Provide a flat list of txid/terators to txn in CTxMemPool (Matt Corallo)
678ee97 Add BIP 152 to implemented BIPs list (Matt Corallo)
56ba516 Add reconstruction debug logging (Matt Corallo)
2f34a2e Get our "best three" peers to announce blocks using cmpctblocks (Matt Corallo)
927f8ee Add ability to fetch CNode by NodeId (Matt Corallo)
d25cd3e Add receiver-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
9c837d5 Add sender-side protocol implementation for CMPCTBLOCK stuff (Matt Corallo)
00c4078 Add protocol messages for short-ids blocks (Matt Corallo)
e3b2222 Add some blockencodings tests (Matt Corallo)
f4f8f14 Add TestMemPoolEntryHelper::FromTx version for CTransaction (Matt Corallo)
85ad31e Add partial-block block encodings API (Matt Corallo)
5249dac Add COMPACTSIZE wrapper similar to VARINT for serialization (Matt Corallo)
cbda71c Move context-required checks from CheckBlockHeader to Contextual... (Matt Corallo)
7c29ec9 If AcceptBlockHeader returns true, pindex will be set. (Matt Corallo)
96806c3 Stop trimming when mapTx is empty (Pieter Wuille)
* Merge #8408: Prevent fingerprinting, disk-DoS with compact blocks
1d06e49 Ignore CMPCTBLOCK messages for pruned blocks (Suhas Daftuar)
1de2a46 Ignore GETBLOCKTXN requests for unknown blocks (Suhas Daftuar)
* Merge #8418: Add tests for compact blocks
45c7ddd Add p2p test for BIP 152 (compact blocks) (Suhas Daftuar)
9a22a6c Add support for compactblocks to mininode (Suhas Daftuar)
a8689fd Tests: refactor compact size serialization in mininode (Suhas Daftuar)
9c8593d Implement SipHash in Python (Pieter Wuille)
56c87e9 Allow changing BIP9 parameters on regtest (Suhas Daftuar)
* Merge #8505: Trivial: Fix typos in various files
1aacfc2 various typos (leijurv)
* Merge #8449: [Trivial] Do not shadow local variable, cleanup
a159f25 Remove redundand (and shadowing) declaration (Pavel Janík)
cce3024 Do not shadow local variable, cleanup (Pavel Janík)
* Merge #8739: [qa] Fix broken sendcmpct test in p2p-compactblocks.py
157254a Fix broken sendcmpct test in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8854: [qa] Fix race condition in p2p-compactblocks test
b5fd666 [qa] Fix race condition in p2p-compactblocks test (Suhas Daftuar)
* Merge #8393: Support for compact blocks together with segwit
27acfc1 [qa] Update p2p-compactblocks.py for compactblocks v2 (Suhas Daftuar)
422fac6 [qa] Add support for compactblocks v2 to mininode (Suhas Daftuar)
f5b9b8f [qa] Fix bug in mininode witness deserialization (Suhas Daftuar)
6aa28ab Use cmpctblock type 2 for segwit-enabled transfer (Pieter Wuille)
be7555f Fix overly-prescriptive p2p-segwit test for new fetch logic (Matt Corallo)
06128da Make GetFetchFlags always request witness objects from witness peers (Matt Corallo)
* Merge #8882: [qa] Fix race conditions in p2p-compactblocks.py and sendheaders.py
b55d941 [qa] Fix race condition in sendheaders.py (Suhas Daftuar)
6976db2 [qa] Another attempt to fix race condition in p2p-compactblocks.py (Suhas Daftuar)
* Merge #8904: [qa] Fix compact block shortids for a test case
4cdece4 [qa] Fix compact block shortids for a test case (Dagur Valberg Johannsson)
* Merge #8637: Compact Block Tweaks (rebase of #8235)
3ac6de0 Align constant names for maximum compact block / blocktxn depth (Pieter Wuille)
b2e93a3 Add cmpctblock to debug help list (instagibbs)
fe998e9 More agressively filter compact block requests (Matt Corallo)
02a337d Dont remove a "preferred" cmpctblock peer if they provide a block (Matt Corallo)
* Merge #8975: Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/
6f2f639 Chainparams: Trivial: In AppInit2(), s/Params()/chainparams/ (Jorge Timón)
* Merge #8968: Don't hold cs_main when calling ProcessNewBlock from a cmpctblock
72ca7d9 Don't hold cs_main when calling ProcessNewBlock from a cmpctblock (Matt Corallo)
* Merge #8995: Add missing cs_main lock to ::GETBLOCKTXN processing
dfe7906 Add missing cs_main lock to ::GETBLOCKTXN processing (Matt Corallo)
* Merge #8515: A few mempool removal optimizations
0334430 Add some missing includes (Pieter Wuille)
4100499 Return shared_ptr<CTransaction> from mempool removes (Pieter Wuille)
51f2783 Make removed and conflicted arguments optional to remove (Pieter Wuille)
f48211b Bypass removeRecursive in removeForReorg (Pieter Wuille)
* Merge #9026: Fix handling of invalid compact blocks
d4833ff Bump the protocol version to distinguish new banning behavior. (Suhas Daftuar)
88c3549 Fix compact block handling to not ban if block is invalid (Suhas Daftuar)
c93beac [qa] Test that invalid compactblocks don't result in ban (Suhas Daftuar)
* Merge #9039: Various serialization simplifcations and optimizations
d59a518 Use fixed preallocation instead of costly GetSerializeSize (Pieter Wuille)
25a211a Add optimized CSizeComputer serializers (Pieter Wuille)
a2929a2 Make CSerAction's ForRead() constexpr (Pieter Wuille)
a603925 Avoid -Wshadow errors (Pieter Wuille)
5284721 Get rid of nType and nVersion (Pieter Wuille)
657e05a Make GetSerializeSize a wrapper on top of CSizeComputer (Pieter Wuille)
fad9b66 Make nType and nVersion private and sometimes const (Pieter Wuille)
c2c5d42 Make streams' read and write return void (Pieter Wuille)
50e8a9c Remove unused ReadVersion and WriteVersion (Pieter Wuille)
* Merge #9058: Fixes for p2p-compactblocks.py test timeouts on travis (#8842)
dac53b5 Modify getblocktxn handler not to drop requests for old blocks (Russell Yanofsky)
55bfddc [qa] Fix stale data bug in test_compactblocks_not_at_tip (Russell Yanofsky)
47e9659 [qa] Fix bug in compactblocks v2 merge (Russell Yanofsky)
* Merge #9160: [trivial] Fix hungarian variable name
ec34648 [trivial] Fix hungarian variable name (Russell Yanofsky)
* Merge #9159: [qa] Wait for specific block announcement in p2p-compactblocks
dfa44d1 [qa] Wait for specific block announcement in p2p-compactblocks (Russell Yanofsky)
* Merge #9125: Make CBlock a vector of shared_ptr of CTransactions
b4e4ba4 Introduce convenience type CTransactionRef (Pieter Wuille)
1662b43 Make CBlock::vtx a vector of shared_ptr<CTransaction> (Pieter Wuille)
da60506 Add deserializing constructors to CTransaction and CMutableTransaction (Pieter Wuille)
0e85204 Add serialization for unique_ptr and shared_ptr (Pieter Wuille)
* Merge #8872: Remove block-request logic from INV message processing
037159c Remove block-request logic from INV message processing (Matt Corallo)
3451203 [qa] Respond to getheaders and do not assume a getdata on inv (Matt Corallo)
d768f15 [qa] Make comptool push blocks instead of relying on inv-fetch (mrbandrews)
* Merge #9199: Always drop the least preferred HB peer when adding a new one.
ca8549d Always drop the least preferred HB peer when adding a new one. (Gregory Maxwell)
* Merge #9233: Fix some typos
15fa95d Fix some typos (fsb4000)
* Merge #9260: Mrs Peacock in The Library with The Candlestick (killed main.{h,cpp})
76faa3c Rename the remaining main.{h,cpp} to validation.{h,cpp} (Matt Corallo)
e736772 Move network-msg-processing code out of main to its own file (Matt Corallo)
87c35f5 Remove orphan state wipe from UnloadBlockIndex. (Matt Corallo)
* Merge #9014: Fix block-connection performance regression
dd0df81 Document ConnectBlock connectTrace postconditions (Matt Corallo)
2d6e561 Switch pblock in ProcessNewBlock to a shared_ptr (Matt Corallo)
2736c44 Make the optional pblock in ActivateBestChain a shared_ptr (Matt Corallo)
ae4db44 Create a shared_ptr for the block we're connecting in ActivateBCS (Matt Corallo)
fd9d890 Keep blocks as shared_ptrs, instead of copying txn in ConnectTip (Matt Corallo)
6fdd43b Add struct to track block-connect-time-generated info for callbacks (Matt Corallo)
* Merge #9240: Remove txConflicted
a874ab5 remove internal tracking of mempool conflicts for reporting to wallet (Alex Morcos)
bf663f8 remove external usage of mempool conflict tracking (Alex Morcos)
* Merge #9344: Do not run functions with necessary side-effects in assert()
da9cdd2 Do not run functions with necessary side-effects in assert() (Gregory Maxwell)
* Merge #9273: Remove unused CDiskBlockPos* argument from ProcessNewBlock
a13fa4c Remove unused CDiskBlockPos* argument from ProcessNewBlock (Matt Corallo)
* Merge #9352: Attempt reconstruction from all compact block announcements
813ede9 [qa] Update compactblocks test for multi-peer reconstruction (Suhas Daftuar)
7017298 Allow compactblock reconstruction when block is in flight (Suhas Daftuar)
* Merge #9252: Release cs_main before calling ProcessNewBlock, or processing headers (cmpctblock handling)
bd02bdd Release cs_main before processing cmpctblock as header (Suhas Daftuar)
680b0c0 Release cs_main before calling ProcessNewBlock (cmpctblock handling) (Suhas Daftuar)
* Merge #9283: A few more CTransactionRef optimizations
91335ba Remove unused MakeTransactionRef overloads (Pieter Wuille)
6713f0f Make FillBlock consume txn_available to avoid shared_ptr copies (Pieter Wuille)
62607d7 Convert COrphanTx to keep a CTransactionRef (Pieter Wuille)
c44e4c4 Make AcceptToMemoryPool take CTransactionRef (Pieter Wuille)
* Merge #9375: Relay compact block messages prior to full block connection
02ee4eb Make most_recent_compact_block a pointer to a const (Matt Corallo)
73666ad Add comment to describe callers to ActivateBestChain (Matt Corallo)
962f7f0 Call ActivateBestChain without cs_main/with most_recent_block (Matt Corallo)
0df777d Use a temp pindex to avoid a const_cast in ProcessNewBlockHeaders (Matt Corallo)
c1ae4fc Avoid holding cs_most_recent_block while calling ReadBlockFromDisk (Matt Corallo)
9eb67f5 Ensure we meet the BIP 152 old-relay-types response requirements (Matt Corallo)
5749a85 Cache most-recently-connected compact block (Matt Corallo)
9eaec08 Cache most-recently-announced block's shared_ptr (Matt Corallo)
c802092 Relay compact block messages prior to full block connection (Matt Corallo)
6987219 Add a CValidationInterface::NewPoWValidBlock callback (Matt Corallo)
180586f Call AcceptBlock with the block's shared_ptr instead of CBlock& (Matt Corallo)
8baaba6 [qa] Avoid race in preciousblock test. (Matt Corallo)
9a0b2f4 [qa] Make compact blocks test construction using fetch methods (Matt Corallo)
8017547 Make CBlockIndex*es in net_processing const (Matt Corallo)
* Merge #9486: Make peer=%d log prints consistent
e6111b2 Make peer id logging consistent ("peer=%d" instead of "peer %d") (Matt Corallo)
* Merge #9400: Set peers as HB peers upon full block validation
d4781ac Set peers as HB peers upon full block validation (Gregory Sanders)
* Merge #9499: Use recent-rejects, orphans, and recently-replaced txn for compact-block-reconstruction
c594580 Add braces around AddToCompactExtraTransactions (Matt Corallo)
1ccfe9b Clarify comment about mempool/extra conflicts (Matt Corallo)
fac4c78 Make PartiallyDownloadedBlock::InitData's second param const (Matt Corallo)
b55b416 Add extra_count lower bound to compact reconstruction debug print (Matt Corallo)
863edb4 Consider all (<100k memusage) txn for compact-block-extra-txn cache (Matt Corallo)
7f8c8ca Consider all orphan txn for compact-block-extra-txn cache (Matt Corallo)
93380c5 Use replaced transactions in compact block reconstruction (Matt Corallo)
1531652 Keep shared_ptrs to recently-replaced txn for compact blocks (Matt Corallo)
edded80 Make ATMP optionally return the CTransactionRefs it replaced (Matt Corallo)
c735540 Move ORPHAN constants from validation.h to net_processing.h (Matt Corallo)
* Merge #9587: Do not shadow local variable named `tx`.
44f2baa Do not shadow local variable named `tx`. (Pavel Janík)
* Merge #9510: [trivial] Fix typos in comments
cc16d99 [trivial] Fix typos in comments (practicalswift)
* Merge #9604: [Trivial] add comment about setting peer as HB peer.
dd5b011 [Trivial] add comment about setting peer as HB peer. (John Newbery)
* Fix using of AcceptToMemoryPool in PrivateSend code
* add `override`
* fSupportsDesiredCmpctVersion
* bring back tx ressurection in DisconnectTip
* Fix delayed headers
* Remove unused CConnman::FindNode overload
* Fix typos and comments
* Fix minor code differences
* Don't use rejection cache for corrupted transactions
Partly based on https://github.com/bitcoin/bitcoin/pull/8525
* Backport missed cs_main locking changes
Missed from https://github.com/bitcoin/bitcoin/commit/58a215ce8c13b900cf982c39f8ee4879290d1a95
* Backport missed comments and mapBlockSource.emplace call
Missed from two commits:
https://github.com/bitcoin/bitcoin/commit/88c35491ab19f9afdf9b3fa9356a072f70ef2f55
https://github.com/bitcoin/bitcoin/commit/7c98ce584ec23bcddcba8cdb33efa6547212f6ef
* Add CheckPeerHeaders() helper and check in (nCount == 0) too
2018-04-11 13:06:01 +02:00
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
typedef std::set<txiter, CompareIteratorByHash> setEntries;
|
|
|
|
|
2018-06-11 15:35:42 +02:00
|
|
|
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
private:
|
|
|
|
typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
|
|
|
|
|
|
|
|
|
2016-04-04 22:37:43 +02:00
|
|
|
typedef std::map<CMempoolAddressDeltaKey, CMempoolAddressDelta, CMempoolAddressDeltaKeyCompare> addressDeltaMap;
|
|
|
|
addressDeltaMap mapAddress;
|
|
|
|
|
|
|
|
typedef std::map<uint256, std::vector<CMempoolAddressDeltaKey> > addressDeltaMapInserted;
|
|
|
|
addressDeltaMapInserted mapAddressInserted;
|
|
|
|
|
2016-05-16 20:23:01 +02:00
|
|
|
typedef std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare> mapSpentIndex;
|
|
|
|
mapSpentIndex mapSpent;
|
|
|
|
|
|
|
|
typedef std::map<uint256, std::vector<CSpentIndexKey> > mapSpentIndexInserted;
|
|
|
|
mapSpentIndexInserted mapSpentInserted;
|
|
|
|
|
2018-12-10 06:03:57 +01:00
|
|
|
std::multimap<uint256, uint256> mapProTxRefs; // proTxHash -> transaction (all TXs that refer to an existing proTx)
|
2018-03-12 12:14:11 +01:00
|
|
|
std::map<CService, uint256> mapProTxAddresses;
|
2018-02-14 14:42:06 +01:00
|
|
|
std::map<CKeyID, uint256> mapProTxPubKeyIDs;
|
2018-10-21 21:45:16 +02:00
|
|
|
std::map<uint256, uint256> mapProTxBlsPubKeyHashes;
|
2018-10-25 16:29:50 +02:00
|
|
|
std::map<COutPoint, uint256> mapProTxCollaterals;
|
2023-07-24 18:39:38 +02:00
|
|
|
std::map<uint256, int /* expiry height */> mapAssetUnlockExpiry; // tx hash -> height
|
2018-02-14 14:42:06 +01:00
|
|
|
|
2020-09-04 12:34:38 +02:00
|
|
|
void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2018-05-05 16:32:19 +02:00
|
|
|
std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2016-06-08 14:01:05 +02:00
|
|
|
|
2020-09-16 00:05:08 +02:00
|
|
|
/**
|
|
|
|
* Track locally submitted transactions to periodically retry initial broadcast.
|
|
|
|
*/
|
2022-05-06 06:04:50 +02:00
|
|
|
std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs);
|
|
|
|
|
Merge bitcoin/bitcoin#21800: mempool/validation: mempool ancestor/descendant limits for packages
accf3d5868460b4b14ab607fd66ac985b086fbb3 [test] mempool package ancestor/descendant limits (glozow)
2b6b26e57c24d2f0abd442c1c33098e3121572ce [test] parameterizable fee for make_chain and create_child_with_parents (glozow)
313c09f7b7beddfdb74c284720d209c81dfdb94f [test] helper function to increase transaction weight (glozow)
f8253d69d6f02850995a11eeb71fedc22e6f6575 extract/rename helper functions from rpc_packages.py (glozow)
3cd663a5d33aa7ef87994e452bced7f192d021a0 [policy] ancestor/descendant limits for packages (glozow)
c6e016aa139c8363e9b38bbc1ba0dca55700b8a7 [mempool] check ancestor/descendant limits for packages (glozow)
f551841d3ec080a2d7a7988c7b35088dff6c5830 [refactor] pass size/count instead of entry to CalculateAncestorsAndCheckLimits (glozow)
97dd1c729d2bbedf9527b914c0cc8267b8a7c21b MOVEONLY: add helper function for calculating ancestors and checking limits (glozow)
f95bbf58aaf72aab8a9c5827b1f162f3b8ac38f4 misc package validation doc improvements (glozow)
Pull request description:
This PR implements a function to calculate mempool ancestors for a package and enforces ancestor/descendant limits on them as a whole. It reuses a portion of `CalculateMemPoolAncestors()`; there's also a small refactor to move the reused code into a generic helper function. Instead of calculating ancestors and descendants on every single transaction in the package and their ancestors, we use a "worst case" heuristic, treating every transaction in the package as each other's ancestor and descendant. This may overestimate everyone's counts, but is still pretty accurate in the our main package use cases, in which at least one of the transactions in the package is directly related to all the others (e.g. 1 parent + 1 child, multiple parents with 1 child, or chains).
Note on Terminology: While "package" is often used to describe groups of related transactions _within_ the mempool, here, I only use package to mean the group of not-in-mempool transactions we are currently validating.
#### Motivation
It would be a potential DoS vector to allow submission of packages to mempool without a proper guard for mempool ancestors/descendants. In general, the purpose of mempool ancestor/descendant limits is to limit the computational complexity of dealing with families during removals and additions. We want to be able to validate multiple transactions on top of the mempool, but also avoid these scenarios:
- We underestimate the ancestors/descendants during package validation and end up with extremely complex families in our mempool (potentially a DoS vector).
- We expend an unreasonable amount of resources calculating everyone's ancestors and descendants during package validation.
ACKs for top commit:
JeremyRubin:
utACK accf3d5
ariard:
ACK accf3d5.
Tree-SHA512: 0d18ce4b77398fe872e0b7c2cc66d3aac2135e561b64029584339e1f4de2a6a16ebab3dd5784f376e119cbafc4d50168b28d3bd95d0b3d01158714ade2e3624d
Signed-off-by: Vijay <vijaydas.mp@gmail.com>
2021-08-09 05:53:10 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor
|
|
|
|
* and descendant limits (including staged_ancestors thsemselves, entry_size and entry_count).
|
|
|
|
* param@[in] entry_size Virtual size to include in the limits.
|
|
|
|
* param@[in] entry_count How many entries to include in the limits.
|
|
|
|
* param@[in] staged_ancestors Should contain entries in the mempool.
|
|
|
|
* param@[out] setAncestors Will be populated with all mempool ancestors.
|
|
|
|
*/
|
|
|
|
bool CalculateAncestorsAndCheckLimits(size_t entry_size,
|
|
|
|
size_t entry_count,
|
|
|
|
setEntries& setAncestors,
|
|
|
|
CTxMemPoolEntry::Parents &staged_ancestors,
|
|
|
|
uint64_t limitAncestorCount,
|
|
|
|
uint64_t limitAncestorSize,
|
|
|
|
uint64_t limitDescendantCount,
|
|
|
|
uint64_t limitDescendantSize,
|
|
|
|
std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
public:
|
2018-05-14 16:29:17 +02:00
|
|
|
indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
|
2021-05-21 08:27:52 +02:00
|
|
|
std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2015-10-13 09:57:41 +02:00
|
|
|
/** Create a new CTxMemPool.
|
2023-02-20 20:31:40 +01:00
|
|
|
* Sanity checks will be off by default for performance, because otherwise
|
|
|
|
* accepting transactions becomes O(N^2) where N is the number of transactions
|
|
|
|
* in the pool.
|
|
|
|
*
|
|
|
|
* @param[in] estimator is used to estimate appropriate transaction fees.
|
|
|
|
* @param[in] check_ratio is the ratio used to determine how often sanity checks will run.
|
2015-10-13 09:57:41 +02:00
|
|
|
*/
|
2023-02-20 20:31:40 +01:00
|
|
|
explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr, int check_ratio = 0);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2024-04-04 12:27:33 +02:00
|
|
|
/**
|
|
|
|
* Set CDeterministicMNManager pointer.
|
|
|
|
*
|
|
|
|
* Separated from constructor as it's initialized after CTxMemPool
|
|
|
|
* is created. Required for ProTx processing.
|
|
|
|
*/
|
2024-05-28 17:24:36 +02:00
|
|
|
void ConnectManagers(gsl::not_null<CDeterministicMNManager*> dmnman);
|
2024-04-04 12:27:33 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Reset CDeterministicMNManager pointer.
|
|
|
|
*
|
|
|
|
* @pre Must be called before CDeterministicMNManager is destroyed.
|
|
|
|
*/
|
|
|
|
void DisconnectManagers() { m_dmnman = nullptr; }
|
|
|
|
|
2014-11-17 03:29:09 +01:00
|
|
|
/**
|
2013-08-27 07:51:57 +02:00
|
|
|
* If sanity-checking is turned on, check makes sure the pool is
|
|
|
|
* consistent (does not contain two transactions that spend the same inputs,
|
|
|
|
* all inputs are in the mapNextTx array). If sanity-checking is turned off,
|
|
|
|
* check does nothing.
|
|
|
|
*/
|
2021-09-30 10:25:11 +02:00
|
|
|
void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
// addUnchecked must updated state for all ancestors of a given transaction,
|
|
|
|
// to track size/count of descendant transactions. First version of
|
|
|
|
// addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
|
|
|
|
// then invoke the second version.
|
2017-11-15 14:14:20 +01:00
|
|
|
// Note that addUnchecked is ONLY called from ATMP outside of tests
|
|
|
|
// and any other callers may break wallet's in-mempool tracking (due to
|
|
|
|
// lack of CValidationInterface::TransactionAddedToMempool callbacks).
|
2019-01-15 19:41:59 +01:00
|
|
|
void addUnchecked(const CTxMemPoolEntry& entry, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
|
|
|
|
void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2024-06-26 19:51:48 +02:00
|
|
|
void addAddressIndex(const CTxMemPoolEntry& entry, const CCoinsViewCache& view);
|
2024-06-26 21:24:21 +02:00
|
|
|
bool getAddressIndex(const std::vector<CMempoolAddressDeltaKey>& addresses,
|
2024-06-26 21:09:14 +02:00
|
|
|
std::vector<CMempoolAddressDeltaEntry>& results) const;
|
2016-04-04 22:37:43 +02:00
|
|
|
bool removeAddressIndex(const uint256 txhash);
|
|
|
|
|
2024-06-26 19:51:48 +02:00
|
|
|
void addSpentIndex(const CTxMemPoolEntry& entry, const CCoinsViewCache& view);
|
|
|
|
bool getSpentIndex(const CSpentIndexKey& key, CSpentIndexValue& value) const;
|
2016-05-16 20:23:01 +02:00
|
|
|
bool removeSpentIndex(const uint256 txhash);
|
|
|
|
|
2022-05-05 16:24:51 +02:00
|
|
|
void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2022-01-19 15:31:52 +01:00
|
|
|
/** After reorg, filter the entries that would no longer be valid in the next block, and update
|
|
|
|
* the entries' cached LockPoints if needed. The mempool does not have any knowledge of
|
|
|
|
* consensus rules. It just appplies the callable function and removes the ones for which it
|
|
|
|
* returns true.
|
|
|
|
* @param[in] filter_final_and_mature Predicate that checks the relevant validation rules
|
|
|
|
* and updates an entry's LockPoints.
|
|
|
|
* */
|
|
|
|
void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
|
2022-05-05 16:24:51 +02:00
|
|
|
void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2021-07-10 16:46:33 +02:00
|
|
|
void removeProTxPubKeyConflicts(const CTransaction &tx, const CKeyID &keyId) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2023-06-04 22:45:56 +02:00
|
|
|
void removeProTxPubKeyConflicts(const CTransaction &tx, const CBLSLazyPublicKey &pubKey) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2021-07-10 16:46:33 +02:00
|
|
|
void removeProTxCollateralConflicts(const CTransaction &tx, const COutPoint &collateralOutpoint) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
void removeProTxSpentCollateralConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
void removeProTxKeyChangedConflicts(const CTransaction &tx, const uint256& proTxHash, const uint256& newKeyHash) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
void removeProTxConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2022-05-05 16:24:51 +02:00
|
|
|
void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2020-05-11 05:33:42 +02:00
|
|
|
void removeExpiredAssetUnlock(int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2017-01-24 10:07:50 +01:00
|
|
|
|
2013-08-27 07:51:57 +02:00
|
|
|
void clear();
|
2018-05-14 16:29:17 +02:00
|
|
|
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs); //lock free
|
2016-05-05 13:14:29 +02:00
|
|
|
bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
|
2019-02-23 17:04:20 +01:00
|
|
|
void queryHashes(std::vector<uint256>& vtxid) const;
|
Merge #12717: [REST] Handle UTXO retrieval when ignoring the mempool
9cb9af8 [REST] Handle UTXO retrieval when ignoring the mempool (Roman Zeyde)
1fdc7c4 Make CTxMemPool::isSpent() const (Roman Zeyde)
Pull request description:
Current REST API always returns empty UTXO when invoked without `/checkmempool/` URL part.
After the fix:
```
$ curl -s http://localhost:8332/rest/getutxos/0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098-0.json | jq
{
"chainHeight": 514109,
"chaintipHash": "0000000000000000001fe76d1445e8a6432fd2de04261dc9c5915311dc7ad6de",
"bitmap": "1",
"utxos": [
{
"height": 1,
"value": 50,
"scriptPubKey": {
"asm": "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG",
"hex": "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac",
"reqSigs": 1,
"type": "pubkey",
"addresses": [
"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"
]
}
}
]
}
```
Before the fix:
```
$ curl -s http://localhost:8332/rest/getutxos/0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098-0.json | jq
{
"chainHeight": 514109,
"chaintipHash": "0000000000000000001fe76d1445e8a6432fd2de04261dc9c5915311dc7ad6de",
"bitmap": "0",
"utxos": []
}
```
Tree-SHA512: 994a350cb34a3c8f5a7afbc169c6b177c5be6cf223b2071c62d63644819d416d3e10d1c58b244d9d351bae7233d2974aa5e9ebadd1b5d6218f5245558675be0d
2018-03-27 21:31:27 +02:00
|
|
|
bool isSpent(const COutPoint& outpoint) const;
|
2013-08-27 07:51:57 +02:00
|
|
|
unsigned int GetTransactionsUpdated() const;
|
|
|
|
void AddTransactionsUpdated(unsigned int n);
|
2014-08-26 22:28:32 +02:00
|
|
|
/**
|
|
|
|
* Check that none of this transactions inputs are in the mempool, and thus
|
|
|
|
* the tx is not dependent on other mempool transactions to be included in a block.
|
|
|
|
*/
|
2022-05-05 16:24:51 +02:00
|
|
|
bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2012-07-11 20:52:41 +02:00
|
|
|
/** Affect CreateNewBlock prioritisation of transactions */
|
2019-03-14 15:44:42 +01:00
|
|
|
void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
|
2020-09-04 12:34:38 +02:00
|
|
|
void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2012-07-11 20:52:41 +02:00
|
|
|
|
2021-08-10 07:21:20 +02:00
|
|
|
/** Get the transaction in the pool that spends the same prevout */
|
|
|
|
const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
|
|
|
|
/** Returns an iterator to the given hash, if found */
|
2022-10-15 22:11:49 +02:00
|
|
|
std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2021-08-10 07:21:20 +02:00
|
|
|
|
|
|
|
/** Translate a set of hashes into a set of pool iterators to avoid repeated lookups */
|
|
|
|
setEntries GetIterSet(const std::set<uint256>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
/** Remove a set of transactions from the mempool.
|
|
|
|
* If a transaction is in this set, then all in-mempool descendants must
|
2016-03-17 13:33:31 +01:00
|
|
|
* also be in the set, unless this transaction is being removed for being
|
|
|
|
* in a block.
|
|
|
|
* Set updateDescendants to true when removing a tx that was in a block, so
|
|
|
|
* that any in-mempool descendants have their ancestor state updated.
|
|
|
|
*/
|
2019-07-30 22:01:06 +02:00
|
|
|
void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
|
|
|
/** When adding transactions from a disconnected block back to the mempool,
|
|
|
|
* new mempool entries may have children in the mempool (which is generally
|
|
|
|
* not the case when otherwise adding transactions).
|
|
|
|
* UpdateTransactionsFromBlock() will find child transactions and update the
|
2017-03-23 08:16:14 +01:00
|
|
|
* descendant state for each transaction in vHashesToUpdate (excluding any
|
|
|
|
* child transactions present in vHashesToUpdate, which are already accounted
|
|
|
|
* for). Note: vHashesToUpdate should be the set of transactions from the
|
2015-07-15 20:47:45 +02:00
|
|
|
* disconnected block that have been accepted back into the mempool.
|
|
|
|
*/
|
2021-02-24 09:07:10 +01:00
|
|
|
void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
|
|
|
/** Try to calculate all in-mempool ancestors of entry.
|
|
|
|
* (these are all calculated including the tx itself)
|
|
|
|
* limitAncestorCount = max number of ancestors
|
|
|
|
* limitAncestorSize = max size of ancestors
|
|
|
|
* limitDescendantCount = max number of descendants any ancestor can have
|
|
|
|
* limitDescendantSize = max size of descendants any ancestor can have
|
|
|
|
* errString = populated with error reason if any limits are hit
|
2015-09-23 19:37:32 +02:00
|
|
|
* fSearchForParents = whether to search a tx's vin for in-mempool parents, or
|
|
|
|
* look up parents from mapLinks. Must be true for entries not in the mempool
|
2015-07-15 20:47:45 +02:00
|
|
|
*/
|
2018-07-30 22:16:16 +02:00
|
|
|
bool CalculateMemPoolAncestors(const CTxMemPoolEntry& entry, setEntries& setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string& errString, bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
Merge bitcoin/bitcoin#21800: mempool/validation: mempool ancestor/descendant limits for packages
accf3d5868460b4b14ab607fd66ac985b086fbb3 [test] mempool package ancestor/descendant limits (glozow)
2b6b26e57c24d2f0abd442c1c33098e3121572ce [test] parameterizable fee for make_chain and create_child_with_parents (glozow)
313c09f7b7beddfdb74c284720d209c81dfdb94f [test] helper function to increase transaction weight (glozow)
f8253d69d6f02850995a11eeb71fedc22e6f6575 extract/rename helper functions from rpc_packages.py (glozow)
3cd663a5d33aa7ef87994e452bced7f192d021a0 [policy] ancestor/descendant limits for packages (glozow)
c6e016aa139c8363e9b38bbc1ba0dca55700b8a7 [mempool] check ancestor/descendant limits for packages (glozow)
f551841d3ec080a2d7a7988c7b35088dff6c5830 [refactor] pass size/count instead of entry to CalculateAncestorsAndCheckLimits (glozow)
97dd1c729d2bbedf9527b914c0cc8267b8a7c21b MOVEONLY: add helper function for calculating ancestors and checking limits (glozow)
f95bbf58aaf72aab8a9c5827b1f162f3b8ac38f4 misc package validation doc improvements (glozow)
Pull request description:
This PR implements a function to calculate mempool ancestors for a package and enforces ancestor/descendant limits on them as a whole. It reuses a portion of `CalculateMemPoolAncestors()`; there's also a small refactor to move the reused code into a generic helper function. Instead of calculating ancestors and descendants on every single transaction in the package and their ancestors, we use a "worst case" heuristic, treating every transaction in the package as each other's ancestor and descendant. This may overestimate everyone's counts, but is still pretty accurate in the our main package use cases, in which at least one of the transactions in the package is directly related to all the others (e.g. 1 parent + 1 child, multiple parents with 1 child, or chains).
Note on Terminology: While "package" is often used to describe groups of related transactions _within_ the mempool, here, I only use package to mean the group of not-in-mempool transactions we are currently validating.
#### Motivation
It would be a potential DoS vector to allow submission of packages to mempool without a proper guard for mempool ancestors/descendants. In general, the purpose of mempool ancestor/descendant limits is to limit the computational complexity of dealing with families during removals and additions. We want to be able to validate multiple transactions on top of the mempool, but also avoid these scenarios:
- We underestimate the ancestors/descendants during package validation and end up with extremely complex families in our mempool (potentially a DoS vector).
- We expend an unreasonable amount of resources calculating everyone's ancestors and descendants during package validation.
ACKs for top commit:
JeremyRubin:
utACK accf3d5
ariard:
ACK accf3d5.
Tree-SHA512: 0d18ce4b77398fe872e0b7c2cc66d3aac2135e561b64029584339e1f4de2a6a16ebab3dd5784f376e119cbafc4d50168b28d3bd95d0b3d01158714ade2e3624d
Signed-off-by: Vijay <vijaydas.mp@gmail.com>
2021-08-09 05:53:10 +02:00
|
|
|
/** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and
|
|
|
|
* check ancestor and descendant limits. Heuristics are used to estimate the ancestor and
|
|
|
|
* descendant count of all entries if the package were to be added to the mempool. The limits
|
|
|
|
* are applied to the union of all package transactions. For example, if the package has 3
|
|
|
|
* transactions and limitAncestorCount = 25, the union of all 3 sets of ancestors (including the
|
|
|
|
* transactions themselves) must be <= 22.
|
|
|
|
* @param[in] package Transaction package being evaluated for acceptance
|
|
|
|
* to mempool. The transactions need not be direct
|
|
|
|
* ancestors/descendants of each other.
|
|
|
|
* @param[in] limitAncestorCount Max number of txns including ancestors.
|
|
|
|
* @param[in] limitAncestorSize Max virtual size including ancestors.
|
|
|
|
* @param[in] limitDescendantCount Max number of txns including descendants.
|
|
|
|
* @param[in] limitDescendantSize Max virtual size including descendants.
|
|
|
|
* @param[out] errString Populated with error reason if a limit is hit.
|
|
|
|
*/
|
|
|
|
bool CheckPackageLimits(const Package& package,
|
|
|
|
uint64_t limitAncestorCount,
|
|
|
|
uint64_t limitAncestorSize,
|
|
|
|
uint64_t limitDescendantCount,
|
|
|
|
uint64_t limitDescendantSize,
|
|
|
|
std::string &errString) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
|
|
|
|
2015-10-30 03:49:00 +01:00
|
|
|
/** Populate setDescendants with all in-mempool descendants of hash.
|
|
|
|
* Assumes that setDescendants includes all in-mempool descendants of anything
|
|
|
|
* already in it. */
|
2021-04-08 21:35:16 +02:00
|
|
|
void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-10-30 03:49:00 +01:00
|
|
|
|
2015-10-02 23:19:55 +02:00
|
|
|
/** The minimum fee to get into the mempool, which may itself not be enough
|
2015-10-14 21:46:20 +02:00
|
|
|
* for larger-sized transactions.
|
2017-01-16 19:32:51 +01:00
|
|
|
* The incrementalRelayFee policy variable is used to bound the time it
|
2015-10-14 21:46:20 +02:00
|
|
|
* takes the fee rate to go back down all the way to 0. When the feerate
|
|
|
|
* would otherwise be half of this, it is set to 0 instead.
|
|
|
|
*/
|
2015-10-02 23:19:55 +02:00
|
|
|
CFeeRate GetMinFee(size_t sizelimit) const;
|
|
|
|
|
2015-10-22 02:44:00 +02:00
|
|
|
/** Remove transactions from the mempool until its dynamic size is <= sizelimit.
|
2017-06-02 00:47:58 +02:00
|
|
|
* pvNoSpendsRemaining, if set, will be populated with the list of outpoints
|
2015-10-22 02:44:00 +02:00
|
|
|
* which are not in mempool which no longer have any spends in this mempool.
|
|
|
|
*/
|
2022-05-05 16:24:51 +02:00
|
|
|
void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-10-02 23:19:55 +02:00
|
|
|
|
2015-10-02 23:43:30 +02:00
|
|
|
/** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
|
2019-10-02 16:55:03 +02:00
|
|
|
int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-10-02 23:43:30 +02:00
|
|
|
|
2018-06-11 15:35:42 +02:00
|
|
|
/**
|
|
|
|
* Calculate the ancestor and descendant count for the given transaction.
|
|
|
|
* The counts include the transaction itself.
|
|
|
|
*/
|
|
|
|
void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const;
|
2016-12-20 13:12:46 +01:00
|
|
|
|
2019-05-01 16:06:11 +02:00
|
|
|
/** @returns true if the mempool is fully loaded */
|
|
|
|
bool IsLoaded() const;
|
|
|
|
|
|
|
|
/** Sets the current loaded state */
|
|
|
|
void SetIsLoaded(bool loaded);
|
|
|
|
|
2019-01-15 19:41:59 +01:00
|
|
|
unsigned long size() const
|
2013-08-27 07:51:57 +02:00
|
|
|
{
|
|
|
|
LOCK(cs);
|
|
|
|
return mapTx.size();
|
|
|
|
}
|
2015-07-09 19:56:31 +02:00
|
|
|
|
2020-09-04 12:34:38 +02:00
|
|
|
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
|
2014-08-07 05:58:19 +02:00
|
|
|
{
|
2020-09-04 12:34:38 +02:00
|
|
|
AssertLockHeld(cs);
|
2014-08-07 05:58:19 +02:00
|
|
|
return totalTxSize;
|
|
|
|
}
|
2013-08-27 07:51:57 +02:00
|
|
|
|
2021-02-08 20:36:33 +01:00
|
|
|
CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
|
|
|
|
{
|
|
|
|
AssertLockHeld(cs);
|
|
|
|
return m_total_fee;
|
|
|
|
}
|
|
|
|
|
2021-08-10 07:21:20 +02:00
|
|
|
bool exists(const uint256& hash) const
|
2013-08-27 07:51:57 +02:00
|
|
|
{
|
|
|
|
LOCK(cs);
|
|
|
|
return (mapTx.count(hash) != 0);
|
|
|
|
}
|
|
|
|
|
2016-11-21 10:51:32 +01:00
|
|
|
CTransactionRef get(const uint256& hash) const;
|
2016-06-08 14:01:05 +02:00
|
|
|
TxMempoolInfo info(const uint256& hash) const;
|
|
|
|
std::vector<TxMempoolInfo> infoAll() const;
|
2014-03-17 13:19:54 +01:00
|
|
|
|
2024-04-04 12:27:33 +02:00
|
|
|
/**
|
|
|
|
* @pre Caller must ensure that CDeterministicMNManager exists and has been
|
|
|
|
* set using ConnectManagers() for the CTxMemPool instance.
|
|
|
|
*/
|
2018-02-14 14:42:06 +01:00
|
|
|
bool existsProviderTxConflict(const CTransaction &tx) const;
|
|
|
|
|
2015-07-09 19:56:31 +02:00
|
|
|
size_t DynamicMemoryUsage() const;
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2022-05-06 06:04:50 +02:00
|
|
|
/** Adds a transaction to the unbroadcast set */
|
2020-09-16 00:05:08 +02:00
|
|
|
void AddUnbroadcastTx(const uint256& txid)
|
|
|
|
{
|
2022-05-06 06:04:50 +02:00
|
|
|
LOCK(cs);
|
2020-09-16 00:05:08 +02:00
|
|
|
// Sanity check the transaction is in the mempool & insert into
|
|
|
|
// unbroadcast set.
|
|
|
|
if (exists(txid)) m_unbroadcast_txids.insert(txid);
|
2022-05-06 06:04:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Removes a transaction from the unbroadcast set */
|
|
|
|
void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false);
|
|
|
|
|
|
|
|
/** Returns transactions in unbroadcast set */
|
2020-09-16 00:05:08 +02:00
|
|
|
std::set<uint256> GetUnbroadcastTxs() const
|
|
|
|
{
|
2022-05-06 06:04:50 +02:00
|
|
|
LOCK(cs);
|
|
|
|
return m_unbroadcast_txids;
|
|
|
|
}
|
|
|
|
|
2020-05-30 18:22:03 +02:00
|
|
|
/** Returns whether a txid is in the unbroadcast set */
|
2020-05-22 01:27:28 +02:00
|
|
|
bool IsUnbroadcastTx(const uint256& txid) const {
|
|
|
|
LOCK(cs);
|
|
|
|
return (m_unbroadcast_txids.count(txid) != 0);
|
|
|
|
}
|
|
|
|
|
2024-08-26 17:35:12 +02:00
|
|
|
/** Guards this internal counter for external reporting */
|
|
|
|
uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
|
|
|
|
return m_sequence_number++;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
|
|
|
|
return m_sequence_number;
|
|
|
|
}
|
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
private:
|
|
|
|
/** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
|
|
|
|
* the descendants for a single transaction that has been added to the
|
|
|
|
* mempool but may have child transactions in the mempool, eg during a
|
|
|
|
* chain reorg. setExclude is the set of descendant transactions in the
|
|
|
|
* mempool that must not be accounted for (because any descendants in
|
|
|
|
* setExclude were added to the mempool after the transaction being
|
|
|
|
* updated and hence their state is already reflected in the parent
|
|
|
|
* state).
|
|
|
|
*
|
|
|
|
* cachedDescendants will be updated with the descendants of the transaction
|
|
|
|
* being updated, so that future invocations don't need to walk the
|
|
|
|
* same transaction again, if encountered in another transaction chain.
|
|
|
|
*/
|
2016-03-17 13:33:31 +01:00
|
|
|
void UpdateForDescendants(txiter updateIt,
|
2015-07-15 20:47:45 +02:00
|
|
|
cacheMap &cachedDescendants,
|
2018-05-14 16:29:17 +02:00
|
|
|
const std::set<uint256> &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
/** Update ancestors of hash to add/remove it as a descendant transaction. */
|
2018-05-14 16:29:17 +02:00
|
|
|
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2016-03-17 13:33:31 +01:00
|
|
|
/** Set ancestor state for an entry */
|
2018-05-14 16:29:17 +02:00
|
|
|
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2016-03-17 13:33:31 +01:00
|
|
|
/** For each transaction being removed, update ancestors and any direct children.
|
|
|
|
* If updateDescendants is true, then also update in-mempool descendants'
|
|
|
|
* ancestor state. */
|
2018-05-14 16:29:17 +02:00
|
|
|
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
/** Sever link between specified transaction and direct children. */
|
2018-05-14 16:29:17 +02:00
|
|
|
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2015-07-15 20:47:45 +02:00
|
|
|
|
2024-04-04 12:02:07 +02:00
|
|
|
/**
|
|
|
|
* addUnchecked extension for Dash-specific transactions (ProTx).
|
|
|
|
* Depends on CDeterministicMNManager.
|
|
|
|
*/
|
|
|
|
void addUncheckedProTx(indexed_transaction_set::iterator& newit, const CTransaction& tx);
|
|
|
|
|
2015-07-15 20:47:45 +02:00
|
|
|
/** Before calling removeUnchecked for a given transaction,
|
|
|
|
* UpdateForRemoveFromMempool must be called on the entire (dependent) set
|
|
|
|
* of transactions being removed at the same time. We use each
|
|
|
|
* CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
|
|
|
|
* given transaction that is removed, so we can't remove intermediate
|
|
|
|
* transactions in a chain before we've updated all the state for the
|
|
|
|
* removal.
|
|
|
|
*/
|
2019-07-30 22:01:06 +02:00
|
|
|
void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
|
2024-04-04 12:02:07 +02:00
|
|
|
void removeUncheckedProTx(const CTransaction& tx);
|
|
|
|
|
2020-01-14 20:31:36 +01:00
|
|
|
public:
|
|
|
|
/** visited marks a CTxMemPoolEntry as having been traversed
|
2021-02-24 09:07:10 +01:00
|
|
|
* during the lifetime of the most recently created Epoch::Guard
|
2020-01-14 20:31:36 +01:00
|
|
|
* and returns false if we are the first visitor, true otherwise.
|
|
|
|
*
|
2021-02-24 09:07:10 +01:00
|
|
|
* An Epoch::Guard must be held when visited is called or an assert will be
|
2020-01-14 20:31:36 +01:00
|
|
|
* triggered.
|
|
|
|
*
|
|
|
|
*/
|
2021-02-24 09:07:10 +01:00
|
|
|
bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
|
|
|
|
{
|
|
|
|
return m_epoch.visited(it->m_epoch_marker);
|
2020-01-14 20:31:36 +01:00
|
|
|
}
|
|
|
|
|
2024-03-19 10:43:27 +01:00
|
|
|
bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch) {
|
2021-02-24 09:07:10 +01:00
|
|
|
assert(m_epoch.guarded());
|
2020-01-14 20:31:36 +01:00
|
|
|
return !it || visited(*it);
|
|
|
|
}
|
2013-08-27 07:51:57 +02:00
|
|
|
};
|
|
|
|
|
2020-07-29 03:23:12 +02:00
|
|
|
/**
|
2018-03-21 16:16:28 +01:00
|
|
|
* CCoinsView that brings transactions from a mempool into view.
|
2014-11-17 03:29:09 +01:00
|
|
|
* It does not check for spendings by memory pool transactions.
|
2017-06-28 20:15:45 +02:00
|
|
|
* Instead, it provides access to all Coins which are either unspent in the
|
2024-01-29 16:01:14 +01:00
|
|
|
* base CCoinsView, are outputs from any mempool transaction, or are
|
|
|
|
* tracked temporarily to allow transaction dependencies in package validation.
|
2017-06-28 20:15:45 +02:00
|
|
|
* This allows transaction replacement to work as expected, as you want to
|
|
|
|
* have all inputs "available" to check signatures, and any cycles in the
|
|
|
|
* dependency graph are checked directly in AcceptToMemoryPool.
|
2019-02-05 16:47:50 +01:00
|
|
|
* It also allows you to sign a double-spend directly in
|
|
|
|
* signrawtransactionwithkey and signrawtransactionwithwallet,
|
2017-06-28 20:15:45 +02:00
|
|
|
* as long as the conflicting transaction is not yet confirmed.
|
2014-11-17 03:29:09 +01:00
|
|
|
*/
|
2013-11-05 02:47:07 +01:00
|
|
|
class CCoinsViewMemPool : public CCoinsViewBacked
|
|
|
|
{
|
2024-01-29 16:01:14 +01:00
|
|
|
/**
|
|
|
|
* Coins made available by transactions being validated. Tracking these allows for package
|
|
|
|
* validation, since we can access transaction outputs without submitting them to mempool.
|
|
|
|
*/
|
|
|
|
std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
|
2013-11-05 02:47:07 +01:00
|
|
|
protected:
|
2016-05-05 12:52:28 +02:00
|
|
|
const CTxMemPool& mempool;
|
2013-11-05 02:47:07 +01:00
|
|
|
|
|
|
|
public:
|
2016-05-05 12:52:28 +02:00
|
|
|
CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
|
2017-06-27 08:49:44 +02:00
|
|
|
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
|
2024-01-18 20:17:25 +01:00
|
|
|
/** Add the coins created by this transaction. These coins are only temporarily stored in
|
|
|
|
* m_temp_added and cannot be flushed to the back end. Only used for package validation. */
|
2024-01-29 16:01:14 +01:00
|
|
|
void PackageAddTransaction(const CTransactionRef& tx);
|
2013-11-05 02:47:07 +01:00
|
|
|
};
|
|
|
|
|
2017-05-30 18:42:22 +02:00
|
|
|
/**
|
|
|
|
* DisconnectedBlockTransactions
|
|
|
|
|
|
|
|
* During the reorg, it's desirable to re-add previously confirmed transactions
|
|
|
|
* to the mempool, so that anything not re-confirmed in the new chain is
|
|
|
|
* available to be mined. However, it's more efficient to wait until the reorg
|
|
|
|
* is complete and process all still-unconfirmed transactions at that time,
|
|
|
|
* since we expect most confirmed transactions to (typically) still be
|
|
|
|
* confirmed in the new chain, and re-accepting to the memory pool is expensive
|
|
|
|
* (and therefore better to not do in the middle of reorg-processing).
|
|
|
|
* Instead, store the disconnected transactions (in order!) as we go, remove any
|
|
|
|
* that are included in blocks in the new chain, and then process the remaining
|
|
|
|
* still-unconfirmed transactions at the end.
|
|
|
|
*/
|
|
|
|
|
|
|
|
// multi_index tag names
|
|
|
|
struct txid_index {};
|
|
|
|
struct insertion_order {};
|
|
|
|
|
|
|
|
struct DisconnectedBlockTransactions {
|
|
|
|
typedef boost::multi_index_container<
|
|
|
|
CTransactionRef,
|
|
|
|
boost::multi_index::indexed_by<
|
|
|
|
// sorted by txid
|
|
|
|
boost::multi_index::hashed_unique<
|
|
|
|
boost::multi_index::tag<txid_index>,
|
|
|
|
mempoolentry_txid,
|
|
|
|
SaltedTxidHasher
|
|
|
|
>,
|
|
|
|
// sorted by order in the blockchain
|
|
|
|
boost::multi_index::sequenced<
|
|
|
|
boost::multi_index::tag<insertion_order>
|
|
|
|
>
|
|
|
|
>
|
|
|
|
> indexed_disconnected_transactions;
|
|
|
|
|
|
|
|
// It's almost certainly a logic bug if we don't clear out queuedTx before
|
|
|
|
// destruction, as we add to it while disconnecting blocks, and then we
|
|
|
|
// need to re-process remaining transactions to ensure mempool consistency.
|
|
|
|
// For now, assert() that we've emptied out this object on destruction.
|
|
|
|
// This assert() can always be removed if the reorg-processing code were
|
|
|
|
// to be refactored such that this assumption is no longer true (for
|
|
|
|
// instance if there was some other way we cleaned up the mempool after a
|
|
|
|
// reorg, besides draining this object).
|
|
|
|
~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
|
|
|
|
|
|
|
|
indexed_disconnected_transactions queuedTx;
|
|
|
|
uint64_t cachedInnerUsage = 0;
|
|
|
|
|
|
|
|
// Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
|
|
|
|
// no exact formula for boost::multi_index_contained is implemented.
|
|
|
|
size_t DynamicMemoryUsage() const {
|
|
|
|
return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
|
|
|
|
}
|
|
|
|
|
|
|
|
void addTransaction(const CTransactionRef& tx)
|
|
|
|
{
|
|
|
|
queuedTx.insert(tx);
|
|
|
|
cachedInnerUsage += RecursiveDynamicUsage(tx);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove entries based on txid_index, and update memory usage.
|
|
|
|
void removeForBlock(const std::vector<CTransactionRef>& vtx)
|
|
|
|
{
|
|
|
|
// Short-circuit in the common case of a block being added to the tip
|
|
|
|
if (queuedTx.empty()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
for (auto const &tx : vtx) {
|
|
|
|
auto it = queuedTx.find(tx->GetHash());
|
|
|
|
if (it != queuedTx.end()) {
|
|
|
|
cachedInnerUsage -= RecursiveDynamicUsage(*it);
|
|
|
|
queuedTx.erase(it);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove an entry by insertion_order index, and update memory usage.
|
|
|
|
void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
|
|
|
|
{
|
|
|
|
cachedInnerUsage -= RecursiveDynamicUsage(*entry);
|
|
|
|
queuedTx.get<insertion_order>().erase(entry);
|
|
|
|
}
|
|
|
|
|
|
|
|
void clear()
|
|
|
|
{
|
|
|
|
cachedInnerUsage = 0;
|
|
|
|
queuedTx.clear();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-08-28 22:21:03 +02:00
|
|
|
#endif // BITCOIN_TXMEMPOOL_H
|