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);
201 for (
int i{0}; i < num_txs; ++i) {
203 block.
vtx.push_back(tx_to_remove);
205 orphanage->EraseForBlock(block);
206 for (
const auto& tx_removed : block.
vtx) {
207 Assert(!orphanage->HaveTx(tx_removed->GetWitnessHash()));
208 Assert(!orphanage->HaveTxFromPeer(tx_removed->GetWitnessHash(), peer_id));
216 ptx_potential_parent = tx;
219 const bool have_tx{orphanage->HaveTx(tx->GetWitnessHash())};
220 const bool get_tx_nonnull{orphanage->GetTx(tx->GetWitnessHash()) !=
nullptr};
221 Assert(have_tx == get_tx_nonnull);
223 orphanage->SanityCheck();
235 const unsigned int MAX_PEERS = 125;
238 std::bitset<MAX_PEERS> protected_peers;
239 for (
unsigned int i = 0; i < num_peers; i++) {
251 const unsigned int honest_latency_limit = global_latency_score_limit / num_peers;
253 const int64_t honest_mem_limit = per_peer_weight_reservation;
255 std::vector<COutPoint> outpoints;
256 outpoints.reserve(400);
259 for (uint8_t i = 0; i < 4; i++) {
264 std::set<Wtxid> protected_wtxids;
275 tx_mut.
vin.reserve(num_in);
276 for (uint32_t i = 0; i < num_in; i++) {
282 tx_mut.
vout.reserve(num_out);
283 for (uint32_t i = 0; i < num_out; i++) {
286 tx_mut.
vout.emplace_back(0,
CScript() << OP_RETURN << std::vector<unsigned char>(payload_size));
293 for (uint32_t i = 0; i < num_out; i++) {
294 outpoints.emplace_back(new_tx->GetHash(), i);
299 const auto wtxid{tx->GetWitnessHash()};
309 const bool peer_is_protected{protected_peers[peer_id]};
314 bool have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
315 if (peer_is_protected && !have_tx_and_peer &&
316 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
317 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
320 orphanage->AddTx(tx, peer_id);
321 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
322 protected_wtxids.insert(wtxid);
327 bool have_tx_and_peer = orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id);
330 if (peer_is_protected && !have_tx_and_peer &&
331 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
332 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
335 orphanage->AddAnnouncer(tx->GetWitnessHash(), peer_id);
336 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
337 protected_wtxids.insert(wtxid);
343 if (protected_wtxids.contains(tx->GetWitnessHash())) {
344 protected_wtxids.erase(wtxid);
346 orphanage->EraseTx(wtxid);
347 Assert(!orphanage->HaveTx(wtxid));
350 if (!protected_peers[peer_id]) {
351 orphanage->EraseForPeer(peer_id);
352 Assert(orphanage->UsageByPeer(peer_id) == 0);
353 Assert(orphanage->LatencyScoreFromPeer(peer_id) == 0);
354 Assert(orphanage->AnnouncementsFromPeer(peer_id) == 0);
361 orphanage->SanityCheck();
363 for (
const auto& wtxid : protected_wtxids) {
364 Assert(orphanage->HaveTx(wtxid));
383 static constexpr unsigned NUM_TX = 16;
386 static constexpr unsigned NUM_PEERS = 16;
389 static constexpr unsigned MAX_ANN = 64;
401 std::vector<unsigned> txorder(NUM_TX);
402 std::iota(txorder.begin(), txorder.end(),
unsigned{0});
403 std::shuffle(txorder.begin(), txorder.end(), rng);
405 std::vector<std::pair<unsigned, unsigned>> deps;
406 deps.reserve((NUM_TX * (NUM_TX - 1)) / 2);
407 for (
unsigned p = 0; p < NUM_TX - 1; ++p) {
408 for (
unsigned c = p + 1; c < NUM_TX; ++c) {
409 deps.emplace_back(c, p);
412 std::shuffle(deps.begin(), deps.end(), rng);
415 std::set<Wtxid> wtxids;
416 std::vector<CTransactionRef> txn(NUM_TX);
418 for (
unsigned t = 0;
t < NUM_TX; ++
t) {
429 for (
unsigned output = 0; output < num_outputs; ++output) {
432 tx.
vout.emplace_back(
CAmount{0}, std::move(scriptpubkey));
435 for (
auto& [child, parent] : deps) {
437 auto& partx = txn[txorder[parent]];
438 assert(partx->version == 1);
440 tx.
vin.emplace_back(outpoint);
445 if (tx.
vin.empty()) {
447 tx.
vin.emplace_back(outpoint);
456 input.scriptWitness.stack.resize(1);
457 input.scriptWitness.stack[0].resize(rng.
randrange(100));
459 input.scriptWitness.stack.resize(0);
464 wtxids.insert(txn[txorder[
t]]->GetWitnessHash());
484 struct SimAnnouncement
488 bool reconsider{
false};
489 SimAnnouncement(
unsigned tx_in,
NodeId announcer_in,
bool reconsider_in) noexcept :
490 tx(tx_in), announcer(announcer_in), reconsider(reconsider_in) {}
495 std::vector<SimAnnouncement> sim_announcements;
502 auto read_tx_peer_fn = [&]() -> std::pair<unsigned, NodeId> {
504 return {code % NUM_TX, code / NUM_TX};
507 auto have_tx_fn = [&](
unsigned tx) ->
bool {
508 for (
auto& ann : sim_announcements) {
509 if (ann.tx == tx)
return true;
514 auto count_peers_fn = [&]() ->
unsigned {
515 std::bitset<NUM_PEERS> mask;
516 for (
auto& ann : sim_announcements) {
517 mask.set(ann.announcer);
522 auto have_reconsiderable_fn = [&](
unsigned tx) ->
bool {
523 for (
auto& ann : sim_announcements) {
524 if (ann.reconsider && ann.tx == tx)
return true;
529 auto have_reconsider_fn = [&](
NodeId peer) ->
bool {
530 for (
auto& ann : sim_announcements) {
531 if (ann.reconsider && ann.announcer == peer)
return true;
536 auto find_announce_wtxid_fn = [&](
const Wtxid& wtxid,
NodeId peer) -> std::vector<SimAnnouncement>::iterator {
537 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
538 if (txn[it->tx]->GetWitnessHash() == wtxid && it->announcer == peer)
return it;
540 return sim_announcements.end();
543 auto find_announce_fn = [&](
unsigned tx,
NodeId peer) {
544 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
545 if (it->tx == tx && it->announcer == peer)
return it;
547 return sim_announcements.end();
550 auto dos_score_fn = [&](
NodeId peer, int32_t max_count, int32_t max_usage) ->
FeeFrac {
553 for (
auto& ann : sim_announcements) {
554 if (ann.announcer != peer)
continue;
555 count += 1 + (txn[ann.tx]->vin.size() / 10);
568 if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
570 auto [tx, peer] = read_tx_peer_fn();
571 bool added = real->AddTx(txn[tx], peer);
572 bool sim_have_tx = have_tx_fn(tx);
573 assert(added == !sim_have_tx);
574 if (find_announce_fn(tx, peer) == sim_announcements.end()) {
575 sim_announcements.emplace_back(tx, peer,
false);
578 }
else if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
580 auto [tx, peer] = read_tx_peer_fn();
581 bool added = real->AddAnnouncer(txn[tx]->GetWitnessHash(), peer);
582 bool sim_have_tx = have_tx_fn(tx);
583 auto sim_it = find_announce_fn(tx, peer);
584 assert(added == (sim_it == sim_announcements.end() && sim_have_tx));
586 sim_announcements.emplace_back(tx, peer,
false);
591 auto tx = read_tx_fn();
592 bool erased = real->EraseTx(txn[tx]->GetWitnessHash());
593 bool sim_have = have_tx_fn(tx);
594 assert(erased == sim_have);
595 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.tx == tx; });
599 auto peer = read_peer_fn();
600 real->EraseForPeer(peer);
601 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.announcer == peer; });
607 std::set<COutPoint> spent;
608 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
609 if ((pattern >> tx) & 1) {
610 block.
vtx.emplace_back(txn[tx]);
611 for (
auto& txin : block.
vtx.back()->vin) {
612 spent.insert(txin.prevout);
616 std::shuffle(block.
vtx.begin(), block.
vtx.end(), rng);
617 real->EraseForBlock(block);
618 std::erase_if(sim_announcements, [&](
auto& ann) {
619 for (
auto& txin : txn[ann.tx]->vin) {
620 if (spent.contains(txin.prevout)) return true;
627 auto tx = read_tx_fn();
629 auto added = real->AddChildrenToWorkSet(*txn[tx], rand_ctx);
631 std::set<Wtxid> child_wtxids;
632 for (
unsigned child_tx = 0; child_tx < NUM_TX; ++child_tx) {
633 if (!have_tx_fn(child_tx))
continue;
634 if (have_reconsiderable_fn(child_tx))
continue;
635 bool child_of =
false;
636 for (
auto& txin : txn[child_tx]->vin) {
637 if (txin.prevout.hash == txn[tx]->GetHash()) {
643 child_wtxids.insert(txn[child_tx]->GetWitnessHash());
646 for (
auto& [wtxid, peer] : added) {
648 auto child_wtxid_it = child_wtxids.find(wtxid);
649 assert(child_wtxid_it != child_wtxids.end());
651 auto sim_ann_it = find_announce_wtxid_fn(wtxid, peer);
652 assert(sim_ann_it != sim_announcements.end());
654 assert(sim_ann_it->reconsider ==
false);
656 sim_ann_it->reconsider =
true;
658 child_wtxids.erase(wtxid);
663 assert(child_wtxids.empty());
667 auto peer = read_peer_fn();
668 auto result = real->GetTxToReconsider(peer);
672 auto sim_ann_it = find_announce_wtxid_fn(result->GetWitnessHash(), peer);
673 assert(sim_ann_it != sim_announcements.end());
674 assert(sim_ann_it->announcer == peer);
675 assert(sim_ann_it->reconsider);
677 sim_ann_it->reconsider =
false;
681 assert(!have_reconsider_fn(peer));
687 const auto max_ann = max_global_latency_score / std::max<unsigned>(1, count_peers_fn());
688 const auto max_mem = reserved_peer_usage;
693 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
694 if (have_tx_fn(tx)) {
696 total_latency_score += txn[tx]->vin.size() / 10;
699 auto num_peers = count_peers_fn();
700 bool oversized = (total_usage > reserved_peer_usage * num_peers) ||
701 (total_latency_score > real->MaxGlobalLatencyScore());
702 if (!oversized)
break;
705 unsigned worst_peer = unsigned(-1);
706 for (
unsigned peer = 0; peer < NUM_PEERS; ++peer) {
707 auto dos_score = dos_score_fn(peer, max_ann, max_mem);
710 if (dos_score >= worst_dos_score) {
711 worst_dos_score = dos_score;
715 assert(worst_peer !=
unsigned(-1));
719 for (
int reconsider = 0; reconsider < 2; ++reconsider) {
720 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
721 if (it->announcer != worst_peer || it->reconsider != reconsider)
continue;
722 sim_announcements.erase(it);
732 assert(real->TotalLatencyScore() <= real->MaxGlobalLatencyScore());
733 assert(real->TotalOrphanUsage() <= real->MaxGlobalUsage());
743 auto all_orphans = real->GetOrphanTransactions();
745 std::vector<node::TxOrphanage::Usage> usage_by_peer(NUM_PEERS);
747 std::vector<node::TxOrphanage::Count> count_by_peer(NUM_PEERS);
749 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
750 bool sim_have_tx = have_tx_fn(tx);
753 total_latency_score += txn[tx]->vin.size() / 10;
755 unique_orphans += sim_have_tx;
756 auto orphans_it = std::find_if(all_orphans.begin(), all_orphans.end(), [&](
auto& orph) { return orph.tx->GetWitnessHash() == txn[tx]->GetWitnessHash(); });
758 assert((orphans_it != all_orphans.end()) == sim_have_tx);
760 bool have_tx = real->HaveTx(txn[tx]->GetWitnessHash());
761 assert(have_tx == sim_have_tx);
763 auto txref = real->GetTx(txn[tx]->GetWitnessHash());
764 assert(!!txref == sim_have_tx);
765 if (sim_have_tx)
assert(txref->GetWitnessHash() == txn[tx]->GetWitnessHash());
767 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
768 auto it_sim_ann = find_announce_fn(tx, peer);
769 bool sim_have_ann = it_sim_ann != sim_announcements.end();
771 count_by_peer[peer] += sim_have_ann;
773 if (sim_have_ann)
assert(sim_have_tx);
774 if (sim_have_tx)
assert(orphans_it->announcers.count(peer) == sim_have_ann);
776 bool have_ann = real->HaveTxFromPeer(txn[tx]->GetWitnessHash(), peer);
777 assert(sim_have_ann == have_ann);
779 auto children_from_peer = real->GetChildrenFromSamePeer(txn[tx], peer);
780 auto it = children_from_peer.rbegin();
781 for (
int phase = 0; phase < 2; ++phase) {
783 for (
auto& ann : sim_announcements) {
784 if (ann.announcer != peer)
continue;
785 if (ann.reconsider != (phase == 1))
continue;
786 bool matching_parent{
false};
787 for (
const auto& vin : txn[ann.tx]->vin) {
788 if (vin.prevout.hash == txn[tx]->GetHash()) matching_parent =
true;
790 if (!matching_parent)
continue;
792 assert(it != children_from_peer.rend());
793 assert((*it)->GetWitnessHash() == txn[ann.tx]->GetWitnessHash());
797 assert(it == children_from_peer.rend());
801 assert(orphan_usage == real->TotalOrphanUsage());
802 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
803 bool sim_have_reconsider = have_reconsider_fn(peer);
805 bool have_reconsider = real->HaveTxToReconsider(peer);
806 assert(have_reconsider == sim_have_reconsider);
808 assert(usage_by_peer[peer] == real->UsageByPeer(peer));
810 assert(count_by_peer[peer] == real->AnnouncementsFromPeer(peer));
813 assert(sim_announcements.size() == real->CountAnnouncements());
815 assert(unique_orphans == real->CountUniqueOrphans());
817 assert(max_global_latency_score == real->MaxGlobalLatencyScore());
819 assert(reserved_peer_usage == real->ReservedPeerUsage());
821 auto present_peers = count_peers_fn();
822 assert(max_global_latency_score / std::max<unsigned>(1, present_peers) == real->MaxPeerLatencyScore());
824 assert(reserved_peer_usage * std::max<unsigned>(1, present_peers) == real->MaxGlobalUsage());
826 assert(real->TotalLatencyScore() == total_latency_score);
int64_t CAmount
Amount in satoshis (Can be negative)
#define Assert(val)
Identity function.
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)
#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, ordered by increasing fee/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