11#include <boost/multi_index/ordered_index.hpp>
12#include <boost/multi_index_container.hpp>
17#include <unordered_map>
42enum class State : uint8_t {
63using SequenceNumber = uint64_t;
76 std::chrono::microseconds m_time;
80 const SequenceNumber m_sequence : 60;
82 const bool m_preferred : 1;
85 State m_state : 3 {State::CANDIDATE_DELAYED};
86 State GetState()
const {
return m_state; }
87 void SetState(State state) { m_state = state; }
93 bool IsSelected()
const {
94 return GetState() == State::CANDIDATE_BEST ||
95 GetState() == State::REQUESTED;
99 bool IsWaiting()
const {
100 return GetState() == State::REQUESTED ||
101 GetState() == State::CANDIDATE_DELAYED;
108 bool IsSelectable()
const {
109 return GetState() == State::CANDIDATE_READY ||
110 GetState() == State::CANDIDATE_BEST;
117 Announcement(
const uint256 &invid,
NodeId peer,
bool preferred,
118 std::chrono::microseconds reqtime, SequenceNumber sequence)
119 : m_invid(invid), m_time(reqtime), m_peer(peer), m_sequence(sequence),
120 m_preferred(preferred) {}
124using Priority = uint64_t;
131class PriorityComputer {
132 const uint64_t m_k0, m_k1;
135 explicit PriorityComputer(
bool deterministic)
140 bool preferred)
const {
143 return low_bits | uint64_t{preferred} << 63;
146 Priority operator()(
const Announcement &ann)
const {
147 return operator()(ann.m_invid, ann.m_peer, ann.m_preferred);
167using ByPeerView = std::tuple<NodeId, bool, const uint256 &>;
168struct ByPeerViewExtractor {
169 using result_type = ByPeerView;
170 result_type operator()(
const Announcement &ann)
const {
171 return ByPeerView{ann.m_peer, ann.GetState() == State::CANDIDATE_BEST,
187using ByInvIdView = std::tuple<const uint256 &, State, Priority>;
188class ByInvIdViewExtractor {
189 const PriorityComputer &m_computer;
192 explicit ByInvIdViewExtractor(
const PriorityComputer &computer)
193 : m_computer(computer) {}
194 using result_type = ByInvIdView;
195 result_type operator()(
const Announcement &ann)
const {
196 const Priority prio =
197 (ann.GetState() == State::CANDIDATE_READY) ? m_computer(ann) : 0;
198 return ByInvIdView{ann.m_invid, ann.GetState(), prio};
202enum class WaitState {
213WaitState GetWaitState(
const Announcement &ann) {
214 if (ann.IsWaiting()) {
215 return WaitState::FUTURE_EVENT;
217 if (ann.IsSelectable()) {
218 return WaitState::PAST_EVENT;
220 return WaitState::NO_EVENT;
235using ByTimeView = std::pair<WaitState, std::chrono::microseconds>;
236struct ByTimeViewExtractor {
237 using result_type = ByTimeView;
238 result_type operator()(
const Announcement &ann)
const {
239 return ByTimeView{GetWaitState(ann), ann.m_time};
247using Index = boost::multi_index_container<
249 boost::multi_index::indexed_by<
250 boost::multi_index::ordered_unique<boost::multi_index::tag<ByPeer>,
251 ByPeerViewExtractor>,
252 boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByInvId>,
253 ByInvIdViewExtractor>,
254 boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTime>,
255 ByTimeViewExtractor>>>;
258template <
typename Tag>
using Iter =
typename Index::index<Tag>::type::iterator;
265 size_t m_completed = 0;
267 size_t m_requested = 0;
273 size_t m_candidate_delayed = 0;
275 size_t m_candidate_ready = 0;
277 size_t m_candidate_best = 0;
280 size_t m_requested = 0;
283 Priority m_priority_candidate_best = std::numeric_limits<Priority>::max();
286 Priority m_priority_best_candidate_ready =
287 std::numeric_limits<Priority>::min();
289 std::vector<NodeId> m_peers;
293bool operator==(
const PeerInfo &a,
const PeerInfo &b) {
294 return std::tie(a.m_total, a.m_completed, a.m_requested) ==
295 std::tie(b.m_total, b.m_completed, b.m_requested);
301std::unordered_map<NodeId, PeerInfo> RecomputePeerInfo(
const Index &index) {
302 std::unordered_map<NodeId, PeerInfo> ret;
303 for (
const Announcement &ann : index) {
304 PeerInfo &info = ret[ann.m_peer];
306 info.m_requested += (ann.GetState() == State::REQUESTED);
307 info.m_completed += (ann.GetState() == State::COMPLETED);
313std::map<uint256, InvIdInfo>
314ComputeInvIdInfo(
const Index &index,
const PriorityComputer &computer) {
315 std::map<uint256, InvIdInfo> ret;
316 for (
const Announcement &ann : index) {
317 InvIdInfo &info = ret[ann.m_invid];
319 info.m_candidate_delayed +=
320 (ann.GetState() == State::CANDIDATE_DELAYED);
321 info.m_candidate_ready += (ann.GetState() == State::CANDIDATE_READY);
322 info.m_candidate_best += (ann.GetState() == State::CANDIDATE_BEST);
323 info.m_requested += (ann.GetState() == State::REQUESTED);
326 if (ann.GetState() == State::CANDIDATE_BEST) {
327 info.m_priority_candidate_best = computer(ann);
329 if (ann.GetState() == State::CANDIDATE_READY) {
330 info.m_priority_best_candidate_ready =
331 std::max(info.m_priority_best_candidate_ready, computer(ann));
335 info.m_peers.push_back(ann.m_peer);
368 InvIdInfo &info = item.second;
372 assert(info.m_candidate_delayed + info.m_candidate_ready +
373 info.m_candidate_best + info.m_requested >
377 assert(info.m_candidate_best + info.m_requested <= 1);
381 if (info.m_candidate_ready > 0) {
382 assert(info.m_candidate_best + info.m_requested == 1);
388 if (info.m_candidate_ready && info.m_candidate_best) {
389 assert(info.m_priority_candidate_best >=
390 info.m_priority_best_candidate_ready);
394 std::sort(info.m_peers.begin(), info.m_peers.end());
396 std::adjacent_find(info.m_peers.begin(), info.m_peers.end()) ==
402 std::chrono::microseconds now)
const override {
403 for (
const Announcement &ann :
m_index) {
404 if (ann.IsWaiting()) {
409 }
else if (ann.IsSelectable()) {
414 assert(ann.m_time <= now);
421 template <
typename Tag> Iter<Tag>
Erase(Iter<Tag> it) {
423 peerit->second.m_completed -= it->GetState() == State::COMPLETED;
424 peerit->second.m_requested -= it->GetState() == State::REQUESTED;
425 if (--peerit->second.m_total == 0) {
428 return m_index.get<Tag>().erase(it);
432 template <
typename Tag,
typename Modifier>
433 void Modify(Iter<Tag> it, Modifier modifier) {
435 peerit->second.m_completed -= it->GetState() == State::COMPLETED;
436 peerit->second.m_requested -= it->GetState() == State::REQUESTED;
437 m_index.get<Tag>().modify(it, std::move(modifier));
438 peerit->second.m_completed += it->GetState() == State::COMPLETED;
439 peerit->second.m_requested += it->GetState() == State::REQUESTED;
448 assert(it->GetState() == State::CANDIDATE_DELAYED);
450 Modify<ByInvId>(it, [](Announcement &ann) {
451 ann.SetState(State::CANDIDATE_READY);
459 auto it_next = std::next(it);
460 if (it_next ==
m_index.get<ByInvId>().end() ||
461 it_next->m_invid != it->m_invid ||
462 it_next->GetState() == State::COMPLETED) {
465 Modify<ByInvId>(it, [](Announcement &ann) {
466 ann.SetState(State::CANDIDATE_BEST);
468 }
else if (it_next->GetState() == State::CANDIDATE_BEST) {
471 if (priority_new > priority_old) {
474 Modify<ByInvId>(it_next, [](Announcement &ann) {
475 ann.SetState(State::CANDIDATE_READY);
477 Modify<ByInvId>(it, [](Announcement &ann) {
478 ann.SetState(State::CANDIDATE_BEST);
488 assert(new_state == State::COMPLETED ||
489 new_state == State::CANDIDATE_DELAYED);
491 if (it->IsSelected() && it !=
m_index.get<ByInvId>().begin()) {
492 auto it_prev = std::prev(it);
495 if (it_prev->m_invid == it->m_invid &&
496 it_prev->GetState() == State::CANDIDATE_READY) {
499 Modify<ByInvId>(it_prev, [](Announcement &ann) {
500 ann.SetState(State::CANDIDATE_BEST);
505 it, [new_state](Announcement &ann) { ann.SetState(new_state); });
513 assert(it->GetState() != State::COMPLETED);
518 if (it !=
m_index.get<ByInvId>().begin() &&
519 std::prev(it)->m_invid == it->m_invid) {
525 if (std::next(it) !=
m_index.get<ByInvId>().end() &&
526 std::next(it)->m_invid == it->m_invid &&
527 std::next(it)->GetState() != State::COMPLETED) {
545 if (it->GetState() == State::COMPLETED) {
554 it = Erase<ByInvId>(it);
555 }
while (it !=
m_index.get<ByInvId>().end() &&
556 it->m_invid == invid);
581 auto it =
m_index.get<ByTime>().begin();
582 if (it->GetState() == State::CANDIDATE_DELAYED &&
585 }
else if (it->GetState() == State::REQUESTED &&
587 emplaceExpired(it->m_peer, it->m_invid);
600 auto it = std::prev(
m_index.get<ByTime>().end());
601 if (it->IsSelectable() && it->m_time > now) {
603 State::CANDIDATE_DELAYED);
616 boost::make_tuple(ByPeerViewExtractor(),
std::less<ByPeerView>()),
617 boost::make_tuple(ByInvIdViewExtractor(
m_computer),
618 std::less<ByInvIdView>()),
619 boost::make_tuple(ByTimeViewExtractor(),
620 std::less<ByTimeView>()))) {}
630 auto &index =
m_index.get<ByPeer>();
633 while (it != index.end() && it->m_peer == peer) {
655 (std::next(it) == index.end() || std::next(it)->m_peer != peer)
672 auto it =
m_index.get<ByInvId>().lower_bound(
673 ByInvIdView{invid, State::CANDIDATE_DELAYED, 0});
674 while (it !=
m_index.get<ByInvId>().end() && it->m_invid == invid) {
675 it = Erase<ByInvId>(it);
680 std::chrono::microseconds reqtime)
override {
686 if (
m_index.get<ByPeer>().count(ByPeerView{peer, true, invid})) {
694 auto ret =
m_index.get<ByPeer>().emplace(invid, peer, preferred,
714 std::vector<const Announcement *> selected;
715 auto it_peer =
m_index.get<ByPeer>().lower_bound(
717 while (it_peer !=
m_index.get<ByPeer>().end() &&
718 it_peer->m_peer == peer &&
719 it_peer->GetState() == State::CANDIDATE_BEST) {
720 selected.emplace_back(&*it_peer);
725 std::sort(selected.begin(), selected.end(),
726 [](
const Announcement *a,
const Announcement *b) {
727 return a->m_sequence < b->m_sequence;
731 std::vector<uint256> ret;
732 ret.reserve(selected.size());
733 std::transform(selected.begin(), selected.end(),
734 std::back_inserter(ret),
735 [](
const Announcement *ann) { return ann->m_invid; });
740 std::chrono::microseconds expiry)
override {
741 auto it =
m_index.get<ByPeer>().find(ByPeerView{peer,
true, invid});
742 if (it ==
m_index.get<ByPeer>().end()) {
751 it =
m_index.get<ByPeer>().find(ByPeerView{peer,
false, invid});
752 if (it ==
m_index.get<ByPeer>().end() ||
753 (it->GetState() != State::CANDIDATE_DELAYED &&
754 it->GetState() != State::CANDIDATE_READY)) {
767 auto it_old =
m_index.get<ByInvId>().lower_bound(
768 ByInvIdView{invid, State::CANDIDATE_BEST, 0});
769 if (it_old !=
m_index.get<ByInvId>().end() &&
770 it_old->m_invid == invid) {
771 if (it_old->GetState() == State::CANDIDATE_BEST) {
782 Modify<ByInvId>(it_old, [](Announcement &ann) {
783 ann.SetState(State::CANDIDATE_READY);
785 }
else if (it_old->GetState() == State::REQUESTED) {
789 Modify<ByInvId>(it_old, [](Announcement &ann) {
790 ann.SetState(State::COMPLETED);
796 Modify<ByPeer>(it, [expiry](Announcement &ann) {
797 ann.SetState(State::REQUESTED);
805 auto it =
m_index.get<ByPeer>().find(ByPeerView{peer,
false, invid});
806 if (it ==
m_index.get<ByPeer>().end()) {
807 it =
m_index.get<ByPeer>().find(ByPeerView{peer,
true, invid});
809 if (it !=
m_index.get<ByPeer>().end()) {
817 return it->second.m_requested;
825 return it->second.m_total - it->second.m_requested -
826 it->second.m_completed;
834 return it->second.m_total;
844 bool preferred)
const override {
846 return uint64_t{
m_computer(invid, peer, preferred)};
850std::unique_ptr<InvRequestTrackerImplInterface>
852 return std::make_unique<InvRequestTrackerImpl>(deterministic);
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
Actual implementation for InvRequestTracker's data structure.
InvRequestTrackerImpl(const InvRequestTrackerImpl &)=delete
size_t Size() const override
Count how many announcements are being tracked in total across all peers and transactions.
void ReceivedInv(NodeId peer, const uint256 &invid, bool preferred, std::chrono::microseconds reqtime) override
void Modify(Iter< Tag > it, Modifier modifier)
Wrapper around Index::...::modify that keeps m_peerinfo up to date.
SequenceNumber m_current_sequence
The current sequence number.
void SanityCheck() const override
uint64_t ComputePriority(const uint256 &invid, NodeId peer, bool preferred) const override
size_t CountInFlight(NodeId peer) const override
Iter< Tag > Erase(Iter< Tag > it)
Wrapper around Index::...::erase that keeps m_peerinfo up to date.
std::unordered_map< NodeId, PeerInfo > m_peerinfo
Map with this tracker's per-peer statistics.
void PostGetRequestableSanityCheck(std::chrono::microseconds now) const override
InvRequestTrackerImpl(bool deterministic)
void ForgetInvId(const uint256 &invid) override
bool MakeCompleted(Iter< ByInvId > it)
Convert any announcement to a COMPLETED one.
void SetTimePoint(std::chrono::microseconds now, ClearExpiredFun clearExpired, EmplaceExpiredFun emplaceExpired)
Make the data structure consistent with a given point in time:
InvRequestTrackerImpl & operator=(const InvRequestTrackerImpl &)=delete
bool IsOnlyNonCompleted(Iter< ByInvId > it)
Check if 'it' is the only announcement for a given invid that isn't COMPLETED.
void ReceivedResponse(NodeId peer, const uint256 &invid) override
~InvRequestTrackerImpl()=default
void ChangeAndReselect(Iter< ByInvId > it, State new_state)
Change the state of an announcement to something non-IsSelected().
size_t CountCandidates(NodeId peer) const override
void PromoteCandidateReady(Iter< ByInvId > it)
Convert a CANDIDATE_DELAYED announcement into a CANDIDATE_READY.
size_t Count(NodeId peer) const override
const PriorityComputer m_computer
This tracker's priority computer.
std::vector< uint256 > GetRequestable(NodeId peer, std::chrono::microseconds now, ClearExpiredFun clearExpired, EmplaceExpiredFun emplaceExpired) override
Find the InvIds to request now from peer.
Index m_index
This tracker's main data structure.
void RequestedData(NodeId peer, const uint256 &invid, std::chrono::microseconds expiry) override
void DisconnectedPeer(NodeId peer) override
Data structure to keep track of, and schedule, inventory downloads from peers.
static std::unique_ptr< InvRequestTrackerImplInterface > BuildImpl(bool deterministic)
const std::function< void()> & ClearExpiredFun
const std::function< void(const NodeId &, const uint256 &)> & EmplaceExpiredFun
static const uint256 ZERO
Implement std::hash so RCUPtr can be used as a key for maps or sets.
bool operator==(const CNetAddr &a, const CNetAddr &b)