47 std::vector<COutPoint> outpoints;
48 outpoints.reserve(200'000);
51 for (uint8_t i = 0; i < 4; i++) {
57 std::vector<CTransactionRef> tx_history;
68 tx_mut.
vin.reserve(num_in);
69 for (uint32_t i = 0; i < num_in; i++) {
75 tx_mut.
vout.reserve(num_out);
76 for (uint32_t i = 0; i < num_out; i++) {
81 for (uint32_t i = 0; i < num_out; i++) {
82 outpoints.emplace_back(new_tx->GetHash(), i);
87 tx_history.push_back(tx);
89 const auto wtxid{tx->GetWitnessHash()};
93 if (ptx_potential_parent) {
95 orphanage->AddChildrenToWorkSet(*ptx_potential_parent, orphanage_rng);
99 for (
const auto& child : orphanage->GetChildrenFromSamePeer(ptx_potential_parent, peer_id)) {
100 assert(std::any_of(child->vin.cbegin(), child->vin.cend(), [&](
const auto& input) {
101 return input.prevout.hash == ptx_potential_parent->GetHash();
110 const auto total_bytes_start{orphanage->TotalOrphanUsage()};
111 const auto total_peer_bytes_start{orphanage->UsageByPeer(peer_id)};
120 Assert(orphanage->HaveTx(ref->GetWitnessHash()));
125 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
126 bool have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
130 bool add_tx = orphanage->AddTx(tx, peer_id);
132 Assert(!have_tx || !add_tx);
134 Assert(!have_tx_and_peer || !add_tx);
141 if (orphanage->UsageByPeer(peer_id) > total_peer_bytes_start) {
142 Assert(orphanage->HaveTxFromPeer(wtxid, peer_id));
147 Assert(orphanage->TotalOrphanUsage() <= total_bytes_start);
156 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
157 bool have_tx_and_peer = orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id);
160 bool added_announcer = orphanage->AddAnnouncer(tx->GetWitnessHash(), peer_id);
162 Assert(have_tx || !added_announcer);
164 Assert(!have_tx_and_peer || !added_announcer);
168 Assert(orphanage->TotalOrphanUsage() <= total_bytes_start);
172 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
173 bool have_tx_and_peer{orphanage->HaveTxFromPeer(wtxid, peer_id)};
176 auto bytes_from_peer_before{orphanage->UsageByPeer(peer_id)};
177 Assert(have_tx == orphanage->EraseTx(tx->GetWitnessHash()));
180 if (!have_tx_and_peer) {
181 Assert(orphanage->UsageByPeer(peer_id) == bytes_from_peer_before);
185 have_tx = orphanage->HaveTx(tx->GetWitnessHash());
186 have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
189 Assert(!have_tx && !have_tx_and_peer && !orphanage->EraseTx(wtxid));
193 orphanage->EraseForPeer(peer_id);
194 Assert(!orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id));
195 Assert(orphanage->UsageByPeer(peer_id) == 0);
200 int64_t block_weight{0};
202 for (
int i{0}; i < num_txs; ++i) {
206 block_weight += tx_weight;
207 block.
vtx.push_back(tx_to_remove);
209 orphanage->EraseForBlock(block);
210 for (
const auto& tx_removed : block.
vtx) {
211 Assert(!orphanage->HaveTx(tx_removed->GetWitnessHash()));
212 Assert(!orphanage->HaveTxFromPeer(tx_removed->GetWitnessHash(), peer_id));
220 ptx_potential_parent = tx;
223 const bool have_tx{orphanage->HaveTx(tx->GetWitnessHash())};
224 const bool get_tx_nonnull{orphanage->GetTx(tx->GetWitnessHash()) !=
nullptr};
225 Assert(have_tx == get_tx_nonnull);
227 orphanage->SanityCheck();
239 const unsigned int MAX_PEERS = 125;
242 std::bitset<MAX_PEERS> protected_peers;
243 for (
unsigned int i = 0; i < num_peers; i++) {
255 const unsigned int honest_latency_limit = global_latency_score_limit / num_peers;
257 const int64_t honest_mem_limit = per_peer_weight_reservation;
259 std::vector<COutPoint> outpoints;
260 outpoints.reserve(400);
263 for (uint8_t i = 0; i < 4; i++) {
268 std::set<Wtxid> protected_wtxids;
279 tx_mut.
vin.reserve(num_in);
280 for (uint32_t i = 0; i < num_in; i++) {
286 tx_mut.
vout.reserve(num_out);
287 for (uint32_t i = 0; i < num_out; i++) {
290 tx_mut.
vout.emplace_back(0,
CScript() << OP_RETURN << std::vector<unsigned char>(payload_size));
297 for (uint32_t i = 0; i < num_out; i++) {
298 outpoints.emplace_back(new_tx->GetHash(), i);
303 const auto wtxid{tx->GetWitnessHash()};
313 const bool peer_is_protected{protected_peers[peer_id]};
318 bool have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
319 if (peer_is_protected && !have_tx_and_peer &&
320 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
321 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
324 orphanage->AddTx(tx, peer_id);
325 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
326 protected_wtxids.insert(wtxid);
331 bool have_tx_and_peer = orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id);
334 if (peer_is_protected && !have_tx_and_peer &&
335 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
336 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
339 orphanage->AddAnnouncer(tx->GetWitnessHash(), peer_id);
340 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
341 protected_wtxids.insert(wtxid);
347 if (protected_wtxids.contains(tx->GetWitnessHash())) {
348 protected_wtxids.erase(wtxid);
350 orphanage->EraseTx(wtxid);
351 Assert(!orphanage->HaveTx(wtxid));
354 if (!protected_peers[peer_id]) {
355 orphanage->EraseForPeer(peer_id);
356 Assert(orphanage->UsageByPeer(peer_id) == 0);
357 Assert(orphanage->LatencyScoreFromPeer(peer_id) == 0);
358 Assert(orphanage->AnnouncementsFromPeer(peer_id) == 0);
365 orphanage->SanityCheck();
367 for (
const auto& wtxid : protected_wtxids) {
368 Assert(orphanage->HaveTx(wtxid));
387 static constexpr unsigned NUM_TX = 16;
390 static constexpr unsigned NUM_PEERS = 16;
393 static constexpr unsigned MAX_ANN = 64;
405 std::vector<unsigned> txorder(NUM_TX);
406 std::iota(txorder.begin(), txorder.end(),
unsigned{0});
407 std::shuffle(txorder.begin(), txorder.end(), rng);
409 std::vector<std::pair<unsigned, unsigned>> deps;
410 deps.reserve((NUM_TX * (NUM_TX - 1)) / 2);
411 for (
unsigned p = 0; p < NUM_TX - 1; ++p) {
412 for (
unsigned c = p + 1; c < NUM_TX; ++c) {
413 deps.emplace_back(c, p);
416 std::shuffle(deps.begin(), deps.end(), rng);
419 std::set<Wtxid> wtxids;
420 std::vector<CTransactionRef> txn(NUM_TX);
422 for (
unsigned t = 0;
t < NUM_TX; ++
t) {
433 for (
unsigned output = 0; output < num_outputs; ++output) {
436 tx.
vout.emplace_back(
CAmount{0}, std::move(scriptpubkey));
439 for (
auto& [child, parent] : deps) {
441 auto& partx = txn[txorder[parent]];
442 assert(partx->version == 1);
444 tx.
vin.emplace_back(outpoint);
449 if (tx.
vin.empty()) {
451 tx.
vin.emplace_back(outpoint);
460 input.scriptWitness.stack.resize(1);
461 input.scriptWitness.stack[0].resize(rng.
randrange(100));
463 input.scriptWitness.stack.resize(0);
468 wtxids.insert(txn[txorder[
t]]->GetWitnessHash());
488 struct SimAnnouncement
492 bool reconsider{
false};
493 SimAnnouncement(
unsigned tx_in,
NodeId announcer_in,
bool reconsider_in) noexcept :
494 tx(tx_in), announcer(announcer_in), reconsider(reconsider_in) {}
499 std::vector<SimAnnouncement> sim_announcements;
506 auto read_tx_peer_fn = [&]() -> std::pair<unsigned, NodeId> {
508 return {code % NUM_TX, code / NUM_TX};
511 auto have_tx_fn = [&](
unsigned tx) ->
bool {
512 for (
auto& ann : sim_announcements) {
513 if (ann.tx == tx)
return true;
518 auto count_peers_fn = [&]() ->
unsigned {
519 std::bitset<NUM_PEERS> mask;
520 for (
auto& ann : sim_announcements) {
521 mask.set(ann.announcer);
526 auto have_reconsiderable_fn = [&](
unsigned tx) ->
bool {
527 for (
auto& ann : sim_announcements) {
528 if (ann.reconsider && ann.tx == tx)
return true;
533 auto have_reconsider_fn = [&](
NodeId peer) ->
bool {
534 for (
auto& ann : sim_announcements) {
535 if (ann.reconsider && ann.announcer == peer)
return true;
540 auto find_announce_wtxid_fn = [&](
const Wtxid& wtxid,
NodeId peer) -> std::vector<SimAnnouncement>::iterator {
541 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
542 if (txn[it->tx]->GetWitnessHash() == wtxid && it->announcer == peer)
return it;
544 return sim_announcements.end();
547 auto find_announce_fn = [&](
unsigned tx,
NodeId peer) {
548 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
549 if (it->tx == tx && it->announcer == peer)
return it;
551 return sim_announcements.end();
554 auto dos_score_fn = [&](
NodeId peer, int32_t max_count, int32_t max_usage) ->
FeeFrac {
557 for (
auto& ann : sim_announcements) {
558 if (ann.announcer != peer)
continue;
559 count += 1 + (txn[ann.tx]->vin.size() / 10);
562 return std::max<ByRatioNegSize<FeeFrac>>(
FeeFrac{
count, max_count},
FeeFrac{usage, max_usage});
572 if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
574 auto [tx, peer] = read_tx_peer_fn();
575 bool added = real->AddTx(txn[tx], peer);
576 bool sim_have_tx = have_tx_fn(tx);
577 assert(added == !sim_have_tx);
578 if (find_announce_fn(tx, peer) == sim_announcements.end()) {
579 sim_announcements.emplace_back(tx, peer,
false);
582 }
else if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
584 auto [tx, peer] = read_tx_peer_fn();
585 bool added = real->AddAnnouncer(txn[tx]->GetWitnessHash(), peer);
586 bool sim_have_tx = have_tx_fn(tx);
587 auto sim_it = find_announce_fn(tx, peer);
588 assert(added == (sim_it == sim_announcements.end() && sim_have_tx));
590 sim_announcements.emplace_back(tx, peer,
false);
595 auto tx = read_tx_fn();
596 bool erased = real->EraseTx(txn[tx]->GetWitnessHash());
597 bool sim_have = have_tx_fn(tx);
598 assert(erased == sim_have);
599 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.tx == tx; });
603 auto peer = read_peer_fn();
604 real->EraseForPeer(peer);
605 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.announcer == peer; });
611 std::set<COutPoint> spent;
612 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
613 if ((pattern >> tx) & 1) {
614 block.
vtx.emplace_back(txn[tx]);
615 for (
auto& txin : block.
vtx.back()->vin) {
616 spent.insert(txin.prevout);
620 std::shuffle(block.
vtx.begin(), block.
vtx.end(), rng);
621 real->EraseForBlock(block);
622 std::erase_if(sim_announcements, [&](
auto& ann) {
623 for (
auto& txin : txn[ann.tx]->vin) {
624 if (spent.contains(txin.prevout)) return true;
631 auto tx = read_tx_fn();
633 auto added = real->AddChildrenToWorkSet(*txn[tx], rand_ctx);
635 std::set<Wtxid> child_wtxids;
636 for (
unsigned child_tx = 0; child_tx < NUM_TX; ++child_tx) {
637 if (!have_tx_fn(child_tx))
continue;
638 if (have_reconsiderable_fn(child_tx))
continue;
639 bool child_of =
false;
640 for (
auto& txin : txn[child_tx]->vin) {
641 if (txin.prevout.hash == txn[tx]->GetHash()) {
647 child_wtxids.insert(txn[child_tx]->GetWitnessHash());
650 for (
auto& [wtxid, peer] : added) {
652 auto child_wtxid_it = child_wtxids.find(wtxid);
653 assert(child_wtxid_it != child_wtxids.end());
655 auto sim_ann_it = find_announce_wtxid_fn(wtxid, peer);
656 assert(sim_ann_it != sim_announcements.end());
658 assert(sim_ann_it->reconsider ==
false);
660 sim_ann_it->reconsider =
true;
662 child_wtxids.erase(wtxid);
667 assert(child_wtxids.empty());
671 auto peer = read_peer_fn();
672 auto result = real->GetTxToReconsider(peer);
676 auto sim_ann_it = find_announce_wtxid_fn(result->GetWitnessHash(), peer);
677 assert(sim_ann_it != sim_announcements.end());
678 assert(sim_ann_it->announcer == peer);
679 assert(sim_ann_it->reconsider);
681 sim_ann_it->reconsider =
false;
685 assert(!have_reconsider_fn(peer));
691 const auto max_ann = max_global_latency_score / std::max<unsigned>(1, count_peers_fn());
692 const auto max_mem = reserved_peer_usage;
697 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
698 if (have_tx_fn(tx)) {
700 total_latency_score += txn[tx]->vin.size() / 10;
703 auto num_peers = count_peers_fn();
704 bool oversized = (total_usage > reserved_peer_usage * num_peers) ||
705 (total_latency_score > real->MaxGlobalLatencyScore());
706 if (!oversized)
break;
709 unsigned worst_peer = unsigned(-1);
710 for (
unsigned peer = 0; peer < NUM_PEERS; ++peer) {
711 auto dos_score = dos_score_fn(peer, max_ann, max_mem);
715 worst_dos_score = dos_score;
719 assert(worst_peer !=
unsigned(-1));
723 for (
int reconsider = 0; reconsider < 2; ++reconsider) {
724 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
725 if (it->announcer != worst_peer || it->reconsider != reconsider)
continue;
726 sim_announcements.erase(it);
736 assert(real->TotalLatencyScore() <= real->MaxGlobalLatencyScore());
737 assert(real->TotalOrphanUsage() <= real->MaxGlobalUsage());
747 auto all_orphans = real->GetOrphanTransactions();
749 std::vector<node::TxOrphanage::Usage> usage_by_peer(NUM_PEERS);
751 std::vector<node::TxOrphanage::Count> count_by_peer(NUM_PEERS);
753 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
754 bool sim_have_tx = have_tx_fn(tx);
757 total_latency_score += txn[tx]->vin.size() / 10;
759 unique_orphans += sim_have_tx;
760 auto orphans_it = std::find_if(all_orphans.begin(), all_orphans.end(), [&](
auto& orph) { return orph.tx->GetWitnessHash() == txn[tx]->GetWitnessHash(); });
762 assert((orphans_it != all_orphans.end()) == sim_have_tx);
764 bool have_tx = real->HaveTx(txn[tx]->GetWitnessHash());
765 assert(have_tx == sim_have_tx);
767 auto txref = real->GetTx(txn[tx]->GetWitnessHash());
768 assert(!!txref == sim_have_tx);
769 if (sim_have_tx)
assert(txref->GetWitnessHash() == txn[tx]->GetWitnessHash());
771 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
772 auto it_sim_ann = find_announce_fn(tx, peer);
773 bool sim_have_ann = it_sim_ann != sim_announcements.end();
775 count_by_peer[peer] += sim_have_ann;
777 if (sim_have_ann)
assert(sim_have_tx);
778 if (sim_have_tx)
assert(orphans_it->announcers.count(peer) == sim_have_ann);
780 bool have_ann = real->HaveTxFromPeer(txn[tx]->GetWitnessHash(), peer);
781 assert(sim_have_ann == have_ann);
783 auto children_from_peer = real->GetChildrenFromSamePeer(txn[tx], peer);
784 auto it = children_from_peer.rbegin();
785 for (
int phase = 0; phase < 2; ++phase) {
787 for (
auto& ann : sim_announcements) {
788 if (ann.announcer != peer)
continue;
789 if (ann.reconsider != (phase == 1))
continue;
790 bool matching_parent{
false};
791 for (
const auto& vin : txn[ann.tx]->vin) {
792 if (vin.prevout.hash == txn[tx]->GetHash()) matching_parent =
true;
794 if (!matching_parent)
continue;
796 assert(it != children_from_peer.rend());
797 assert((*it)->GetWitnessHash() == txn[ann.tx]->GetWitnessHash());
801 assert(it == children_from_peer.rend());
805 assert(orphan_usage == real->TotalOrphanUsage());
806 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
807 bool sim_have_reconsider = have_reconsider_fn(peer);
809 bool have_reconsider = real->HaveTxToReconsider(peer);
810 assert(have_reconsider == sim_have_reconsider);
812 assert(usage_by_peer[peer] == real->UsageByPeer(peer));
814 assert(count_by_peer[peer] == real->AnnouncementsFromPeer(peer));
817 assert(sim_announcements.size() == real->CountAnnouncements());
819 assert(unique_orphans == real->CountUniqueOrphans());
821 assert(max_global_latency_score == real->MaxGlobalLatencyScore());
823 assert(reserved_peer_usage == real->ReservedPeerUsage());
825 auto present_peers = count_peers_fn();
826 assert(max_global_latency_score / std::max<unsigned>(1, present_peers) == real->MaxPeerLatencyScore());
828 assert(reserved_peer_usage * std::max<unsigned>(1, present_peers) == real->MaxGlobalUsage());
830 assert(real->TotalLatencyScore() == total_latency_score);
int64_t CAmount
Amount in satoshis (Can be negative)
#define Assert(val)
Identity function.
Wrapper around FeeFrac & derived types, which adds a feerate-based ordering which treats equal-feerat...
Wrapper around FeeFrac & derived types, which adds a total ordering which first sorts by feerate and ...
std::vector< CTransactionRef > vtx
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
T ConsumeIntegralInRange(T min, T max)
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
uint256 rand256() noexcept
generate a random uint256.
bool randbool() noexcept
Generate a random boolean.
void resize(size_type new_size)
transaction_identifier represents the two canonical transaction identifier types (txid,...
static transaction_identifier FromUint256(const uint256 &id)
static int32_t GetTransactionWeight(const CTransaction &tx)
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
std::unique_ptr< TxOrphanage > MakeTxOrphanage() noexcept
Create a new TxOrphanage instance.
static constexpr int32_t MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
std::unique_ptr< T > MakeNoLogFileContext(const ChainType chain_type=ChainType::REGTEST, TestOpts opts={})
Make a test setup that has disk access to the debug.log file disabled.
A mutable version of CTransaction.
std::vector< CTxOut > vout
Data structure storing a fee and size.
NodeSeconds 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)
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
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.
void initialize_orphanage()
FUZZ_TARGET(txorphan,.init=initialize_orphanage)
FuzzedDataProvider & fuzzed_data_provider