30std::vector<COutPoint> g_outpoints_coinbase_init_mature;
36 lastRollingFeeUpdate =
GetTime();
37 blockSinceLastRollingFeeBump =
true;
41void initialize_tx_pool()
43 static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
44 g_setup = testing_setup.get();
46 BlockAssembler::Options options;
53 g_outpoints_coinbase_init_mature.push_back(prevout);
60 std::set<COutPoint>& m_mempool_outpoints;
62 explicit OutpointsUpdater(std::set<COutPoint>& r)
63 : m_mempool_outpoints{r} {}
70 for (uint32_t index{0}; index < tx.
info.
m_tx->vout.size(); ++index) {
78 for (
const auto& input : tx->vin) {
80 m_mempool_outpoints.insert(input.prevout);
83 for (uint32_t index{0}; index < tx->vout.size(); ++index) {
84 m_mempool_outpoints.erase(
COutPoint{tx->GetHash(), index});
90 std::set<CTransactionRef>& m_added;
92 explicit TransactionsDelta(std::set<CTransactionRef>& a)
110 const auto time =
ConsumeTime(fuzzed_data_provider,
112 std::numeric_limits<
decltype(chainstate.
m_chain.
Tip()->
nTime)>::max());
124 mempool_opts.limits.ancestor_size_vbytes = fuzzed_data_provider.
ConsumeIntegralInRange<
unsigned>(0, 202) * 1'000;
126 mempool_opts.limits.descendant_size_vbytes = fuzzed_data_provider.
ConsumeIntegralInRange<
unsigned>(0, 202) * 1'000;
132 mempool_opts.check_ratio = 1;
133 mempool_opts.require_standard = fuzzed_data_provider.
ConsumeBool();
137 auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
144std::unique_ptr<CTxMemPool> MakeEphemeralMempool(
const NodeContext&
node)
152 mempool_opts.require_standard =
true;
155 mempool_opts.min_relay_feerate =
CFeeRate(0);
159 auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
169std::optional<COutPoint> GetChildEvictingPrevout(
const CTxMemPool& tx_pool)
172 for (
const auto& tx_info : tx_pool.
infoAll()) {
173 const auto& entry = *
Assert(tx_pool.
GetEntry(tx_info.tx->GetHash()));
175 if (!dust_indexes.empty()) {
176 const auto& children = entry.GetMemPoolChildrenConst();
177 if (!children.empty()) {
178 Assert(children.size() == 1);
180 const auto& only_child = children.begin()->get().GetTx();
181 for (
const auto& tx_input : only_child.vin) {
182 if (tx_input.prevout.hash != tx_info.tx->GetHash()) {
183 return tx_input.prevout;
200 MockTime(fuzzed_data_provider, chainstate);
203 std::set<COutPoint> mempool_outpoints;
204 std::map<COutPoint, CAmount> outpoints_value;
205 for (
const auto& outpoint : g_outpoints_coinbase_init_mature) {
206 Assert(mempool_outpoints.insert(outpoint).second);
207 outpoints_value[outpoint] = 50 *
COIN;
210 auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
211 node.validation_signals->RegisterSharedValidationInterface(outpoints_updater);
213 auto tx_pool_{MakeEphemeralMempool(
node)};
214 MockedTxPool& tx_pool = *
static_cast<MockedTxPool*
>(tx_pool_.get());
216 chainstate.SetMempool(&tx_pool);
220 Assert(!mempool_outpoints.empty());
222 std::vector<CTransactionRef> txs;
225 std::optional<COutPoint> outpoint_to_rbf{fuzzed_data_provider.
ConsumeBool() ? GetChildEvictingPrevout(tx_pool) :
std::nullopt};
228 const auto num_txs = outpoint_to_rbf ? 1 : (size_t) fuzzed_data_provider.
ConsumeIntegralInRange<
int>(1, 4);
230 std::set<COutPoint> package_outpoints;
231 while (txs.size() < num_txs) {
233 txs.emplace_back([&] {
240 bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
241 const auto num_in = outpoint_to_rbf ? 2 :
242 last_tx ? fuzzed_data_provider.
ConsumeIntegralInRange<
int>(package_outpoints.size()/2 + 1, package_outpoints.size()) :
246 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
248 Assert((
int)outpoints.size() >= num_in && num_in > 0);
251 for (
int i = 0; i < num_in; ++i) {
254 auto pop = outpoints.begin();
256 auto outpoint = *pop;
258 if (i == 0 && outpoint_to_rbf) {
259 outpoint = *outpoint_to_rbf;
260 outpoints.erase(outpoint);
262 outpoints.erase(pop);
265 amount_in += outpoints_value.at(outpoint);
272 tx_mut.
vin.push_back(in);
276 const auto amount_out = (amount_in - amount_fee) / num_out;
277 for (
int i = 0; i < num_out; ++i) {
282 if (!outpoint_to_rbf && fuzzed_data_provider.
ConsumeBool()) {
290 for (
const auto& in : tx->vin) {
294 for (
size_t i = 0; i < tx->vout.size(); ++i) {
295 package_outpoints.emplace(tx->GetHash(), i);
299 for (
size_t i = 0; i < tx->vout.size(); ++i) {
300 outpoints_value[
COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
307 const auto& txid = fuzzed_data_provider.
ConsumeBool() ?
308 txs.back()->GetHash() :
309 PickValue(fuzzed_data_provider, mempool_outpoints).hash;
315 if (
GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate).empty()) {
316 tx_pool.PrioritiseTransaction(txid.ToUint256(), delta);
321 auto single_submit = txs.size() == 1;
327 fuzzed_data_provider.
ConsumeBool(), !single_submit));
333 const bool expect_valid{result_package.m_state.IsValid()};
337 node.validation_signals->SyncWithValidationInterfaceQueue();
342 node.validation_signals->UnregisterSharedValidationInterface(outpoints_updater);
344 WITH_LOCK(
::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
355 MockTime(fuzzed_data_provider, chainstate);
358 std::set<COutPoint> mempool_outpoints;
359 std::map<COutPoint, CAmount> outpoints_value;
360 for (
const auto& outpoint : g_outpoints_coinbase_init_mature) {
361 Assert(mempool_outpoints.insert(outpoint).second);
362 outpoints_value[outpoint] = 50 *
COIN;
365 auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
366 node.validation_signals->RegisterSharedValidationInterface(outpoints_updater);
368 auto tx_pool_{MakeMempool(fuzzed_data_provider,
node)};
369 MockedTxPool& tx_pool = *
static_cast<MockedTxPool*
>(tx_pool_.get());
371 chainstate.SetMempool(&tx_pool);
375 Assert(!mempool_outpoints.empty());
377 std::vector<CTransactionRef> txs;
381 std::set<COutPoint> package_outpoints;
382 while (txs.size() < num_txs) {
384 txs.emplace_back([&] {
391 bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
392 const auto num_in = last_tx ? package_outpoints.size() : fuzzed_data_provider.
ConsumeIntegralInRange<
int>(1, mempool_outpoints.size());
395 auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
397 Assert(!outpoints.empty());
400 for (
size_t i = 0; i < num_in; ++i) {
403 auto pop = outpoints.begin();
405 const auto outpoint = *pop;
406 outpoints.erase(pop);
408 amount_in += outpoints_value.at(outpoint);
412 const auto script_sig =
CScript{};
421 tx_mut.
vin.push_back(in);
425 bool dup_input = fuzzed_data_provider.
ConsumeBool();
427 tx_mut.
vin.push_back(tx_mut.
vin.back());
432 tx_mut.
vin.emplace_back();
436 if (last_tx && amount_in > 1000 && fuzzed_data_provider.
ConsumeBool()) {
444 const auto amount_out = (amount_in - amount_fee) / num_out;
445 for (
int i = 0; i < num_out; ++i) {
451 for (
const auto& in : tx->vin) {
456 for (
size_t i = 0; i < tx->vout.size(); ++i) {
457 package_outpoints.emplace(tx->GetHash(), i);
461 for (
size_t i = 0; i < tx->vout.size(); ++i) {
462 outpoints_value[
COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
469 MockTime(fuzzed_data_provider, chainstate);
472 tx_pool.RollingFeeUpdate();
475 const auto& txid = fuzzed_data_provider.
ConsumeBool() ?
476 txs.back()->GetHash() :
477 PickValue(fuzzed_data_provider, mempool_outpoints).hash;
479 tx_pool.PrioritiseTransaction(txid.ToUint256(), delta);
483 std::set<CTransactionRef> added;
484 auto txr = std::make_shared<TransactionsDelta>(added);
485 node.validation_signals->RegisterSharedValidationInterface(txr);
490 auto single_submit = txs.size() == 1 && fuzzed_data_provider.
ConsumeBool();
493 std::optional<CFeeRate> client_maxfeerate{};
499 return ProcessNewPackage(chainstate, tx_pool, txs, single_submit, client_maxfeerate));
504 false, !single_submit));
507 node.validation_signals->SyncWithValidationInterfaceQueue();
508 node.validation_signals->UnregisterSharedValidationInterface(txr);
512 Assert(passed != added.empty());
513 Assert(passed == res.m_state.IsValid());
515 Assert(added.size() == 1);
516 Assert(txs.back() == *added.begin());
522 const bool expect_valid{result_package.m_state.IsValid()};
526 Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
532 if (tx_pool.m_opts.require_standard) {
537 node.validation_signals->UnregisterSharedValidationInterface(outpoints_updater);
539 WITH_LOCK(
::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr CAmount COIN
The amount of satoshis in one BTC.
#define Assert(val)
Identity function.
int64_t GetMedianTimePast() const
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
static const uint32_t CURRENT_VERSION
An input of a transaction.
CScriptWitness scriptWitness
Only serialized through CTransaction.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
std::vector< TxMempoolInfo > infoAll() const
const CTxMemPoolEntry * GetEntry(const Txid &txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs)
An output of a transaction.
Implement this to subscribe to events generated in validation and mempool.
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
T ConsumeIntegralInRange(T min, T max)
static GenTxid Txid(const uint256 &hash)
Generate a new block, without valid proof-of-work.
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
unsigned int nBytesPerSigOp
std::vector< uint32_t > GetDust(const CTransaction &tx, CFeeRate dust_relay_rate)
Get the vout index numbers of all dust outputs.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::vector< std::vector< unsigned char > > stack
Testing setup that configures a complete environment.
const CTransactionRef m_tx
int64_t ancestor_count
The maximum allowed number of transactions in a package including the entry and its ancestors.
Options struct containing options for constructing a CTxMemPool.
CFeeRate dust_relay_feerate
NodeContext struct containing references to chain state and connection state.
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
COutPoint MineBlock(const NodeContext &node, const node::BlockAssembler::Options &assembler_options)
Returns the generated coin.
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
@ ZEROS
Seed with a compile time constant of zeros.
static const std::vector< std::vector< uint8_t > > P2WSH_EMPTY_TRUE_STACK
static const std::vector< std::vector< uint8_t > > P2WSH_EMPTY_TWO_STACK
static const CScript P2WSH_EMPTY
void CheckMempoolTRUCInvariants(const CTxMemPool &tx_pool)
For every transaction in tx_pool, check TRUC invariants:
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
std::optional< std::string > CheckPackageMempoolAcceptResult(const Package &txns, const PackageMempoolAcceptResult &result, bool expect_valid, const CTxMemPool *mempool)
Check expected properties for every PackageMempoolAcceptResult, regardless of value.
void CheckMempoolEphemeralInvariants(const CTxMemPool &tx_pool)
Check that we never get into a state where an ephemeral dust transaction would be mined without the s...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
static constexpr decltype(CTransaction::version) TRUC_VERSION
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate)
Validate (and maybe submit) a package to the mempool.
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept)
Try to add a transaction to the mempool.