Bitcoin Core 31.99.0
P2P Digital Currency
tx_pool.cpp
Go to the documentation of this file.
1// Copyright (c) 2021-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <chain.h>
6#include <coins.h>
7#include <consensus/amount.h>
10#include <node/miner.h>
11#include <node/mining_types.h>
12#include <policy/feerate.h>
13#include <policy/packages.h>
14#include <policy/policy.h>
15#include <policy/truc_policy.h>
16#include <primitives/block.h>
18#include <script/script.h>
19#include <sync.h>
21#include <test/fuzz/fuzz.h>
22#include <test/fuzz/util.h>
24#include <test/util/mining.h>
25#include <test/util/random.h>
26#include <test/util/script.h>
28#include <test/util/txmempool.h>
29#include <txmempool.h>
30#include <util/check.h>
31#include <util/string.h>
32#include <util/time.h>
33#include <util/translation.h>
34#include <validation.h>
35#include <validationinterface.h>
36
37#include <cstddef>
38#include <cstdint>
39#include <functional>
40#include <iterator>
41#include <limits>
42#include <map>
43#include <memory>
44#include <optional>
45#include <set>
46#include <span>
47#include <string>
48#include <utility>
49#include <vector>
53using util::ToString;
54
55namespace {
56
58std::vector<COutPoint> g_outpoints_coinbase_init_mature;
59std::vector<COutPoint> g_outpoints_coinbase_init_immature;
60
61struct MockedTxPool : public CTxMemPool {
62 void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
63 {
64 LOCK(cs);
65 lastRollingFeeUpdate = GetTime();
66 blockSinceLastRollingFeeBump = true;
67 }
68};
69
70void initialize_tx_pool()
71{
72 static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
73 g_setup = testing_setup.get();
74 SetMockTime(WITH_LOCK(g_setup->m_node.chainman->GetMutex(), return g_setup->m_node.chainman->ActiveTip()->Time()));
75
76 for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
78 .coinbase_output_script = P2WSH_OP_TRUE,
79 })};
80 // Remember the txids to avoid expensive disk access later on
81 auto& outpoints = i < COINBASE_MATURITY ?
82 g_outpoints_coinbase_init_mature :
83 g_outpoints_coinbase_init_immature;
84 outpoints.push_back(prevout);
85 }
86 g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
87}
88
89struct TransactionsDelta final : public CValidationInterface {
90 std::set<CTransactionRef>& m_removed;
91 std::set<CTransactionRef>& m_added;
92
93 explicit TransactionsDelta(std::set<CTransactionRef>& r, std::set<CTransactionRef>& a)
94 : m_removed{r}, m_added{a} {}
95
96 void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
97 {
98 Assert(m_added.insert(tx.info.m_tx).second);
99 }
100
101 void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
102 {
103 Assert(m_removed.insert(tx).second);
104 }
105};
106
107void SetMempoolConstraints(ArgsManager& args, FuzzedDataProvider& fuzzed_data_provider)
108{
109 args.ForceSetArg("-limitclustercount",
111 args.ForceSetArg("-limitclustersize",
113 args.ForceSetArg("-maxmempool",
115 args.ForceSetArg("-mempoolexpiry",
117}
118
121std::vector<Wtxid> WtxidsToRelay(FuzzedDataProvider& fuzzed_data_provider, const MockedTxPool& tx_pool)
122{
123 LOCK(tx_pool.cs);
124 std::vector<Wtxid> res;
125
126 uint8_t dummy{0};
127 const auto mempool_entries{tx_pool.entryAll()};
129 if (!mempool_entries.empty() && fuzzed_data_provider.ConsumeBool()) {
130 // Wtxid of an in-mempool transaction
131 const auto& entry_ref{PickValue(fuzzed_data_provider, mempool_entries).get()};
132 res.push_back(entry_ref.GetTx().GetWitnessHash());
133 // Don't remove it from the mempool, so the next pick is possibly a duplicate
134 } else {
135 // Wtxid of a not-in-mempool transaction
136 res.push_back(Wtxid::FromUint256(uint256{dummy}));
137 // Possibly make the next wtxid of a not-in-mempool transaction, a duplicate
138 if (fuzzed_data_provider.ConsumeBool()) dummy++;
139 }
140 }
141
142 return res;
143}
144
145void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, Chainstate& chainstate)
146{
147 WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
148 {
149 BlockCreateOptions options{
152 };
153 auto assembler = BlockAssembler{chainstate, &tx_pool, options};
154 auto block_template = assembler.CreateNewBlock();
155 Assert(block_template->block.vtx.size() >= 1);
156
157 // Try updating the mempool for this block, as though it were mined.
158 LOCK2(::cs_main, tx_pool.cs);
159 tx_pool.removeForBlock(block_template->block.vtx, chainstate.m_chain.Height() + 1);
160
161 // Now try to add those transactions back, as though a reorg happened.
162 std::vector<Txid> hashes_to_update;
163 for (const auto& tx : block_template->block.vtx) {
164 const auto res = AcceptToMemoryPool(chainstate, tx, GetTime(), true, /*test_accept=*/false);
165 if (res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
166 hashes_to_update.push_back(tx->GetHash());
167 } else {
168 tx_pool.removeRecursive(*tx, MemPoolRemovalReason::REORG);
169 }
170 }
171 tx_pool.UpdateTransactionsFromBlock(hashes_to_update);
172 }
173 const auto info_all = tx_pool.infoAll();
174 if (!info_all.empty()) {
175 const auto& tx_to_remove = *PickValue(fuzzed_data_provider, info_all).tx;
176 WITH_LOCK(tx_pool.cs, tx_pool.removeRecursive(tx_to_remove, MemPoolRemovalReason::BLOCK /* dummy */));
177 assert(tx_pool.size() < info_all.size());
178 }
179
180 // Query a number of mempool entries as if to relay them, and assert some invariants on the result.
181 auto wtxids_to_relay{WtxidsToRelay(fuzzed_data_provider, tx_pool)};
182 const auto wtxids_count_before{wtxids_to_relay.size()};
183 const auto n_to_sort{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 100)};
184 const auto sorted_iter{WITH_LOCK(tx_pool.cs, return tx_pool.ExtractBestByMiningScoreWithTopology(wtxids_to_relay, n_to_sort))};
185 const auto expected_count{std::min(n_to_sort, wtxids_count_before)};
186 // We removed at least as many transactions from the list as we expected sorted entries.
187 Assert(wtxids_to_relay.size() <= wtxids_count_before - expected_count);
188 // When there is enough non-duplicate in-mempool transactions (list of remaining wtxids is
189 // non-empty), we must have received the expected number of entries.
190 Assert(sorted_iter.size() == expected_count || wtxids_to_relay.empty());
191 if (n_to_sort > 0) {
192 // If we asked for a positive number of entries, we must have removed all wtxids that do
193 // not correspond to a mempool entry..
194 const auto is_in_mempool = [&](const auto& wtxid) EXCLUSIVE_LOCKS_REQUIRED(tx_pool.cs) { return tx_pool.GetIter(wtxid).has_value(); };
195 Assert(WITH_LOCK(tx_pool.cs, return std::ranges::all_of(wtxids_to_relay, is_in_mempool)));
196 // ..As well as all duplicates.
197 const auto wtxids_count{wtxids_to_relay.size()};
198 const std::set<Wtxid> unique_wtxids{std::make_move_iterator(wtxids_to_relay.begin()), std::make_move_iterator(wtxids_to_relay.end())};
199 Assert(unique_wtxids.size() == wtxids_count);
200 }
201
203 // Try eviction
204 LOCK2(::cs_main, tx_pool.cs);
205 tx_pool.TrimToSize(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0U, tx_pool.DynamicMemoryUsage() * 2));
206 }
208 // Try expiry
209 LOCK2(::cs_main, tx_pool.cs);
210 tx_pool.Expire(GetMockTime() - std::chrono::seconds(fuzzed_data_provider.ConsumeIntegral<uint32_t>()));
211 }
212 WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
213 g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
214}
215
216void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
217{
218 const auto time = ConsumeTime(fuzzed_data_provider,
219 chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
220 std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
221 SetMockTime(time);
222}
223
224std::unique_ptr<CTxMemPool> MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
225{
226 // Take the default options for tests...
228
229 // ...override specific options for this specific fuzz suite
230 mempool_opts.check_ratio = 1;
231 mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
232
233 // ...and construct a CTxMemPool from it
234 bilingual_str error;
235 auto mempool{std::make_unique<CTxMemPool>(std::move(mempool_opts), error)};
236 // ... ignore the error since it might be beneficial to fuzz even when the
237 // mempool size is unreasonably small
238 Assert(error.empty() || error.original.starts_with("-maxmempool must be at least "));
239 return mempool;
240}
241
242void CheckATMPInvariants(const MempoolAcceptResult& res, bool txid_in_mempool, bool wtxid_in_mempool)
243{
244
245 switch (res.m_result_type) {
247 {
248 Assert(txid_in_mempool);
249 Assert(wtxid_in_mempool);
250 Assert(res.m_state.IsValid());
251 Assert(!res.m_state.IsInvalid());
252 Assert(res.m_vsize);
253 Assert(res.m_base_fees);
256 Assert(!res.m_other_wtxid);
257 break;
258 }
260 {
261 // It may be already in the mempool since in ATMP cases we don't set MEMPOOL_ENTRY or DIFFERENT_WITNESS
262 Assert(!res.m_state.IsValid());
263 Assert(res.m_state.IsInvalid());
264
265 const bool is_reconsiderable{res.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE};
266 Assert(!res.m_vsize);
267 Assert(!res.m_base_fees);
268 // Fee information is provided if the failure is TX_RECONSIDERABLE.
269 // In other cases, validation may be unable or unwilling to calculate the fees.
270 Assert(res.m_effective_feerate.has_value() == is_reconsiderable);
271 Assert(res.m_wtxids_fee_calculations.has_value() == is_reconsiderable);
272 Assert(!res.m_other_wtxid);
273 break;
274 }
276 {
277 // ATMP never sets this; only set in package settings
278 Assert(false);
279 break;
280 }
282 {
283 // ATMP never sets this; only set in package settings
284 Assert(false);
285 break;
286 }
287 }
288}
289
290FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
291{
293 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
294 const auto& node = g_setup->m_node;
295 auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
296
297 MockTime(fuzzed_data_provider, chainstate);
298
299 // All RBF-spendable outpoints
300 std::set<COutPoint> outpoints_rbf;
301 // All outpoints counting toward the total supply (subset of outpoints_rbf)
302 std::set<COutPoint> outpoints_supply;
303 for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
304 Assert(outpoints_supply.insert(outpoint).second);
305 }
306 outpoints_rbf = outpoints_supply;
307
308 // The sum of the values of all spendable outpoints
309 constexpr CAmount SUPPLY_TOTAL{COINBASE_MATURITY * 50 * COIN};
310
311 SetMempoolConstraints(*node.args, fuzzed_data_provider);
312 auto tx_pool_{MakeMempool(fuzzed_data_provider, node)};
313 MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
314
315 chainstate.SetMempool(&tx_pool);
316
317 // Helper to query an amount
318 const CCoinsViewMemPool amount_view{WITH_LOCK(::cs_main, return &chainstate.CoinsTip()), tx_pool};
319 const auto GetAmount = [&](const COutPoint& outpoint) {
320 auto coin{amount_view.GetCoin(outpoint).value()};
321 return coin.out.nValue;
322 };
323
325 {
326 // Total supply is the mempool fee + all outpoints
327 CAmount supply_now{WITH_LOCK(tx_pool.cs, return tx_pool.GetTotalFee())};
328 for (const auto& op : outpoints_supply) {
329 supply_now += GetAmount(op);
330 }
331 Assert(supply_now == SUPPLY_TOTAL);
332 }
333 Assert(!outpoints_supply.empty());
334
335 // Create transaction to add to the mempool
336 const CTransactionRef tx = [&] {
337 CMutableTransaction tx_mut;
340 const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size());
341 const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size() * 2);
342
343 CAmount amount_in{0};
344 for (int i = 0; i < num_in; ++i) {
345 // Pop random outpoint
346 auto pop = outpoints_rbf.begin();
347 std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints_rbf.size() - 1));
348 const auto outpoint = *pop;
349 outpoints_rbf.erase(pop);
350 amount_in += GetAmount(outpoint);
351
352 // Create input
354 const auto script_sig = CScript{};
355 const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
356 CTxIn in;
357 in.prevout = outpoint;
358 in.nSequence = sequence;
359 in.scriptSig = script_sig;
360 in.scriptWitness.stack = script_wit_stack;
361
362 tx_mut.vin.push_back(in);
363 }
364
365 // Check sigops in mempool + block template creation
366 bool add_sigops{fuzzed_data_provider.ConsumeBool()};
367
368 const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1000, amount_in);
369 const auto amount_out = (amount_in - amount_fee) / num_out;
370 for (int i = 0; i < num_out; ++i) {
371 if (i == 0 && add_sigops) {
372 tx_mut.vout.emplace_back(amount_out, CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG);
373 } else {
374 tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
375 }
376 }
377
378 auto tx = MakeTransactionRef(tx_mut);
379 // Restore previously removed outpoints
380 for (const auto& in : tx->vin) {
381 Assert(outpoints_rbf.insert(in.prevout).second);
382 }
383 return tx;
384 }();
385
387 MockTime(fuzzed_data_provider, chainstate);
388 }
390 tx_pool.RollingFeeUpdate();
391 }
393 const auto& txid = fuzzed_data_provider.ConsumeBool() ?
394 tx->GetHash() :
395 PickValue(fuzzed_data_provider, outpoints_rbf).hash;
396 const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
397 tx_pool.PrioritiseTransaction(txid, delta);
398 }
399
400 // Remember all removed and added transactions
401 std::set<CTransactionRef> removed;
402 std::set<CTransactionRef> added;
403 auto txr = std::make_shared<TransactionsDelta>(removed, added);
404 node.validation_signals->RegisterSharedValidationInterface(txr);
405
406 // Make sure ProcessNewPackage on one transaction works.
407 // The result is not guaranteed to be the same as what is returned by ATMP.
408 const auto result_package = WITH_LOCK(::cs_main,
409 return ProcessNewPackage(chainstate, tx_pool, {tx}, true, /*client_maxfeerate=*/{}));
410 // If something went wrong due to a package-specific policy, it might not return a
411 // validation result for the transaction.
412 if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
413 auto it = result_package.m_tx_results.find(tx->GetWitnessHash());
414 Assert(it != result_package.m_tx_results.end());
415 Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID ||
416 it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
417 }
418
419 const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), /*bypass_limits=*/false, /*test_accept=*/false));
420 const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
421 node.validation_signals->SyncWithValidationInterfaceQueue();
422 node.validation_signals->UnregisterSharedValidationInterface(txr);
423
424 bool txid_in_mempool = tx_pool.exists(tx->GetHash());
425 bool wtxid_in_mempool = tx_pool.exists(tx->GetWitnessHash());
426 CheckATMPInvariants(res, txid_in_mempool, wtxid_in_mempool);
427
428 Assert(accepted != added.empty());
429 if (accepted) {
430 Assert(added.size() == 1); // For now, no package acceptance
431 Assert(tx == *added.begin());
433 } else {
434 // Do not consider rejected transaction removed
435 removed.erase(tx);
436 }
437
438 // Helper to insert spent and created outpoints of a tx into collections
439 using Sets = std::vector<std::reference_wrapper<std::set<COutPoint>>>;
440 const auto insert_tx = [](Sets created_by_tx, Sets consumed_by_tx, const auto& tx) {
441 for (size_t i{0}; i < tx.vout.size(); ++i) {
442 for (auto& set : created_by_tx) {
443 Assert(set.get().emplace(tx.GetHash(), i).second);
444 }
445 }
446 for (const auto& in : tx.vin) {
447 for (auto& set : consumed_by_tx) {
448 Assert(set.get().insert(in.prevout).second);
449 }
450 }
451 };
452 // Add created outpoints, remove spent outpoints
453 {
454 // Outpoints that no longer exist at all
455 std::set<COutPoint> consumed_erased;
456 // Outpoints that no longer count toward the total supply
457 std::set<COutPoint> consumed_supply;
458 for (const auto& removed_tx : removed) {
459 insert_tx(/*created_by_tx=*/{consumed_erased}, /*consumed_by_tx=*/{outpoints_supply}, /*tx=*/*removed_tx);
460 }
461 for (const auto& added_tx : added) {
462 insert_tx(/*created_by_tx=*/{outpoints_supply, outpoints_rbf}, /*consumed_by_tx=*/{consumed_supply}, /*tx=*/*added_tx);
463 }
464 for (const auto& p : consumed_erased) {
465 Assert(outpoints_supply.erase(p) == 1);
466 Assert(outpoints_rbf.erase(p) == 1);
467 }
468 for (const auto& p : consumed_supply) {
469 Assert(outpoints_supply.erase(p) == 1);
470 }
471 }
472 }
473 Finish(fuzzed_data_provider, tx_pool, chainstate);
474}
475
476FUZZ_TARGET(tx_pool, .init = initialize_tx_pool)
477{
479 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
480 const auto& node = g_setup->m_node;
481 auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
482
483 MockTime(fuzzed_data_provider, chainstate);
484
485 std::vector<Txid> txids;
486 txids.reserve(g_outpoints_coinbase_init_mature.size());
487 for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
488 txids.push_back(outpoint.hash);
489 }
490 for (int i{0}; i <= 3; ++i) {
491 // Add some immature and non-existent outpoints
492 txids.push_back(g_outpoints_coinbase_init_immature.at(i).hash);
494 }
495
496 SetMempoolConstraints(*node.args, fuzzed_data_provider);
497 auto tx_pool_{MakeMempool(fuzzed_data_provider, node)};
498 MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(tx_pool_.get());
499
500 chainstate.SetMempool(&tx_pool);
501
502 // If we ever bypass limits, do not do TRUC invariants checks
503 bool ever_bypassed_limits{false};
504
506 const auto mut_tx = ConsumeTransaction(fuzzed_data_provider, txids);
507
509 MockTime(fuzzed_data_provider, chainstate);
510 }
512 tx_pool.RollingFeeUpdate();
513 }
515 const auto txid = fuzzed_data_provider.ConsumeBool() ?
516 mut_tx.GetHash() :
518 const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
519 tx_pool.PrioritiseTransaction(txid, delta);
520 }
521
522 const bool bypass_limits{fuzzed_data_provider.ConsumeBool()};
523 ever_bypassed_limits |= bypass_limits;
524
525 const auto tx = MakeTransactionRef(mut_tx);
526 const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), bypass_limits, /*test_accept=*/false));
527 const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
528 if (accepted) {
529 txids.push_back(tx->GetHash());
530 if (!ever_bypassed_limits) {
532 }
533 }
534 }
535 Finish(fuzzed_data_provider, tx_pool, chainstate);
536}
537} // namespace
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
static void pool cs
ArgsManager & args
Definition: bitcoind.cpp:280
const TestingSetup * g_setup
#define Assert(val)
Identity function.
Definition: check.h:116
void ForceSetArg(const std::string &strArg, const std::string &strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: args.cpp:627
uint32_t nTime
Definition: chain.h:142
int64_t GetMedianTimePast() const
Definition: chain.h:233
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:777
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
static constexpr uint32_t CURRENT_VERSION
Definition: transaction.h:284
An input of a transaction.
Definition: transaction.h:62
uint32_t nSequence
Definition: transaction.h:66
CScript scriptSig
Definition: transaction.h:65
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:67
COutPoint prevout
Definition: transaction.h:64
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:187
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.
Definition: validation.h:554
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:628
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:689
T ConsumeIntegralInRange(T min, T max)
bool IsValid() const
Definition: validation.h:113
Result GetResult() const
Definition: validation.h:116
bool IsInvalid() const
Definition: validation.h:114
Generate a new block, without valid proof-of-work.
Definition: miner.h:61
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:196
LIMITED_WHILE(provider.remaining_bytes(), 10000)
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define FUZZ_TARGET(...)
Definition: fuzz.h:35
uint64_t sequence
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ BLOCK
Removed for block.
@ REORG
Removed for reorganization.
is used externally by mining IPC clients, so it should only declare simple data definitions.
Definition: basic.cpp:8
Definition: messages.h:22
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:249
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
static constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
Definition: policy.h:27
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
@ OP_CHECKSIG
Definition: script.h:191
node::NodeContext m_node
Definition: setup_common.h:60
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
std::vector< std::vector< unsigned char > > stack
Definition: script.h:581
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:134
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition: validation.h:151
const ResultType m_result_type
Result type.
Definition: validation.h:143
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:153
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:146
@ DIFFERENT_WITNESS
‍Valid, transaction was already in the mempool.
@ INVALID
‍Fully validated, valid.
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:159
const std::optional< Wtxid > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness.
Definition: validation.h:168
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:165
Testing setup that configures a complete environment.
Definition: setup_common.h:115
const CTransactionRef m_tx
Bilingual messages:
Definition: translation.h:24
bool empty() const
Definition: translation.h:35
std::string original
Definition: translation.h:25
Options struct containing options for constructing a CTxMemPool.
Block template creation options.
Definition: mining_types.h:33
std::optional< CFeeRate > block_min_fee_rate
Minimum fee rate for transactions to be included.
Definition: mining_types.h:42
NodeContext struct containing references to chain state and connection state.
Definition: context.h:59
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:97
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:76
#define LOCK2(cs1, cs2)
Definition: sync.h:269
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
SeedRandomStateForTest(SeedRand::ZEROS)
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:155
CMutableTransaction ConsumeTransaction(FuzzedDataProvider &fuzzed_data_provider, const std::optional< std::vector< Txid > > &prevout_txids, const int max_num_in, const int max_num_out) noexcept
Definition: util.cpp:42
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:29
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:57
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:195
COutPoint MineBlock(const NodeContext &node, const node::BlockCreateOptions &assembler_options)
Returns the generated coin.
Definition: mining.cpp:78
@ ZEROS
Seed with a compile time constant of zeros.
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
Definition: script.h:12
static const CScript P2WSH_OP_TRUE
Definition: script.h:13
void CheckMempoolTRUCInvariants(const CTxMemPool &tx_pool)
For every transaction in tx_pool, check TRUC invariants:
Definition: txmempool.cpp:182
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:21
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static constexpr decltype(CTransaction::version) TRUC_VERSION
Definition: truc_policy.h:20
std::chrono::seconds GetMockTime()
For testing.
Definition: time.cpp:60
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:89
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:52
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.
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition: fees.cpp:39