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;
67 tx_mut.
vin.reserve(num_in);
68 for (uint32_t i = 0; i < num_in; i++) {
74 tx_mut.
vout.reserve(num_out);
75 for (uint32_t i = 0; i < num_out; i++) {
80 for (uint32_t i = 0; i < num_out; i++) {
81 outpoints.emplace_back(new_tx->GetHash(), i);
86 tx_history.push_back(tx);
88 const auto wtxid{tx->GetWitnessHash()};
92 if (ptx_potential_parent) {
94 orphanage->AddChildrenToWorkSet(*ptx_potential_parent, orphanage_rng);
98 for (
const auto& child : orphanage->GetChildrenFromSamePeer(ptx_potential_parent, peer_id)) {
99 assert(std::any_of(child->vin.cbegin(), child->vin.cend(), [&](
const auto& input) {
100 return input.prevout.hash == ptx_potential_parent->GetHash();
108 const auto total_bytes_start{orphanage->TotalOrphanUsage()};
109 const auto total_peer_bytes_start{orphanage->UsageByPeer(peer_id)};
118 Assert(orphanage->HaveTx(ref->GetWitnessHash()));
123 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
124 bool have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
128 bool add_tx = orphanage->AddTx(tx, peer_id);
130 Assert(!have_tx || !add_tx);
132 Assert(!have_tx_and_peer || !add_tx);
139 if (orphanage->UsageByPeer(peer_id) > total_peer_bytes_start) {
140 Assert(orphanage->HaveTxFromPeer(wtxid, peer_id));
145 Assert(orphanage->TotalOrphanUsage() <= total_bytes_start);
154 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
155 bool have_tx_and_peer = orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id);
158 bool added_announcer = orphanage->AddAnnouncer(tx->GetWitnessHash(), peer_id);
160 Assert(have_tx || !added_announcer);
162 Assert(!have_tx_and_peer || !added_announcer);
166 Assert(orphanage->TotalOrphanUsage() <= total_bytes_start);
170 bool have_tx = orphanage->HaveTx(tx->GetWitnessHash());
171 bool have_tx_and_peer{orphanage->HaveTxFromPeer(wtxid, peer_id)};
174 auto bytes_from_peer_before{orphanage->UsageByPeer(peer_id)};
175 Assert(have_tx == orphanage->EraseTx(tx->GetWitnessHash()));
178 Assert(orphanage->UsageByPeer(peer_id) == bytes_from_peer_before);
179 }
else if (have_tx_and_peer) {
180 Assert(orphanage->UsageByPeer(peer_id) <= bytes_from_peer_before - tx_weight);
182 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;
278 tx_mut.
vin.reserve(num_in);
279 for (uint32_t i = 0; i < num_in; i++) {
285 tx_mut.
vout.reserve(num_out);
286 for (uint32_t i = 0; i < num_out; i++) {
289 tx_mut.
vout.emplace_back(0,
CScript() << OP_RETURN << std::vector<unsigned char>(payload_size));
296 for (uint32_t i = 0; i < num_out; i++) {
297 outpoints.emplace_back(new_tx->GetHash(), i);
302 const auto wtxid{tx->GetWitnessHash()};
311 const bool peer_is_protected{protected_peers[peer_id]};
316 bool have_tx_and_peer = orphanage->HaveTxFromPeer(wtxid, peer_id);
317 if (peer_is_protected && !have_tx_and_peer &&
318 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
319 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
322 orphanage->AddTx(tx, peer_id);
323 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
324 protected_wtxids.insert(wtxid);
329 bool have_tx_and_peer = orphanage->HaveTxFromPeer(tx->GetWitnessHash(), peer_id);
332 if (peer_is_protected && !have_tx_and_peer &&
333 (orphanage->UsageByPeer(peer_id) + tx_weight > honest_mem_limit ||
334 orphanage->LatencyScoreFromPeer(peer_id) + (tx->vin.size() / 10) + 1 > honest_latency_limit)) {
337 orphanage->AddAnnouncer(tx->GetWitnessHash(), peer_id);
338 if (peer_is_protected && orphanage->HaveTxFromPeer(wtxid, peer_id)) {
339 protected_wtxids.insert(wtxid);
345 if (protected_wtxids.contains(tx->GetWitnessHash())) {
346 protected_wtxids.erase(wtxid);
348 orphanage->EraseTx(wtxid);
349 Assert(!orphanage->HaveTx(wtxid));
352 if (!protected_peers[peer_id]) {
353 orphanage->EraseForPeer(peer_id);
354 Assert(orphanage->UsageByPeer(peer_id) == 0);
355 Assert(orphanage->LatencyScoreFromPeer(peer_id) == 0);
356 Assert(orphanage->AnnouncementsFromPeer(peer_id) == 0);
363 orphanage->SanityCheck();
365 for (
const auto& wtxid : protected_wtxids) {
366 Assert(orphanage->HaveTx(wtxid));
385 static constexpr unsigned NUM_TX = 16;
388 static constexpr unsigned NUM_PEERS = 16;
391 static constexpr unsigned MAX_ANN = 64;
403 std::vector<unsigned> txorder(NUM_TX);
404 std::iota(txorder.begin(), txorder.end(),
unsigned{0});
405 std::shuffle(txorder.begin(), txorder.end(),
rng);
407 std::vector<std::pair<unsigned, unsigned>> deps;
408 deps.reserve((NUM_TX * (NUM_TX - 1)) / 2);
409 for (
unsigned p = 0; p < NUM_TX - 1; ++p) {
410 for (
unsigned c = p + 1; c < NUM_TX; ++c) {
411 deps.emplace_back(c, p);
414 std::shuffle(deps.begin(), deps.end(),
rng);
417 std::set<Wtxid> wtxids;
418 std::vector<CTransactionRef> txn(NUM_TX);
420 for (
unsigned t = 0;
t < NUM_TX; ++
t) {
431 for (
unsigned output = 0; output < num_outputs; ++output) {
434 tx.
vout.emplace_back(
CAmount{0}, std::move(scriptpubkey));
437 for (
auto& [child, parent] : deps) {
439 auto& partx = txn[txorder[parent]];
440 assert(partx->version == 1);
442 tx.
vin.emplace_back(outpoint);
447 if (tx.
vin.empty()) {
449 tx.
vin.emplace_back(outpoint);
458 input.scriptWitness.stack.resize(1);
459 input.scriptWitness.stack[0].resize(
rng.
randrange(100));
461 input.scriptWitness.stack.resize(0);
466 wtxids.insert(txn[txorder[
t]]->GetWitnessHash());
486 struct SimAnnouncement
490 bool reconsider{
false};
491 SimAnnouncement(
unsigned tx_in,
NodeId announcer_in,
bool reconsider_in) noexcept :
492 tx(tx_in), announcer(announcer_in), reconsider(reconsider_in) {}
497 std::vector<SimAnnouncement> sim_announcements;
504 auto read_tx_peer_fn = [&]() -> std::pair<unsigned, NodeId> {
506 return {code % NUM_TX, code / NUM_TX};
509 auto have_tx_fn = [&](
unsigned tx) ->
bool {
510 for (
auto& ann : sim_announcements) {
511 if (ann.tx == tx)
return true;
516 auto count_peers_fn = [&]() ->
unsigned {
517 std::bitset<NUM_PEERS> mask;
518 for (
auto& ann : sim_announcements) {
519 mask.set(ann.announcer);
524 auto have_reconsiderable_fn = [&](
unsigned tx) ->
bool {
525 for (
auto& ann : sim_announcements) {
526 if (ann.reconsider && ann.tx == tx)
return true;
531 auto have_reconsider_fn = [&](
NodeId peer) ->
bool {
532 for (
auto& ann : sim_announcements) {
533 if (ann.reconsider && ann.announcer == peer)
return true;
538 auto find_announce_wtxid_fn = [&](
const Wtxid& wtxid,
NodeId peer) -> std::vector<SimAnnouncement>::iterator {
539 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
540 if (txn[it->tx]->GetWitnessHash() == wtxid && it->announcer == peer)
return it;
542 return sim_announcements.end();
545 auto find_announce_fn = [&](
unsigned tx,
NodeId peer) {
546 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
547 if (it->tx == tx && it->announcer == peer)
return it;
549 return sim_announcements.end();
552 auto dos_score_fn = [&](
NodeId peer, int32_t max_count, int32_t max_usage) ->
FeeFrac {
555 for (
auto& ann : sim_announcements) {
556 if (ann.announcer != peer)
continue;
557 count += 1 + (txn[ann.tx]->vin.size() / 10);
560 return std::max<ByRatioNegSize<FeeFrac>>(
FeeFrac{
count, max_count},
FeeFrac{usage, max_usage});
570 if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
572 auto [tx, peer] = read_tx_peer_fn();
573 bool added = real->AddTx(txn[tx], peer);
574 bool sim_have_tx = have_tx_fn(tx);
575 assert(added == !sim_have_tx);
576 if (find_announce_fn(tx, peer) == sim_announcements.end()) {
577 sim_announcements.emplace_back(tx, peer,
false);
580 }
else if (sim_announcements.size() < MAX_ANN &&
command-- == 0) {
582 auto [tx, peer] = read_tx_peer_fn();
583 bool added = real->AddAnnouncer(txn[tx]->GetWitnessHash(), peer);
584 bool sim_have_tx = have_tx_fn(tx);
585 auto sim_it = find_announce_fn(tx, peer);
586 assert(added == (sim_it == sim_announcements.end() && sim_have_tx));
588 sim_announcements.emplace_back(tx, peer,
false);
593 auto tx = read_tx_fn();
594 bool erased = real->EraseTx(txn[tx]->GetWitnessHash());
595 bool sim_have = have_tx_fn(tx);
596 assert(erased == sim_have);
597 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.tx == tx; });
601 auto peer = read_peer_fn();
602 real->EraseForPeer(peer);
603 std::erase_if(sim_announcements, [&](
auto& ann) {
return ann.announcer == peer; });
609 std::set<COutPoint> spent;
610 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
611 if ((pattern >> tx) & 1) {
612 block.
vtx.emplace_back(txn[tx]);
613 for (
auto& txin : block.
vtx.back()->vin) {
614 spent.insert(txin.prevout);
618 std::shuffle(block.
vtx.begin(), block.
vtx.end(),
rng);
619 real->EraseForBlock(block);
620 std::erase_if(sim_announcements, [&](
auto& ann) {
621 for (
auto& txin : txn[ann.tx]->vin) {
622 if (spent.contains(txin.prevout)) return true;
629 auto tx = read_tx_fn();
631 auto added = real->AddChildrenToWorkSet(*txn[tx], rand_ctx);
633 std::set<Wtxid> child_wtxids;
634 for (
unsigned child_tx = 0; child_tx < NUM_TX; ++child_tx) {
635 if (!have_tx_fn(child_tx))
continue;
636 if (have_reconsiderable_fn(child_tx))
continue;
637 bool child_of =
false;
638 for (
auto& txin : txn[child_tx]->vin) {
639 if (txin.prevout.hash == txn[tx]->GetHash()) {
645 child_wtxids.insert(txn[child_tx]->GetWitnessHash());
648 for (
auto& [wtxid, peer] : added) {
650 auto child_wtxid_it = child_wtxids.find(wtxid);
651 assert(child_wtxid_it != child_wtxids.end());
653 auto sim_ann_it = find_announce_wtxid_fn(wtxid, peer);
654 assert(sim_ann_it != sim_announcements.end());
656 assert(sim_ann_it->reconsider ==
false);
658 sim_ann_it->reconsider =
true;
660 child_wtxids.erase(wtxid);
665 assert(child_wtxids.empty());
669 auto peer = read_peer_fn();
670 auto result = real->GetTxToReconsider(peer);
674 auto sim_ann_it = find_announce_wtxid_fn(result->GetWitnessHash(), peer);
675 assert(sim_ann_it != sim_announcements.end());
676 assert(sim_ann_it->announcer == peer);
677 assert(sim_ann_it->reconsider);
679 sim_ann_it->reconsider =
false;
683 assert(!have_reconsider_fn(peer));
689 const auto max_ann = max_global_latency_score / std::max<unsigned>(1, count_peers_fn());
690 const auto max_mem = reserved_peer_usage;
695 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
696 if (have_tx_fn(tx)) {
698 total_latency_score += txn[tx]->vin.size() / 10;
701 auto num_peers = count_peers_fn();
702 bool oversized = (total_usage > reserved_peer_usage * num_peers) ||
703 (total_latency_score > real->MaxGlobalLatencyScore());
704 if (!oversized)
break;
707 unsigned worst_peer = unsigned(-1);
708 for (
unsigned peer = 0; peer < NUM_PEERS; ++peer) {
709 auto dos_score = dos_score_fn(peer, max_ann, max_mem);
713 worst_dos_score = dos_score;
717 assert(worst_peer !=
unsigned(-1));
721 for (
int reconsider = 0; reconsider < 2; ++reconsider) {
722 for (
auto it = sim_announcements.begin(); it != sim_announcements.end(); ++it) {
723 if (it->announcer != worst_peer || it->reconsider != reconsider)
continue;
724 sim_announcements.erase(it);
734 assert(real->TotalLatencyScore() <= real->MaxGlobalLatencyScore());
735 assert(real->TotalOrphanUsage() <= real->MaxGlobalUsage());
745 auto all_orphans = real->GetOrphanTransactions();
747 std::vector<node::TxOrphanage::Usage> usage_by_peer(NUM_PEERS);
749 std::vector<node::TxOrphanage::Count> count_by_peer(NUM_PEERS);
751 for (
unsigned tx = 0; tx < NUM_TX; ++tx) {
752 bool sim_have_tx = have_tx_fn(tx);
755 total_latency_score += txn[tx]->vin.size() / 10;
757 unique_orphans += sim_have_tx;
758 auto orphans_it = std::find_if(all_orphans.begin(), all_orphans.end(), [&](
auto& orph) { return orph.tx->GetWitnessHash() == txn[tx]->GetWitnessHash(); });
760 assert((orphans_it != all_orphans.end()) == sim_have_tx);
762 bool have_tx = real->HaveTx(txn[tx]->GetWitnessHash());
763 assert(have_tx == sim_have_tx);
765 auto txref = real->GetTx(txn[tx]->GetWitnessHash());
766 assert(!!txref == sim_have_tx);
767 if (sim_have_tx)
assert(txref->GetWitnessHash() == txn[tx]->GetWitnessHash());
769 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
770 auto it_sim_ann = find_announce_fn(tx, peer);
771 bool sim_have_ann = it_sim_ann != sim_announcements.end();
773 count_by_peer[peer] += sim_have_ann;
775 if (sim_have_ann)
assert(sim_have_tx);
776 if (sim_have_tx)
assert(orphans_it->announcers.count(peer) == sim_have_ann);
778 bool have_ann = real->HaveTxFromPeer(txn[tx]->GetWitnessHash(), peer);
779 assert(sim_have_ann == have_ann);
781 auto children_from_peer = real->GetChildrenFromSamePeer(txn[tx], peer);
782 auto it = children_from_peer.rbegin();
783 for (
int phase = 0; phase < 2; ++phase) {
785 for (
auto& ann : sim_announcements) {
786 if (ann.announcer != peer)
continue;
787 if (ann.reconsider != (phase == 1))
continue;
788 bool matching_parent{
false};
789 for (
const auto& vin : txn[ann.tx]->vin) {
790 if (vin.prevout.hash == txn[tx]->GetHash()) matching_parent =
true;
792 if (!matching_parent)
continue;
794 assert(it != children_from_peer.rend());
795 assert((*it)->GetWitnessHash() == txn[ann.tx]->GetWitnessHash());
799 assert(it == children_from_peer.rend());
803 assert(orphan_usage == real->TotalOrphanUsage());
804 for (
NodeId peer = 0; peer < NUM_PEERS; ++peer) {
805 bool sim_have_reconsider = have_reconsider_fn(peer);
807 bool have_reconsider = real->HaveTxToReconsider(peer);
808 assert(have_reconsider == sim_have_reconsider);
810 assert(usage_by_peer[peer] == real->UsageByPeer(peer));
812 assert(count_by_peer[peer] == real->AnnouncementsFromPeer(peer));
815 assert(sim_announcements.size() == real->CountAnnouncements());
817 assert(unique_orphans == real->CountUniqueOrphans());
819 assert(max_global_latency_score == real->MaxGlobalLatencyScore());
821 assert(reserved_peer_usage == real->ReservedPeerUsage());
823 auto present_peers = count_peers_fn();
824 assert(max_global_latency_score / std::max<unsigned>(1, present_peers) == real->MaxPeerLatencyScore());
826 assert(reserved_peer_usage * std::max<unsigned>(1, present_peers) == real->MaxGlobalUsage());
828 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 constexpr uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
T ConsumeIntegralInRange(T min, T max)
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)
static transaction_identifier FromUint256(const uint256 &id)
LIMITED_WHILE(provider.remaining_bytes(), 10000)
static int32_t GetTransactionWeight(const CTransaction &tx)
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
std::unique_ptr< TxOrphanage > MakeTxOrphanage() noexcept
Create a new TxOrphanage instance.
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.
SeedRandomStateForTest(SeedRand::ZEROS)
FuzzedDataProvider provider
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)
@ ZEROS
Seed with a compile time constant of zeros.
void initialize_orphanage()
FUZZ_TARGET(txorphan,.init=initialize_orphanage)
FuzzedDataProvider & fuzzed_data_provider