Bitcoin Core  0.20.99
P2P Digital Currency
txrequest.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <txrequest.h>
6 
7 #include <crypto/siphash.h>
8 #include <net.h>
10 #include <random.h>
11 #include <uint256.h>
12 #include <util/memory.h>
13 
14 #include <boost/multi_index_container.hpp>
15 #include <boost/multi_index/ordered_index.hpp>
16 
17 #include <chrono>
18 #include <unordered_map>
19 #include <utility>
20 
21 #include <assert.h>
22 
23 namespace {
24 
39 enum class State : uint8_t {
41  CANDIDATE_DELAYED,
43  CANDIDATE_READY,
47  CANDIDATE_BEST,
49  REQUESTED,
51  COMPLETED,
52 };
53 
55 using SequenceNumber = uint64_t;
56 
58 struct Announcement {
60  const uint256 m_txhash;
62  std::chrono::microseconds m_time;
64  const NodeId m_peer;
66  const SequenceNumber m_sequence : 59;
68  const bool m_preferred : 1;
70  const bool m_is_wtxid : 1;
71 
75  uint8_t m_state : 3;
76 
78  State GetState() const { return static_cast<State>(m_state); }
79 
81  void SetState(State state) { m_state = static_cast<uint8_t>(state); }
82 
84  bool IsSelected() const
85  {
86  return GetState() == State::CANDIDATE_BEST || GetState() == State::REQUESTED;
87  }
88 
90  bool IsWaiting() const
91  {
92  return GetState() == State::REQUESTED || GetState() == State::CANDIDATE_DELAYED;
93  }
94 
96  bool IsSelectable() const
97  {
98  return GetState() == State::CANDIDATE_READY || GetState() == State::CANDIDATE_BEST;
99  }
100 
102  Announcement(const GenTxid& gtxid, NodeId peer, bool preferred, std::chrono::microseconds reqtime,
103  SequenceNumber sequence) :
104  m_txhash(gtxid.GetHash()), m_time(reqtime), m_peer(peer), m_sequence(sequence), m_preferred(preferred),
105  m_is_wtxid(gtxid.IsWtxid()), m_state(static_cast<uint8_t>(State::CANDIDATE_DELAYED)) {}
106 };
107 
109 using Priority = uint64_t;
110 
115 class PriorityComputer {
116  const uint64_t m_k0, m_k1;
117 public:
118  explicit PriorityComputer(bool deterministic) :
119  m_k0{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)},
120  m_k1{deterministic ? 0 : GetRand(0xFFFFFFFFFFFFFFFF)} {}
121 
122  Priority operator()(const uint256& txhash, NodeId peer, bool preferred) const
123  {
124  uint64_t low_bits = CSipHasher(m_k0, m_k1).Write(txhash.begin(), txhash.size()).Write(peer).Finalize() >> 1;
125  return low_bits | uint64_t{preferred} << 63;
126  }
127 
128  Priority operator()(const Announcement& ann) const
129  {
130  return operator()(ann.m_txhash, ann.m_peer, ann.m_preferred);
131  }
132 };
133 
134 // Definitions for the 3 indexes used in the main data structure.
135 //
136 // Each index has a By* type to identify it, a By*View data type to represent the view of announcement it is sorted
137 // by, and an By*ViewExtractor type to convert an announcement into the By*View type.
138 // See https://www.boost.org/doc/libs/1_58_0/libs/multi_index/doc/reference/key_extraction.html#key_extractors
139 // for more information about the key extraction concept.
140 
141 // The ByPeer index is sorted by (peer, state == CANDIDATE_BEST, txhash)
142 //
143 // Uses:
144 // * Looking up existing announcements by peer/txhash, by checking both (peer, false, txhash) and
145 // (peer, true, txhash).
146 // * Finding all CANDIDATE_BEST announcements for a given peer in GetRequestable.
147 struct ByPeer {};
148 using ByPeerView = std::tuple<NodeId, bool, const uint256&>;
149 struct ByPeerViewExtractor
150 {
151  using result_type = ByPeerView;
152  result_type operator()(const Announcement& ann) const
153  {
154  return ByPeerView{ann.m_peer, ann.GetState() == State::CANDIDATE_BEST, ann.m_txhash};
155  }
156 };
157 
158 // The ByTxHash index is sorted by (txhash, state, priority).
159 //
160 // Note: priority == 0 whenever state != CANDIDATE_READY.
161 //
162 // Uses:
163 // * Deleting all announcements with a given txhash in ForgetTxHash.
164 // * Finding the best CANDIDATE_READY to convert to CANDIDATE_BEST, when no other CANDIDATE_READY or REQUESTED
165 // announcement exists for that txhash.
166 // * Determining when no more non-COMPLETED announcements for a given txhash exist, so the COMPLETED ones can be
167 // deleted.
168 struct ByTxHash {};
169 using ByTxHashView = std::tuple<const uint256&, State, Priority>;
170 class ByTxHashViewExtractor {
171  const PriorityComputer& m_computer;
172 public:
173  ByTxHashViewExtractor(const PriorityComputer& computer) : m_computer(computer) {}
174  using result_type = ByTxHashView;
175  result_type operator()(const Announcement& ann) const
176  {
177  const Priority prio = (ann.GetState() == State::CANDIDATE_READY) ? m_computer(ann) : 0;
178  return ByTxHashView{ann.m_txhash, ann.GetState(), prio};
179  }
180 };
181 
182 enum class WaitState {
184  FUTURE_EVENT,
186  NO_EVENT,
188  PAST_EVENT,
189 };
190 
191 WaitState GetWaitState(const Announcement& ann)
192 {
193  if (ann.IsWaiting()) return WaitState::FUTURE_EVENT;
194  if (ann.IsSelectable()) return WaitState::PAST_EVENT;
195  return WaitState::NO_EVENT;
196 }
197 
198 // The ByTime index is sorted by (wait_state, time).
199 //
200 // All announcements with a timestamp in the future can be found by iterating the index forward from the beginning.
201 // All announcements with a timestamp in the past can be found by iterating the index backwards from the end.
202 //
203 // Uses:
204 // * Finding CANDIDATE_DELAYED announcements whose reqtime has passed, and REQUESTED announcements whose expiry has
205 // passed.
206 // * Finding CANDIDATE_READY/BEST announcements whose reqtime is in the future (when the clock time went backwards).
207 struct ByTime {};
208 using ByTimeView = std::pair<WaitState, std::chrono::microseconds>;
209 struct ByTimeViewExtractor
210 {
211  using result_type = ByTimeView;
212  result_type operator()(const Announcement& ann) const
213  {
214  return ByTimeView{GetWaitState(ann), ann.m_time};
215  }
216 };
217 
219 using Index = boost::multi_index_container<
220  Announcement,
221  boost::multi_index::indexed_by<
222  boost::multi_index::ordered_unique<boost::multi_index::tag<ByPeer>, ByPeerViewExtractor>,
223  boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTxHash>, ByTxHashViewExtractor>,
224  boost::multi_index::ordered_non_unique<boost::multi_index::tag<ByTime>, ByTimeViewExtractor>
225  >
226 >;
227 
229 template<typename Tag>
230 using Iter = typename Index::index<Tag>::type::iterator;
231 
233 struct PeerInfo {
234  size_t m_total = 0;
235  size_t m_completed = 0;
236  size_t m_requested = 0;
237 };
238 
240 struct TxHashInfo
241 {
243  size_t m_candidate_delayed = 0;
245  size_t m_candidate_ready = 0;
247  size_t m_candidate_best = 0;
249  size_t m_requested = 0;
251  Priority m_priority_candidate_best = std::numeric_limits<Priority>::max();
253  Priority m_priority_best_candidate_ready = std::numeric_limits<Priority>::min();
255  std::vector<NodeId> m_peers;
256 };
257 
259 bool operator==(const PeerInfo& a, const PeerInfo& b)
260 {
261  return std::tie(a.m_total, a.m_completed, a.m_requested) ==
262  std::tie(b.m_total, b.m_completed, b.m_requested);
263 };
264 
266 std::unordered_map<NodeId, PeerInfo> RecomputePeerInfo(const Index& index)
267 {
268  std::unordered_map<NodeId, PeerInfo> ret;
269  for (const Announcement& ann : index) {
270  PeerInfo& info = ret[ann.m_peer];
271  ++info.m_total;
272  info.m_requested += (ann.GetState() == State::REQUESTED);
273  info.m_completed += (ann.GetState() == State::COMPLETED);
274  }
275  return ret;
276 }
277 
279 std::map<uint256, TxHashInfo> ComputeTxHashInfo(const Index& index, const PriorityComputer& computer)
280 {
281  std::map<uint256, TxHashInfo> ret;
282  for (const Announcement& ann : index) {
283  TxHashInfo& info = ret[ann.m_txhash];
284  // Classify how many announcements of each state we have for this txhash.
285  info.m_candidate_delayed += (ann.GetState() == State::CANDIDATE_DELAYED);
286  info.m_candidate_ready += (ann.GetState() == State::CANDIDATE_READY);
287  info.m_candidate_best += (ann.GetState() == State::CANDIDATE_BEST);
288  info.m_requested += (ann.GetState() == State::REQUESTED);
289  // And track the priority of the best CANDIDATE_READY/CANDIDATE_BEST announcements.
290  if (ann.GetState() == State::CANDIDATE_BEST) {
291  info.m_priority_candidate_best = computer(ann);
292  }
293  if (ann.GetState() == State::CANDIDATE_READY) {
294  info.m_priority_best_candidate_ready = std::max(info.m_priority_best_candidate_ready, computer(ann));
295  }
296  // Also keep track of which peers this txhash has an announcement for (so we can detect duplicates).
297  info.m_peers.push_back(ann.m_peer);
298  }
299  return ret;
300 }
301 
302 GenTxid ToGenTxid(const Announcement& ann)
303 {
304  return {ann.m_is_wtxid, ann.m_txhash};
305 }
306 
307 } // namespace
308 
313  SequenceNumber m_current_sequence{0};
314 
316  const PriorityComputer m_computer;
317 
319  Index m_index;
320 
322  std::unordered_map<NodeId, PeerInfo> m_peerinfo;
323 
324 public:
325  void SanityCheck() const
326  {
327  // Recompute m_peerdata from m_index. This verifies the data in it as it should just be caching statistics
328  // on m_index. It also verifies the invariant that no PeerInfo announcements with m_total==0 exist.
329  assert(m_peerinfo == RecomputePeerInfo(m_index));
330 
331  // Calculate per-txhash statistics from m_index, and validate invariants.
332  for (auto& item : ComputeTxHashInfo(m_index, m_computer)) {
333  TxHashInfo& info = item.second;
334 
335  // Cannot have only COMPLETED peer (txhash should have been forgotten already)
336  assert(info.m_candidate_delayed + info.m_candidate_ready + info.m_candidate_best + info.m_requested > 0);
337 
338  // Can have at most 1 CANDIDATE_BEST/REQUESTED peer
339  assert(info.m_candidate_best + info.m_requested <= 1);
340 
341  // If there are any CANDIDATE_READY announcements, there must be exactly one CANDIDATE_BEST or REQUESTED
342  // announcement.
343  if (info.m_candidate_ready > 0) {
344  assert(info.m_candidate_best + info.m_requested == 1);
345  }
346 
347  // If there is both a CANDIDATE_READY and a CANDIDATE_BEST announcement, the CANDIDATE_BEST one must be
348  // at least as good (equal or higher priority) as the best CANDIDATE_READY.
349  if (info.m_candidate_ready && info.m_candidate_best) {
350  assert(info.m_priority_candidate_best >= info.m_priority_best_candidate_ready);
351  }
352 
353  // No txhash can have been announced by the same peer twice.
354  std::sort(info.m_peers.begin(), info.m_peers.end());
355  assert(std::adjacent_find(info.m_peers.begin(), info.m_peers.end()) == info.m_peers.end());
356  }
357  }
358 
359  void PostGetRequestableSanityCheck(std::chrono::microseconds now) const
360  {
361  for (const Announcement& ann : m_index) {
362  if (ann.IsWaiting()) {
363  // REQUESTED and CANDIDATE_DELAYED must have a time in the future (they should have been converted
364  // to COMPLETED/CANDIDATE_READY respectively).
365  assert(ann.m_time > now);
366  } else if (ann.IsSelectable()) {
367  // CANDIDATE_READY and CANDIDATE_BEST cannot have a time in the future (they should have remained
368  // CANDIDATE_DELAYED, or should have been converted back to it if time went backwards).
369  assert(ann.m_time <= now);
370  }
371  }
372  }
373 
374 private:
376  template<typename Tag>
377  Iter<Tag> Erase(Iter<Tag> it)
378  {
379  auto peerit = m_peerinfo.find(it->m_peer);
380  peerit->second.m_completed -= it->GetState() == State::COMPLETED;
381  peerit->second.m_requested -= it->GetState() == State::REQUESTED;
382  if (--peerit->second.m_total == 0) m_peerinfo.erase(peerit);
383  return m_index.get<Tag>().erase(it);
384  }
385 
387  template<typename Tag, typename Modifier>
388  void Modify(Iter<Tag> it, Modifier modifier)
389  {
390  auto peerit = m_peerinfo.find(it->m_peer);
391  peerit->second.m_completed -= it->GetState() == State::COMPLETED;
392  peerit->second.m_requested -= it->GetState() == State::REQUESTED;
393  m_index.get<Tag>().modify(it, std::move(modifier));
394  peerit->second.m_completed += it->GetState() == State::COMPLETED;
395  peerit->second.m_requested += it->GetState() == State::REQUESTED;
396  }
397 
401  void PromoteCandidateReady(Iter<ByTxHash> it)
402  {
403  assert(it != m_index.get<ByTxHash>().end());
404  assert(it->GetState() == State::CANDIDATE_DELAYED);
405  // Convert CANDIDATE_DELAYED to CANDIDATE_READY first.
406  Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); });
407  // The following code relies on the fact that the ByTxHash is sorted by txhash, and then by state (first
408  // _DELAYED, then _READY, then _BEST/REQUESTED). Within the _READY announcements, the best one (highest
409  // priority) comes last. Thus, if an existing _BEST exists for the same txhash that this announcement may
410  // be preferred over, it must immediately follow the newly created _READY.
411  auto it_next = std::next(it);
412  if (it_next == m_index.get<ByTxHash>().end() || it_next->m_txhash != it->m_txhash ||
413  it_next->GetState() == State::COMPLETED) {
414  // This is the new best CANDIDATE_READY, and there is no IsSelected() announcement for this txhash
415  // already.
416  Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
417  } else if (it_next->GetState() == State::CANDIDATE_BEST) {
418  Priority priority_old = m_computer(*it_next);
419  Priority priority_new = m_computer(*it);
420  if (priority_new > priority_old) {
421  // There is a CANDIDATE_BEST announcement already, but this one is better.
422  Modify<ByTxHash>(it_next, [](Announcement& ann){ ann.SetState(State::CANDIDATE_READY); });
423  Modify<ByTxHash>(it, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
424  }
425  }
426  }
427 
430  void ChangeAndReselect(Iter<ByTxHash> it, State new_state)
431  {
432  assert(new_state == State::COMPLETED || new_state == State::CANDIDATE_DELAYED);
433  assert(it != m_index.get<ByTxHash>().end());
434  if (it->IsSelected() && it != m_index.get<ByTxHash>().begin()) {
435  auto it_prev = std::prev(it);
436  // The next best CANDIDATE_READY, if any, immediately precedes the REQUESTED or CANDIDATE_BEST
437  // announcement in the ByTxHash index.
438  if (it_prev->m_txhash == it->m_txhash && it_prev->GetState() == State::CANDIDATE_READY) {
439  // If one such CANDIDATE_READY exists (for this txhash), convert it to CANDIDATE_BEST.
440  Modify<ByTxHash>(it_prev, [](Announcement& ann){ ann.SetState(State::CANDIDATE_BEST); });
441  }
442  }
443  Modify<ByTxHash>(it, [new_state](Announcement& ann){ ann.SetState(new_state); });
444  }
445 
447  bool IsOnlyNonCompleted(Iter<ByTxHash> it)
448  {
449  assert(it != m_index.get<ByTxHash>().end());
450  assert(it->GetState() != State::COMPLETED); // Not allowed to call this on COMPLETED announcements.
451 
452  // This announcement has a predecessor that belongs to the same txhash. Due to ordering, and the
453  // fact that 'it' is not COMPLETED, its predecessor cannot be COMPLETED here.
454  if (it != m_index.get<ByTxHash>().begin() && std::prev(it)->m_txhash == it->m_txhash) return false;
455 
456  // This announcement has a successor that belongs to the same txhash, and is not COMPLETED.
457  if (std::next(it) != m_index.get<ByTxHash>().end() && std::next(it)->m_txhash == it->m_txhash &&
458  std::next(it)->GetState() != State::COMPLETED) return false;
459 
460  return true;
461  }
462 
466  bool MakeCompleted(Iter<ByTxHash> it)
467  {
468  assert(it != m_index.get<ByTxHash>().end());
469 
470  // Nothing to be done if it's already COMPLETED.
471  if (it->GetState() == State::COMPLETED) return true;
472 
473  if (IsOnlyNonCompleted(it)) {
474  // This is the last non-COMPLETED announcement for this txhash. Delete all.
475  uint256 txhash = it->m_txhash;
476  do {
477  it = Erase<ByTxHash>(it);
478  } while (it != m_index.get<ByTxHash>().end() && it->m_txhash == txhash);
479  return false;
480  }
481 
482  // Mark the announcement COMPLETED, and select the next best announcement (the first CANDIDATE_READY) if
483  // needed.
484  ChangeAndReselect(it, State::COMPLETED);
485 
486  return true;
487  }
488 
493  void SetTimePoint(std::chrono::microseconds now, std::vector<std::pair<NodeId, GenTxid>>* expired)
494  {
495  if (expired) expired->clear();
496 
497  // Iterate over all CANDIDATE_DELAYED and REQUESTED from old to new, as long as they're in the past,
498  // and convert them to CANDIDATE_READY and COMPLETED respectively.
499  while (!m_index.empty()) {
500  auto it = m_index.get<ByTime>().begin();
501  if (it->GetState() == State::CANDIDATE_DELAYED && it->m_time <= now) {
502  PromoteCandidateReady(m_index.project<ByTxHash>(it));
503  } else if (it->GetState() == State::REQUESTED && it->m_time <= now) {
504  if (expired) expired->emplace_back(it->m_peer, ToGenTxid(*it));
505  MakeCompleted(m_index.project<ByTxHash>(it));
506  } else {
507  break;
508  }
509  }
510 
511  while (!m_index.empty()) {
512  // If time went backwards, we may need to demote CANDIDATE_BEST and CANDIDATE_READY announcements back
513  // to CANDIDATE_DELAYED. This is an unusual edge case, and unlikely to matter in production. However,
514  // it makes it much easier to specify and test TxRequestTracker::Impl's behaviour.
515  auto it = std::prev(m_index.get<ByTime>().end());
516  if (it->IsSelectable() && it->m_time > now) {
517  ChangeAndReselect(m_index.project<ByTxHash>(it), State::CANDIDATE_DELAYED);
518  } else {
519  break;
520  }
521  }
522  }
523 
524 public:
525  Impl(bool deterministic) :
526  m_computer(deterministic),
527  // Explicitly initialize m_index as we need to pass a reference to m_computer to ByTxHashViewExtractor.
528  m_index(boost::make_tuple(
529  boost::make_tuple(ByPeerViewExtractor(), std::less<ByPeerView>()),
530  boost::make_tuple(ByTxHashViewExtractor(m_computer), std::less<ByTxHashView>()),
531  boost::make_tuple(ByTimeViewExtractor(), std::less<ByTimeView>())
532  )) {}
533 
534  // Disable copying and assigning (a default copy won't work due the stateful ByTxHashViewExtractor).
535  Impl(const Impl&) = delete;
536  Impl& operator=(const Impl&) = delete;
537 
539  {
540  auto& index = m_index.get<ByPeer>();
541  auto it = index.lower_bound(ByPeerView{peer, false, uint256::ZERO});
542  while (it != index.end() && it->m_peer == peer) {
543  // Check what to continue with after this iteration. 'it' will be deleted in what follows, so we need to
544  // decide what to continue with afterwards. There are a number of cases to consider:
545  // - std::next(it) is end() or belongs to a different peer. In that case, this is the last iteration
546  // of the loop (denote this by setting it_next to end()).
547  // - 'it' is not the only non-COMPLETED announcement for its txhash. This means it will be deleted, but
548  // no other Announcement objects will be modified. Continue with std::next(it) if it belongs to the
549  // same peer, but decide this ahead of time (as 'it' may change position in what follows).
550  // - 'it' is the only non-COMPLETED announcement for its txhash. This means it will be deleted along
551  // with all other announcements for the same txhash - which may include std::next(it). However, other
552  // than 'it', no announcements for the same peer can be affected (due to (peer, txhash) uniqueness).
553  // In other words, the situation where std::next(it) is deleted can only occur if std::next(it)
554  // belongs to a different peer but the same txhash as 'it'. This is covered by the first bulletpoint
555  // already, and we'll have set it_next to end().
556  auto it_next = (std::next(it) == index.end() || std::next(it)->m_peer != peer) ? index.end() :
557  std::next(it);
558  // If the announcement isn't already COMPLETED, first make it COMPLETED (which will mark other
559  // CANDIDATEs as CANDIDATE_BEST, or delete all of a txhash's announcements if no non-COMPLETED ones are
560  // left).
561  if (MakeCompleted(m_index.project<ByTxHash>(it))) {
562  // Then actually delete the announcement (unless it was already deleted by MakeCompleted).
563  Erase<ByPeer>(it);
564  }
565  it = it_next;
566  }
567  }
568 
569  void ForgetTxHash(const uint256& txhash)
570  {
571  auto it = m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_DELAYED, 0});
572  while (it != m_index.get<ByTxHash>().end() && it->m_txhash == txhash) {
573  it = Erase<ByTxHash>(it);
574  }
575  }
576 
577  void ReceivedInv(NodeId peer, const GenTxid& gtxid, bool preferred,
578  std::chrono::microseconds reqtime)
579  {
580  // Bail out if we already have a CANDIDATE_BEST announcement for this (txhash, peer) combination. The case
581  // where there is a non-CANDIDATE_BEST announcement already will be caught by the uniqueness property of the
582  // ByPeer index when we try to emplace the new object below.
583  if (m_index.get<ByPeer>().count(ByPeerView{peer, true, gtxid.GetHash()})) return;
584 
585  // Try creating the announcement with CANDIDATE_DELAYED state (which will fail due to the uniqueness
586  // of the ByPeer index if a non-CANDIDATE_BEST announcement already exists with the same txhash and peer).
587  // Bail out in that case.
588  auto ret = m_index.get<ByPeer>().emplace(gtxid, peer, preferred, reqtime, m_current_sequence);
589  if (!ret.second) return;
590 
591  // Update accounting metadata.
592  ++m_peerinfo[peer].m_total;
593  ++m_current_sequence;
594  }
595 
597  std::vector<GenTxid> GetRequestable(NodeId peer, std::chrono::microseconds now,
598  std::vector<std::pair<NodeId, GenTxid>>* expired)
599  {
600  // Move time.
601  SetTimePoint(now, expired);
602 
603  // Find all CANDIDATE_BEST announcements for this peer.
604  std::vector<const Announcement*> selected;
605  auto it_peer = m_index.get<ByPeer>().lower_bound(ByPeerView{peer, true, uint256::ZERO});
606  while (it_peer != m_index.get<ByPeer>().end() && it_peer->m_peer == peer &&
607  it_peer->GetState() == State::CANDIDATE_BEST) {
608  selected.emplace_back(&*it_peer);
609  ++it_peer;
610  }
611 
612  // Sort by sequence number.
613  std::sort(selected.begin(), selected.end(), [](const Announcement* a, const Announcement* b) {
614  return a->m_sequence < b->m_sequence;
615  });
616 
617  // Convert to GenTxid and return.
618  std::vector<GenTxid> ret;
619  ret.reserve(selected.size());
620  std::transform(selected.begin(), selected.end(), std::back_inserter(ret), [](const Announcement* ann) {
621  return ToGenTxid(*ann);
622  });
623  return ret;
624  }
625 
626  void RequestedTx(NodeId peer, const uint256& txhash, std::chrono::microseconds expiry)
627  {
628  auto it = m_index.get<ByPeer>().find(ByPeerView{peer, true, txhash});
629  if (it == m_index.get<ByPeer>().end()) {
630  // There is no CANDIDATE_BEST announcement, look for a _READY or _DELAYED instead. If the caller only
631  // ever invokes RequestedTx with the values returned by GetRequestable, and no other non-const functions
632  // other than ForgetTxHash and GetRequestable in between, this branch will never execute (as txhashes
633  // returned by GetRequestable always correspond to CANDIDATE_BEST announcements).
634 
635  it = m_index.get<ByPeer>().find(ByPeerView{peer, false, txhash});
636  if (it == m_index.get<ByPeer>().end() || (it->GetState() != State::CANDIDATE_DELAYED &&
637  it->GetState() != State::CANDIDATE_READY)) {
638  // There is no CANDIDATE announcement tracked for this peer, so we have nothing to do. Either this
639  // txhash wasn't tracked at all (and the caller should have called ReceivedInv), or it was already
640  // requested and/or completed for other reasons and this is just a superfluous RequestedTx call.
641  return;
642  }
643 
644  // Look for an existing CANDIDATE_BEST or REQUESTED with the same txhash. We only need to do this if the
645  // found announcement had a different state than CANDIDATE_BEST. If it did, invariants guarantee that no
646  // other CANDIDATE_BEST or REQUESTED can exist.
647  auto it_old = m_index.get<ByTxHash>().lower_bound(ByTxHashView{txhash, State::CANDIDATE_BEST, 0});
648  if (it_old != m_index.get<ByTxHash>().end() && it_old->m_txhash == txhash) {
649  if (it_old->GetState() == State::CANDIDATE_BEST) {
650  // The data structure's invariants require that there can be at most one CANDIDATE_BEST or one
651  // REQUESTED announcement per txhash (but not both simultaneously), so we have to convert any
652  // existing CANDIDATE_BEST to another CANDIDATE_* when constructing another REQUESTED.
653  // It doesn't matter whether we pick CANDIDATE_READY or _DELAYED here, as SetTimePoint()
654  // will correct it at GetRequestable() time. If time only goes forward, it will always be
655  // _READY, so pick that to avoid extra work in SetTimePoint().
656  Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::CANDIDATE_READY); });
657  } else if (it_old->GetState() == State::REQUESTED) {
658  // As we're no longer waiting for a response to the previous REQUESTED announcement, convert it
659  // to COMPLETED. This also helps guaranteeing progress.
660  Modify<ByTxHash>(it_old, [](Announcement& ann) { ann.SetState(State::COMPLETED); });
661  }
662  }
663  }
664 
665  Modify<ByPeer>(it, [expiry](Announcement& ann) {
666  ann.SetState(State::REQUESTED);
667  ann.m_time = expiry;
668  });
669  }
670 
671  void ReceivedResponse(NodeId peer, const uint256& txhash)
672  {
673  // We need to search the ByPeer index for both (peer, false, txhash) and (peer, true, txhash).
674  auto it = m_index.get<ByPeer>().find(ByPeerView{peer, false, txhash});
675  if (it == m_index.get<ByPeer>().end()) {
676  it = m_index.get<ByPeer>().find(ByPeerView{peer, true, txhash});
677  }
678  if (it != m_index.get<ByPeer>().end()) MakeCompleted(m_index.project<ByTxHash>(it));
679  }
680 
681  size_t CountInFlight(NodeId peer) const
682  {
683  auto it = m_peerinfo.find(peer);
684  if (it != m_peerinfo.end()) return it->second.m_requested;
685  return 0;
686  }
687 
688  size_t CountCandidates(NodeId peer) const
689  {
690  auto it = m_peerinfo.find(peer);
691  if (it != m_peerinfo.end()) return it->second.m_total - it->second.m_requested - it->second.m_completed;
692  return 0;
693  }
694 
695  size_t Count(NodeId peer) const
696  {
697  auto it = m_peerinfo.find(peer);
698  if (it != m_peerinfo.end()) return it->second.m_total;
699  return 0;
700  }
701 
703  size_t Size() const { return m_index.size(); }
704 
705  uint64_t ComputePriority(const uint256& txhash, NodeId peer, bool preferred) const
706  {
707  // Return Priority as a uint64_t as Priority is internal.
708  return uint64_t{m_computer(txhash, peer, preferred)};
709  }
710 
711 };
712 
714  m_impl{MakeUnique<TxRequestTracker::Impl>(deterministic)} {}
715 
717 
718 void TxRequestTracker::ForgetTxHash(const uint256& txhash) { m_impl->ForgetTxHash(txhash); }
719 void TxRequestTracker::DisconnectedPeer(NodeId peer) { m_impl->DisconnectedPeer(peer); }
720 size_t TxRequestTracker::CountInFlight(NodeId peer) const { return m_impl->CountInFlight(peer); }
721 size_t TxRequestTracker::CountCandidates(NodeId peer) const { return m_impl->CountCandidates(peer); }
722 size_t TxRequestTracker::Count(NodeId peer) const { return m_impl->Count(peer); }
723 size_t TxRequestTracker::Size() const { return m_impl->Size(); }
724 void TxRequestTracker::SanityCheck() const { m_impl->SanityCheck(); }
725 
726 void TxRequestTracker::PostGetRequestableSanityCheck(std::chrono::microseconds now) const
727 {
728  m_impl->PostGetRequestableSanityCheck(now);
729 }
730 
731 void TxRequestTracker::ReceivedInv(NodeId peer, const GenTxid& gtxid, bool preferred,
732  std::chrono::microseconds reqtime)
733 {
734  m_impl->ReceivedInv(peer, gtxid, preferred, reqtime);
735 }
736 
737 void TxRequestTracker::RequestedTx(NodeId peer, const uint256& txhash, std::chrono::microseconds expiry)
738 {
739  m_impl->RequestedTx(peer, txhash, expiry);
740 }
741 
743 {
744  m_impl->ReceivedResponse(peer, txhash);
745 }
746 
747 std::vector<GenTxid> TxRequestTracker::GetRequestable(NodeId peer, std::chrono::microseconds now,
748  std::vector<std::pair<NodeId, GenTxid>>* expired)
749 {
750  return m_impl->GetRequestable(peer, now, expired);
751 }
752 
753 uint64_t TxRequestTracker::ComputePriority(const uint256& txhash, NodeId peer, bool preferred) const
754 {
755  return m_impl->ComputePriority(txhash, peer, preferred);
756 }
void ReceivedResponse(NodeId peer, const uint256 &txhash)
Converts a CANDIDATE or REQUESTED announcement to a COMPLETED one.
Definition: txrequest.cpp:742
peer m_getdata_requests erase(peer.m_getdata_requests.begin(), it)
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:592
std::deque< CInv >::iterator it
void ReceivedResponse(NodeId peer, const uint256 &txhash)
Definition: txrequest.cpp:671
const std::chrono::seconds now
size_t Count(NodeId peer) const
Count how many announcements a peer has (REQUESTED, CANDIDATE, and COMPLETED combined).
Definition: txrequest.cpp:722
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 ...
Definition: siphash.cpp:28
Definition: init.h:17
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:581
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.
Definition: txrequest.cpp:747
void ReceivedInv(NodeId peer, const GenTxid &gtxid, bool preferred, std::chrono::microseconds reqtime)
Adds a new CANDIDATE announcement.
Definition: txrequest.cpp:731
size_t CountInFlight(NodeId peer) const
Count how many REQUESTED announcements a peer has.
Definition: txrequest.cpp:720
bool MakeCompleted(Iter< ByTxHash > it)
Convert any announcement to a COMPLETED one.
Definition: txrequest.cpp:466
void SetTimePoint(std::chrono::microseconds now, std::vector< std::pair< NodeId, GenTxid >> *expired)
Make the data structure consistent with a given point in time:
Definition: txrequest.cpp:493
Impl(bool deterministic)
Definition: txrequest.cpp:525
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.
Definition: txrequest.cpp:597
bool IsOnlyNonCompleted(Iter< ByTxHash > it)
Check if &#39;it&#39; is the only announcement for a given txhash that isn&#39;t COMPLETED.
Definition: txrequest.cpp:447
void ReceivedInv(NodeId peer, const GenTxid &gtxid, bool preferred, std::chrono::microseconds reqtime)
Definition: txrequest.cpp:577
const uint256 & GetHash() const
Definition: transaction.h:407
const PriorityComputer m_computer
This tracker&#39;s priority computer.
Definition: txrequest.cpp:316
void SanityCheck() const
Definition: txrequest.cpp:325
size_t Count(NodeId peer) const
Definition: txrequest.cpp:695
unsigned char * begin()
Definition: uint256.h:58
State
The various states a (txhash,peer) pair can be in.
Definition: txrequest.cpp:39
void Modify(Iter< Tag > it, Modifier modifier)
Wrapper around Index::...::modify that keeps m_peerinfo up to date.
Definition: txrequest.cpp:388
size_t Size() const
Count how many announcements are being tracked in total across all peers and transaction hashes...
Definition: txrequest.cpp:723
void DisconnectedPeer(NodeId peer)
Definition: txrequest.cpp:538
size_t CountInFlight(NodeId peer) const
Definition: txrequest.cpp:681
void DisconnectedPeer(NodeId peer)
Deletes all announcements for a given peer.
Definition: txrequest.cpp:719
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:235
void SanityCheck() const
Run internal consistency check (testing only).
Definition: txrequest.cpp:724
size_t CountCandidates(NodeId peer) const
Definition: txrequest.cpp:688
TxRequestTracker(bool deterministic=false)
Construct a TxRequestTracker.
Definition: txrequest.cpp:713
static const uint256 ZERO
Definition: uint256.h:129
size_t Size() const
Count how many announcements are being tracked in total across all peers and transactions.
Definition: txrequest.cpp:703
int64_t NodeId
Definition: net.h:92
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
void RequestedTx(NodeId peer, const uint256 &txhash, std::chrono::microseconds expiry)
Marks a transaction as requested, with a specified expiry.
Definition: txrequest.cpp:737
unsigned int size() const
Definition: uint256.h:78
Index m_index
This tracker&#39;s main data structure. See SanityCheck() for the invariants that apply to it...
Definition: txrequest.cpp:319
void PostGetRequestableSanityCheck(std::chrono::microseconds now) const
Definition: txrequest.cpp:359
bool IsWtxid() const
Definition: transaction.h:406
WaitState
Definition: txrequest.cpp:182
void PromoteCandidateReady(Iter< ByTxHash > it)
Convert a CANDIDATE_DELAYED announcement into a CANDIDATE_READY.
Definition: txrequest.cpp:401
std::unordered_map< NodeId, PeerInfo > m_peerinfo
Map with this tracker&#39;s per-peer statistics.
Definition: txrequest.cpp:322
256-bit opaque blob.
Definition: uint256.h:124
void PostGetRequestableSanityCheck(std::chrono::microseconds now) const
Run a time-dependent internal consistency check (testing only).
Definition: txrequest.cpp:726
void ChangeAndReselect(Iter< ByTxHash > it, State new_state)
Change the state of an announcement to something non-IsSelected().
Definition: txrequest.cpp:430
size_t CountCandidates(NodeId peer) const
Count how many CANDIDATE announcements a peer has.
Definition: txrequest.cpp:721
SipHash-2-4.
Definition: siphash.h:13
uint64_t ComputePriority(const uint256 &txhash, NodeId peer, bool preferred) const
Access to the internal priority computation (testing only)
Definition: txrequest.cpp:753
void RequestedTx(NodeId peer, const uint256 &txhash, std::chrono::microseconds expiry)
Definition: txrequest.cpp:626
void ForgetTxHash(const uint256 &txhash)
Definition: txrequest.cpp:569
uint64_t ComputePriority(const uint256 &txhash, NodeId peer, bool preferred) const
Definition: txrequest.cpp:705
const std::unique_ptr< Impl > m_impl
Definition: txrequest.h:98
A generic txid reference (txid or wtxid).
Definition: transaction.h:400
Actual implementation for TxRequestTracker&#39;s data structure.
Definition: txrequest.cpp:310
void ForgetTxHash(const uint256 &txhash)
Deletes all announcements for a given txhash (both txid and wtxid ones).
Definition: txrequest.cpp:718
Iter< Tag > Erase(Iter< Tag > it)
Wrapper around Index::...erase that keeps m_peerinfo up to date.
Definition: txrequest.cpp:377