13 #include <boost/multi_index/indexed_by.hpp> 14 #include <boost/multi_index/ordered_index.hpp> 15 #include <boost/multi_index/sequenced_index.hpp> 16 #include <boost/multi_index/tag.hpp> 17 #include <boost/multi_index_container.hpp> 18 #include <boost/tuple/tuple.hpp> 21 #include <unordered_map> 58 using SequenceNumber = uint64_t;
65 std::chrono::microseconds m_time;
69 const SequenceNumber m_sequence : 59;
71 const bool m_preferred : 1;
73 const bool m_is_wtxid : 1;
81 State GetState()
const {
return static_cast<State>(m_state); }
84 void SetState(
State state) { m_state =
static_cast<uint8_t
>(state); }
87 bool IsSelected()
const 89 return GetState() == State::CANDIDATE_BEST || GetState() == State::REQUESTED;
93 bool IsWaiting()
const 95 return GetState() == State::REQUESTED || GetState() == State::CANDIDATE_DELAYED;
99 bool IsSelectable()
const 101 return GetState() == State::CANDIDATE_READY || GetState() == State::CANDIDATE_BEST;
105 Announcement(
const GenTxid& gtxid,
NodeId peer,
bool preferred, std::chrono::microseconds reqtime,
107 m_txhash(gtxid.GetHash()), m_time(reqtime), m_peer(peer), m_sequence(
sequence), m_preferred(preferred),
108 m_is_wtxid(gtxid.IsWtxid()), m_state(static_cast<uint8_t>(
State::CANDIDATE_DELAYED)) {}
112 using Priority = uint64_t;
118 class PriorityComputer {
119 const uint64_t m_k0, m_k1;
121 explicit PriorityComputer(
bool deterministic) :
122 m_k0{deterministic ? 0 :
GetRand(0xFFFFFFFFFFFFFFFF)},
123 m_k1{deterministic ? 0 :
GetRand(0xFFFFFFFFFFFFFFFF)} {}
125 Priority operator()(
const uint256& txhash,
NodeId peer,
bool preferred)
const 128 return low_bits | uint64_t{preferred} << 63;
131 Priority operator()(
const Announcement& ann)
const 133 return operator()(ann.m_txhash, ann.m_peer, ann.m_preferred);
151 using ByPeerView = std::tuple<NodeId, bool, const uint256&>;
152 struct ByPeerViewExtractor
154 using result_type = ByPeerView;
155 result_type operator()(
const Announcement& ann)
const 157 return ByPeerView{ann.m_peer, ann.GetState() == State::CANDIDATE_BEST, ann.m_txhash};
172 using ByTxHashView = std::tuple<const uint256&, State, Priority>;
173 class ByTxHashViewExtractor {
174 const PriorityComputer& m_computer;
176 explicit ByTxHashViewExtractor(
const PriorityComputer& computer) : m_computer(computer) {}
177 using result_type = ByTxHashView;
178 result_type operator()(
const Announcement& ann)
const 180 const Priority prio = (ann.GetState() == State::CANDIDATE_READY) ? m_computer(ann) : 0;
181 return ByTxHashView{ann.m_txhash, ann.GetState(), prio};
194 WaitState GetWaitState(
const Announcement& ann)
196 if (ann.IsWaiting())
return WaitState::FUTURE_EVENT;
197 if (ann.IsSelectable())
return WaitState::PAST_EVENT;
198 return WaitState::NO_EVENT;
211 using ByTimeView = std::pair<WaitState, std::chrono::microseconds>;
212 struct ByTimeViewExtractor
214 using result_type = ByTimeView;
215 result_type operator()(
const Announcement& ann)
const 217 return ByTimeView{GetWaitState(ann), ann.m_time};
222 using Index = boost::multi_index_container<
224 boost::multi_index::indexed_by<
225 boost::multi_index::ordered_unique<boost::multi_index::tag<ByPeer>, ByPeerViewExtractor>,
226 boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTxHash>, ByTxHashViewExtractor>,
227 boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTime>, ByTimeViewExtractor>
232 template<
typename Tag>
233 using Iter =
typename Index::index<Tag>::type::iterator;
238 size_t m_completed = 0;
239 size_t m_requested = 0;
246 size_t m_candidate_delayed = 0;
248 size_t m_candidate_ready = 0;
250 size_t m_candidate_best = 0;
252 size_t m_requested = 0;
254 Priority m_priority_candidate_best = std::numeric_limits<Priority>::max();
256 Priority m_priority_best_candidate_ready = std::numeric_limits<Priority>::min();
258 std::vector<NodeId> m_peers;
262 bool operator==(
const PeerInfo& a,
const PeerInfo& b)
264 return std::tie(a.m_total, a.m_completed, a.m_requested) ==
265 std::tie(b.m_total, b.m_completed, b.m_requested);
269 std::unordered_map<NodeId, PeerInfo> RecomputePeerInfo(
const Index& index)
271 std::unordered_map<NodeId, PeerInfo>
ret;
272 for (
const Announcement& ann : index) {
273 PeerInfo& info =
ret[ann.m_peer];
275 info.m_requested += (ann.GetState() == State::REQUESTED);
276 info.m_completed += (ann.GetState() == State::COMPLETED);
282 std::map<uint256, TxHashInfo> ComputeTxHashInfo(
const Index& index,
const PriorityComputer& computer)
284 std::map<uint256, TxHashInfo>
ret;
285 for (
const Announcement& ann : index) {
286 TxHashInfo& info =
ret[ann.m_txhash];
288 info.m_candidate_delayed += (ann.GetState() == State::CANDIDATE_DELAYED);
289 info.m_candidate_ready += (ann.GetState() == State::CANDIDATE_READY);
290 info.m_candidate_best += (ann.GetState() == State::CANDIDATE_BEST);
291 info.m_requested += (ann.GetState() == State::REQUESTED);
293 if (ann.GetState() == State::CANDIDATE_BEST) {
294 info.m_priority_candidate_best = computer(ann);
296 if (ann.GetState() == State::CANDIDATE_READY) {
297 info.m_priority_best_candidate_ready = std::max(info.m_priority_best_candidate_ready, computer(ann));
300 info.m_peers.push_back(ann.m_peer);
336 TxHashInfo& info = item.second;
339 assert(info.m_candidate_delayed + info.m_candidate_ready + info.m_candidate_best + info.m_requested > 0);
342 assert(info.m_candidate_best + info.m_requested <= 1);
346 if (info.m_candidate_ready > 0) {
347 assert(info.m_candidate_best + info.m_requested == 1);
352 if (info.m_candidate_ready && info.m_candidate_best) {
353 assert(info.m_priority_candidate_best >= info.m_priority_best_candidate_ready);
357 std::sort(info.m_peers.begin(), info.m_peers.end());
358 assert(std::adjacent_find(info.m_peers.begin(), info.m_peers.end()) == info.m_peers.end());
364 for (
const Announcement& ann :
m_index) {
365 if (ann.IsWaiting()) {
369 }
else if (ann.IsSelectable()) {
372 assert(ann.m_time <= now);
379 template<
typename Tag>
383 peerit->second.m_completed -= it->GetState() == State::COMPLETED;
384 peerit->second.m_requested -= it->GetState() == State::REQUESTED;
385 if (--peerit->second.m_total == 0)
m_peerinfo.erase(peerit);
386 return m_index.get<Tag>().erase(it);
390 template<
typename Tag,
typename Modifier>
391 void Modify(Iter<Tag> it, Modifier modifier)
394 peerit->second.m_completed -= it->GetState() == State::COMPLETED;
395 peerit->second.m_requested -= it->GetState() == State::REQUESTED;
396 m_index.get<Tag>().modify(it, std::move(modifier));
397 peerit->second.m_completed += it->GetState() == State::COMPLETED;
398 peerit->second.m_requested += it->GetState() == State::REQUESTED;
407 assert(it->GetState() == State::CANDIDATE_DELAYED);
409 Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); });
414 auto it_next = std::next(it);
415 if (it_next ==
m_index.get<ByTxHash>().end() || it_next->m_txhash != it->m_txhash ||
416 it_next->GetState() == State::COMPLETED) {
419 Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
420 }
else if (it_next->GetState() == State::CANDIDATE_BEST) {
423 if (priority_new > priority_old) {
425 Modify<ByTxHash>(it_next, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); });
426 Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
435 assert(new_state == State::COMPLETED || new_state == State::CANDIDATE_DELAYED);
437 if (it->IsSelected() && it !=
m_index.get<ByTxHash>().begin()) {
438 auto it_prev = std::prev(it);
441 if (it_prev->m_txhash == it->m_txhash && it_prev->GetState() == State::CANDIDATE_READY) {
443 Modify<ByTxHash>(it_prev, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
446 Modify<ByTxHash>(it, [new_state](Announcement& ann){ ann.SetState(new_state); });
453 assert(it->GetState() != State::COMPLETED);
457 if (it !=
m_index.get<ByTxHash>().begin() && std::prev(it)->m_txhash == it->m_txhash)
return false;
460 if (std::next(it) !=
m_index.get<ByTxHash>().end() && std::next(it)->m_txhash == it->m_txhash &&
461 std::next(it)->GetState() != State::COMPLETED)
return false;
474 if (it->GetState() == State::COMPLETED)
return true;
480 it = Erase<ByTxHash>(it);
481 }
while (it !=
m_index.get<ByTxHash>().end() && it->m_txhash == txhash);
496 void SetTimePoint(std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired)
498 if (expired) expired->clear();
503 auto it =
m_index.get<ByTime>().begin();
504 if (it->GetState() == State::CANDIDATE_DELAYED && it->m_time <= now) {
506 }
else if (it->GetState() == State::REQUESTED && it->m_time <= now) {
507 if (expired) expired->emplace_back(it->m_peer,
ToGenTxid(*it));
518 auto it = std::prev(
m_index.get<ByTime>().end());
519 if (it->IsSelectable() && it->m_time > now) {
528 explicit Impl(
bool deterministic) :
532 boost::make_tuple(ByPeerViewExtractor(),
std::less<ByPeerView>()),
534 boost::make_tuple(ByTimeViewExtractor(),
std::less<ByTimeView>())
543 auto& index =
m_index.get<ByPeer>();
544 auto it = index.lower_bound(ByPeerView{peer,
false,
uint256::ZERO});
545 while (it != index.end() && it->m_peer == peer) {
559 auto it_next = (std::next(it) == index.end() || std::next(it)->m_peer != peer) ? index.end() :
574 auto it =
m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_DELAYED, 0});
575 while (it !=
m_index.get<ByTxHash>().end() && it->m_txhash == txhash) {
576 it = Erase<ByTxHash>(it);
581 std::chrono::microseconds reqtime)
586 if (
m_index.get<ByPeer>().count(ByPeerView{peer, true, gtxid.GetHash()}))
return;
592 if (!
ret.second)
return;
601 std::vector<std::pair<NodeId, GenTxid>>* expired)
607 std::vector<const Announcement*> selected;
609 while (it_peer !=
m_index.get<ByPeer>().end() && it_peer->m_peer == peer &&
610 it_peer->GetState() == State::CANDIDATE_BEST) {
611 selected.emplace_back(&*it_peer);
616 std::sort(selected.begin(), selected.end(), [](
const Announcement* a,
const Announcement* b) {
617 return a->m_sequence < b->m_sequence;
621 std::vector<GenTxid>
ret;
622 ret.reserve(selected.size());
623 std::transform(selected.begin(), selected.end(), std::back_inserter(
ret), [](
const Announcement* ann) {
631 auto it =
m_index.get<ByPeer>().find(ByPeerView{peer,
true, txhash});
632 if (it ==
m_index.get<ByPeer>().end()) {
638 it =
m_index.get<ByPeer>().find(ByPeerView{peer,
false, txhash});
639 if (it ==
m_index.get<ByPeer>().end() || (it->GetState() != State::CANDIDATE_DELAYED &&
640 it->GetState() != State::CANDIDATE_READY)) {
650 auto it_old =
m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_BEST, 0});
651 if (it_old !=
m_index.get<ByTxHash>().end() && it_old->m_txhash == txhash) {
652 if (it_old->GetState() == State::CANDIDATE_BEST) {
659 Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::CANDIDATE_READY); });
660 }
else if (it_old->GetState() == State::REQUESTED) {
663 Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::COMPLETED); });
668 Modify<ByPeer>(it, [expiry](Announcement& ann) {
669 ann.SetState(State::REQUESTED);
677 auto it =
m_index.get<ByPeer>().find(ByPeerView{peer,
false, txhash});
678 if (it ==
m_index.get<ByPeer>().end()) {
679 it =
m_index.get<ByPeer>().find(ByPeerView{peer,
true, txhash});
687 if (it !=
m_peerinfo.end())
return it->second.m_requested;
694 if (it !=
m_peerinfo.end())
return it->second.m_total - it->second.m_requested - it->second.m_completed;
701 if (it !=
m_peerinfo.end())
return it->second.m_total;
711 return uint64_t{
m_computer(txhash, peer, preferred)};
717 m_impl{std::make_unique<TxRequestTracker::Impl>(deterministic)} {}
731 m_impl->PostGetRequestableSanityCheck(now);
735 std::chrono::microseconds reqtime)
737 m_impl->ReceivedInv(peer, gtxid, preferred, reqtime);
742 m_impl->RequestedTx(peer, txhash, expiry);
747 m_impl->ReceivedResponse(peer, txhash);
751 std::vector<std::pair<NodeId, GenTxid>>* expired)
753 return m_impl->GetRequestable(peer, now, expired);
758 return m_impl->ComputePriority(txhash, peer, preferred);
Impl & operator=(const Impl &)=delete
void ReceivedResponse(NodeId peer, const uint256 &txhash)
Converts a CANDIDATE or REQUESTED announcement to a COMPLETED one.
void ReceivedResponse(NodeId peer, const uint256 &txhash)
static GenTxid Wtxid(const uint256 &hash)
size_t Count(NodeId peer) const
Count how many announcements a peer has (REQUESTED, CANDIDATE, and COMPLETED combined).
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
bool operator==(const CNetAddr &a, const CNetAddr &b)
std::vector< GenTxid > GetRequestable(NodeId peer, std::chrono::microseconds now, std::vector< std::pair< NodeId, GenTxid >> *expired=nullptr)
Find the txids to request now from peer.
void ReceivedInv(NodeId peer, const GenTxid >xid, bool preferred, std::chrono::microseconds reqtime)
Adds a new CANDIDATE announcement.
size_t CountInFlight(NodeId peer) const
Count how many REQUESTED announcements a peer has.
bool MakeCompleted(Iter< ByTxHash > it)
Convert any announcement to a COMPLETED one.
void SetTimePoint(std::chrono::microseconds now, std::vector< std::pair< NodeId, GenTxid >> *expired)
Make the data structure consistent with a given point in time:
std::vector< GenTxid > GetRequestable(NodeId peer, std::chrono::microseconds now, std::vector< std::pair< NodeId, GenTxid >> *expired)
Find the GenTxids to request now from peer.
bool IsOnlyNonCompleted(Iter< ByTxHash > it)
Check if 'it' is the only announcement for a given txhash that isn't COMPLETED.
void ReceivedInv(NodeId peer, const GenTxid >xid, bool preferred, std::chrono::microseconds reqtime)
const PriorityComputer m_computer
This tracker's priority computer.
size_t Count(NodeId peer) const
State
The various states a (txhash,peer) pair can be in.
void Modify(Iter< Tag > it, Modifier modifier)
Wrapper around Index::...::modify that keeps m_peerinfo up to date.
size_t Size() const
Count how many announcements are being tracked in total across all peers and transaction hashes...
void DisconnectedPeer(NodeId peer)
size_t CountInFlight(NodeId peer) const
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
void DisconnectedPeer(NodeId peer)
Deletes all announcements for a given peer.
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
void SanityCheck() const
Run internal consistency check (testing only).
size_t CountCandidates(NodeId peer) const
TxRequestTracker(bool deterministic=false)
Construct a TxRequestTracker.
static const uint256 ZERO
size_t Size() const
Count how many announcements are being tracked in total across all peers and transactions.
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
void RequestedTx(NodeId peer, const uint256 &txhash, std::chrono::microseconds expiry)
Marks a transaction as requested, with a specified expiry.
Index m_index
This tracker's main data structure. See SanityCheck() for the invariants that apply to it...
void PostGetRequestableSanityCheck(std::chrono::microseconds now) const
void PromoteCandidateReady(Iter< ByTxHash > it)
Convert a CANDIDATE_DELAYED announcement into a CANDIDATE_READY.
std::unordered_map< NodeId, PeerInfo > m_peerinfo
Map with this tracker's per-peer statistics.
void PostGetRequestableSanityCheck(std::chrono::microseconds now) const
Run a time-dependent internal consistency check (testing only).
void ChangeAndReselect(Iter< ByTxHash > it, State new_state)
Change the state of an announcement to something non-IsSelected().
size_t CountCandidates(NodeId peer) const
Count how many CANDIDATE announcements a peer has.
uint64_t ComputePriority(const uint256 &txhash, NodeId peer, bool preferred) const
Access to the internal priority computation (testing only)
void RequestedTx(NodeId peer, const uint256 &txhash, std::chrono::microseconds expiry)
void ForgetTxHash(const uint256 &txhash)
SequenceNumber m_current_sequence
The current sequence number.
uint64_t ComputePriority(const uint256 &txhash, NodeId peer, bool preferred) const
const std::unique_ptr< Impl > m_impl
A generic txid reference (txid or wtxid).
Actual implementation for TxRequestTracker's data structure.
void ForgetTxHash(const uint256 &txhash)
Deletes all announcements for a given txhash (both txid and wtxid ones).
Iter< Tag > Erase(Iter< Tag > it)
Wrapper around Index::...::erase that keeps m_peerinfo up to date.