Bitcoin ABC  0.26.3
P2P Digital Currency
peermanager.h
Go to the documentation of this file.
1 // Copyright (c) 2020 The Bitcoin 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 #ifndef BITCOIN_AVALANCHE_PEERMANAGER_H
6 #define BITCOIN_AVALANCHE_PEERMANAGER_H
7 
8 #include <avalanche/node.h>
9 #include <avalanche/proof.h>
10 #include <avalanche/proofpool.h>
12 #include <bloom.h>
13 #include <coins.h>
14 #include <consensus/validation.h>
15 #include <pubkey.h>
16 #include <radix.h>
17 #include <util/hasher.h>
18 #include <util/time.h>
19 
20 #include <boost/multi_index/composite_key.hpp>
21 #include <boost/multi_index/hashed_index.hpp>
22 #include <boost/multi_index/mem_fun.hpp>
23 #include <boost/multi_index/member.hpp>
24 #include <boost/multi_index/ordered_index.hpp>
25 #include <boost/multi_index_container.hpp>
26 
27 #include <atomic>
28 #include <chrono>
29 #include <cstdint>
30 #include <memory>
31 #include <vector>
32 
33 class ChainstateManager;
34 class CScheduler;
35 
36 namespace avalanche {
37 
44 static constexpr uint32_t AVALANCHE_MAX_IMMATURE_PROOFS = 4000;
45 
46 class Delegation;
47 
48 namespace {
49  struct TestPeerManager;
50 }
51 
52 struct Slot {
53 private:
54  uint64_t start;
55  uint32_t score;
57 
58 public:
59  Slot(uint64_t startIn, uint32_t scoreIn, PeerId peeridIn)
60  : start(startIn), score(scoreIn), peerid(peeridIn) {}
61 
62  Slot withStart(uint64_t startIn) const {
63  return Slot(startIn, score, peerid);
64  }
65  Slot withScore(uint64_t scoreIn) const {
66  return Slot(start, scoreIn, peerid);
67  }
68  Slot withPeerId(PeerId peeridIn) const {
69  return Slot(start, score, peeridIn);
70  }
71 
72  uint64_t getStart() const { return start; }
73  uint64_t getStop() const { return start + score; }
74  uint32_t getScore() const { return score; }
75  PeerId getPeerId() const { return peerid; }
76 
77  bool contains(uint64_t slot) const {
78  return getStart() <= slot && slot < getStop();
79  }
80  bool precedes(uint64_t slot) const { return slot >= getStop(); }
81  bool follows(uint64_t slot) const { return getStart() > slot; }
82 };
83 
84 struct Peer {
86  uint32_t index = -1;
87  uint32_t node_count = 0;
88 
90  bool hasFinalized = false;
91 
92  // The network stack uses timestamp in seconds, so we oblige.
93  std::chrono::seconds registration_time;
94  std::chrono::seconds nextPossibleConflictTime;
95 
96  double availabilityScore = 0.0;
97 
102  static constexpr auto DANGLING_TIMEOUT = 15min;
103 
104  Peer(PeerId peerid_, ProofRef proof_,
105  std::chrono::seconds nextPossibleConflictTime_)
106  : peerid(peerid_), proof(std::move(proof_)),
107  registration_time(GetTime<std::chrono::seconds>()),
108  nextPossibleConflictTime(std::move(nextPossibleConflictTime_)) {}
109 
110  const ProofId &getProofId() const { return proof->getId(); }
111  uint32_t getScore() const { return proof->getScore(); }
112 };
113 
114 struct proof_index {
116  result_type operator()(const Peer &p) const { return p.proof->getId(); }
117 };
118 
119 struct score_index {
120  using result_type = uint32_t;
121  result_type operator()(const Peer &p) const { return p.getScore(); }
122 };
123 
125 
126 struct PendingNode {
129 
130  PendingNode(ProofId proofid_, NodeId nodeid_)
131  : proofid(proofid_), nodeid(nodeid_){};
132 };
133 
134 struct by_proofid;
135 struct by_nodeid;
136 struct by_score;
137 
139  NONE = 0,
141  IMMATURE,
142  INVALID,
143  CONFLICTING,
144  REJECTED,
146  DANGLING,
147  MISSING_UTXO,
148 };
149 
150 class ProofRegistrationState : public ValidationState<ProofRegistrationResult> {
151 };
152 
153 namespace bmi = boost::multi_index;
154 
155 class PeerManager {
156  std::vector<Slot> slots;
157  uint64_t slotCount = 0;
158  uint64_t fragmentation = 0;
159 
164  using PeerSet = boost::multi_index_container<
165  Peer, bmi::indexed_by<
166  // index by peerid
167  bmi::hashed_unique<bmi::member<Peer, PeerId, &Peer::peerid>>,
168  // index by proof
169  bmi::hashed_unique<bmi::tag<by_proofid>, proof_index,
171  // ordered by score, decreasing order
172  bmi::ordered_non_unique<bmi::tag<by_score>, score_index,
173  std::greater<uint32_t>>>>;
174 
177 
181 
184 
185  using NodeSet = boost::multi_index_container<
186  Node,
187  bmi::indexed_by<
188  // index by nodeid
189  bmi::hashed_unique<bmi::member<Node, NodeId, &Node::nodeid>>,
190  // sorted by peerid/nextRequestTime
191  bmi::ordered_non_unique<
192  bmi::tag<next_request_time>,
193  bmi::composite_key<
194  Node, bmi::member<Node, PeerId, &Node::peerid>,
195  bmi::member<Node, TimePoint, &Node::nextRequestTime>>>>>;
196 
198 
203  std::atomic<bool> needMoreNodes{false};
204 
205  using PendingNodeSet = boost::multi_index_container<
206  PendingNode,
207  bmi::indexed_by<
208  // index by proofid
209  bmi::hashed_non_unique<
210  bmi::tag<by_proofid>,
211  bmi::member<PendingNode, ProofId, &PendingNode::proofid>,
213  // index by nodeid
214  bmi::hashed_unique<
215  bmi::tag<by_nodeid>,
216  bmi::member<PendingNode, NodeId, &PendingNode::nodeid>>>>;
218 
219  static constexpr int SELECT_PEER_MAX_RETRY = 3;
220  static constexpr int SELECT_NODE_MAX_RETRY = 3;
221 
226 
235 
239  uint32_t totalPeersScore = 0;
240  uint32_t connectedPeersScore = 0;
241 
243 
245 
246 public:
247  PeerManager(const Amount &stakeUtxoDustThresholdIn,
248  ChainstateManager &chainmanIn)
249  : stakeUtxoDustThreshold(stakeUtxoDustThresholdIn),
250  chainman(chainmanIn){};
251 
255  bool addNode(NodeId nodeid, const ProofId &proofid);
256  bool removeNode(NodeId nodeid);
257  size_t getNodeCount() const { return nodes.size(); }
258  size_t getPendingNodeCount() const { return pendingNodes.size(); }
259 
260  // Update when a node is to be polled next.
261  bool updateNextRequestTime(NodeId nodeid, TimePoint timeout);
267  bool latchAvaproofsSent(NodeId nodeid);
268 
269  // Randomly select a node to poll.
270  NodeId selectNode();
271 
275  bool shouldRequestMoreNodes() { return needMoreNodes.exchange(false); }
276 
277  template <typename Callable>
278  bool forNode(NodeId nodeid, Callable &&func) const {
279  auto it = nodes.find(nodeid);
280  return it != nodes.end() && func(*it);
281  }
282 
283  template <typename Callable>
284  void forEachNode(const Peer &peer, Callable &&func) const {
285  auto &nview = nodes.get<next_request_time>();
286  auto range = nview.equal_range(peer.peerid);
287  for (auto it = range.first; it != range.second; ++it) {
288  func(*it);
289  }
290  }
291 
301  const std::chrono::seconds &nextTime);
302 
306  bool setFinalized(PeerId peerid);
307 
315  enum class RegistrationMode {
316  DEFAULT,
317  FORCE_ACCEPT,
318  };
319 
320  bool registerProof(const ProofRef &proof,
321  ProofRegistrationState &registrationState,
323  bool registerProof(const ProofRef &proof,
326  return registerProof(proof, dummy, mode);
327  }
328 
338  enum class RejectionMode {
339  DEFAULT,
340  INVALIDATE,
341  };
342 
343  bool rejectProof(const ProofId &proofid,
345 
346  bool exists(const ProofId &proofid) const {
347  return getProof(proofid) != nullptr;
348  }
349 
350  void cleanupDanglingProofs(const ProofRef &localProof);
351 
352  template <typename Callable>
353  bool forPeer(const ProofId &proofid, Callable &&func) const {
354  auto &pview = peers.get<by_proofid>();
355  auto it = pview.find(proofid);
356  return it != pview.end() && func(*it);
357  }
358 
359  template <typename Callable> void forEachPeer(Callable &&func) const {
360  for (const auto &p : peers) {
361  func(p);
362  }
363  }
364 
368  std::unordered_set<ProofRef, SaltedProofHasher> updatedBlockTip();
369 
373  void addUnbroadcastProof(const ProofId &proofid);
374  void removeUnbroadcastProof(const ProofId &proofid);
376 
377  /*
378  * Quorum management
379  */
380  uint32_t getTotalPeersScore() const { return totalPeersScore; }
381  uint32_t getConnectedPeersScore() const { return connectedPeersScore; }
382 
383  template <typename Callable>
384  void updateAvailabilityScores(const double decayFactor,
385  Callable &&getNodeAvailabilityScore) {
386  for (auto it = peers.begin(); it != peers.end(); it++) {
387  peers.modify(it, [&](Peer &peer) {
388  // Calculate average of current node scores
389  double peerScore{0.0};
390  forEachNode(peer, [&](const avalanche::Node &node) {
391  peerScore += getNodeAvailabilityScore(node.nodeid);
392  });
393 
394  // Calculate exponential moving average of averaged node scores
395  peer.availabilityScore =
396  decayFactor * peerScore +
397  (1. - decayFactor) * peer.availabilityScore;
398  });
399  }
400  }
401 
402  /****************************************************
403  * Functions which are public for testing purposes. *
404  ****************************************************/
405 
409  bool removePeer(const PeerId peerid);
410 
414  PeerId selectPeer() const;
415 
420  uint64_t compact();
421 
425  bool verify() const;
426 
427  // Accessors.
428  uint64_t getSlotCount() const { return slotCount; }
429  uint64_t getFragmentation() const { return fragmentation; }
430 
431  const ProofPool &getValidProofPool() const { return validProofPool; }
433  return conflictingProofPool;
434  }
436 
437  ProofRef getProof(const ProofId &proofid) const;
438  bool isBoundToPeer(const ProofId &proofid) const;
439  bool isImmature(const ProofId &proofid) const;
440  bool isInConflictingPool(const ProofId &proofid) const;
441 
443  return shareableProofs;
444  }
445 
447  return stakeUtxoDustThreshold;
448  }
449 
450 private:
451  template <typename ProofContainer>
452  void moveToConflictingPool(const ProofContainer &proofs);
453 
454  bool addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid);
455  bool addNodeToPeer(const PeerSet::iterator &it);
456  bool removeNodeFromPeer(const PeerSet::iterator &it, uint32_t count = 1);
457 
458  friend struct ::avalanche::TestPeerManager;
459 };
460 
464 PeerId selectPeerImpl(const std::vector<Slot> &slots, const uint64_t slot,
465  const uint64_t max);
466 
467 } // namespace avalanche
468 
469 #endif // BITCOIN_AVALANCHE_PEERMANAGER_H
std::chrono::time_point< std::chrono::steady_clock > TimePoint
Definition: node.h:17
uint32_t PeerId
Definition: node.h:14
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:119
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1060
Template for capturing information about block/transaction validation.
Definition: validation.h:90
PeerManager(const Amount &stakeUtxoDustThresholdIn, ChainstateManager &chainmanIn)
Definition: peermanager.h:247
boost::multi_index_container< Node, bmi::indexed_by< bmi::hashed_unique< bmi::member< Node, NodeId, &Node::nodeid > >, bmi::ordered_non_unique< bmi::tag< next_request_time >, bmi::composite_key< Node, bmi::member< Node, PeerId, &Node::peerid >, bmi::member< Node, TimePoint, &Node::nextRequestTime > >> >> NodeSet
Definition: peermanager.h:195
uint32_t connectedPeersScore
Definition: peermanager.h:240
boost::multi_index_container< PendingNode, bmi::indexed_by< bmi::hashed_non_unique< bmi::tag< by_proofid >, bmi::member< PendingNode, ProofId, &PendingNode::proofid >, SaltedProofIdHasher >, bmi::hashed_unique< bmi::tag< by_nodeid >, bmi::member< PendingNode, NodeId, &PendingNode::nodeid > >> > PendingNodeSet
Definition: peermanager.h:216
bool removeNode(NodeId nodeid)
Definition: peermanager.cpp:83
bool setFinalized(PeerId peerid)
Latch on that this peer has a finalized proof.
uint64_t getFragmentation() const
Definition: peermanager.h:429
uint32_t getConnectedPeersScore() const
Definition: peermanager.h:381
void cleanupDanglingProofs(const ProofRef &localProof)
bool addNodeToPeer(const PeerSet::iterator &it)
Definition: peermanager.cpp:63
bool shouldRequestMoreNodes()
Returns true if we encountered a lack of node since the last call.
Definition: peermanager.h:275
bool exists(const ProofId &proofid) const
Definition: peermanager.h:346
bool updateNextRequestTime(NodeId nodeid, TimePoint timeout)
size_t getNodeCount() const
Definition: peermanager.h:257
PendingNodeSet pendingNodes
Definition: peermanager.h:217
bool verify() const
Perform consistency check on internal data structures.
bool forNode(NodeId nodeid, Callable &&func) const
Definition: peermanager.h:278
bool forPeer(const ProofId &proofid, Callable &&func) const
Definition: peermanager.h:353
uint32_t getTotalPeersScore() const
Definition: peermanager.h:380
bool latchAvaproofsSent(NodeId nodeid)
Flag that a node did send its compact proofs.
bool registerProof(const ProofRef &proof, RegistrationMode mode=RegistrationMode::DEFAULT)
Definition: peermanager.h:323
bool addNode(NodeId nodeid, const ProofId &proofid)
Node API.
Definition: peermanager.cpp:18
uint64_t getSlotCount() const
Definition: peermanager.h:428
static constexpr int SELECT_PEER_MAX_RETRY
Definition: peermanager.h:219
ProofIdSet m_unbroadcast_proofids
Track proof ids to broadcast.
Definition: peermanager.h:225
RejectionMode
Rejection mode.
Definition: peermanager.h:338
void addUnbroadcastProof(const ProofId &proofid)
Proof broadcast API.
std::unordered_set< ProofRef, SaltedProofHasher > updatedBlockTip()
Update the peer set when a new block is connected.
void removeUnbroadcastProof(const ProofId &proofid)
bool isBoundToPeer(const ProofId &proofid) const
const ProofPool & getConflictingProofPool() const
Definition: peermanager.h:432
size_t getPendingNodeCount() const
Definition: peermanager.h:258
ProofRadixTree shareableProofs
Definition: peermanager.h:183
uint64_t compact()
Trigger maintenance of internal data structures.
std::vector< Slot > slots
Definition: peermanager.h:156
uint32_t totalPeersScore
Quorum management.
Definition: peermanager.h:239
void forEachPeer(Callable &&func) const
Definition: peermanager.h:359
const ProofPool & getValidProofPool() const
Definition: peermanager.h:431
void forEachNode(const Peer &peer, Callable &&func) const
Definition: peermanager.h:284
const Amount & getStakeUtxoDustThreshold() const
Definition: peermanager.h:446
ChainstateManager & chainman
Definition: peermanager.h:244
bool removePeer(const PeerId peerid)
Remove an existing peer.
const ProofPool & getImmatureProofPool() const
Definition: peermanager.h:435
bool isImmature(const ProofId &proofid) const
bool addOrUpdateNode(const PeerSet::iterator &it, NodeId nodeid)
Definition: peermanager.cpp:33
bool rejectProof(const ProofId &proofid, RejectionMode mode=RejectionMode::DEFAULT)
ProofPool immatureProofPool
Definition: peermanager.h:180
RegistrationMode
Registration mode.
Definition: peermanager.h:315
ProofPool conflictingProofPool
Definition: peermanager.h:179
std::atomic< bool > needMoreNodes
Flag indicating that we failed to select a node and need to expand our node set.
Definition: peermanager.h:203
PeerId selectPeer() const
Randomly select a peer to poll.
const ProofRadixTree & getShareableProofsSnapshot() const
Definition: peermanager.h:442
boost::multi_index_container< Peer, bmi::indexed_by< bmi::hashed_unique< bmi::member< Peer, PeerId, &Peer::peerid > >, bmi::hashed_unique< bmi::tag< by_proofid >, proof_index, SaltedProofIdHasher >, bmi::ordered_non_unique< bmi::tag< by_score >, score_index, std::greater< uint32_t > >> > PeerSet
Several nodes can make an avalanche peer.
Definition: peermanager.h:173
void updateAvailabilityScores(const double decayFactor, Callable &&getNodeAvailabilityScore)
Definition: peermanager.h:384
auto getUnbroadcastProofs() const
Definition: peermanager.h:375
bool isInConflictingPool(const ProofId &proofid) const
static constexpr int SELECT_NODE_MAX_RETRY
Definition: peermanager.h:220
ProofRef getProof(const ProofId &proofid) const
bool registerProof(const ProofRef &proof, ProofRegistrationState &registrationState, RegistrationMode mode=RegistrationMode::DEFAULT)
bool removeNodeFromPeer(const PeerSet::iterator &it, uint32_t count=1)
bool updateNextPossibleConflictTime(PeerId peerid, const std::chrono::seconds &nextTime)
Proof and Peer related API.
void moveToConflictingPool(const ProofContainer &proofs)
CRollingBloomFilter danglingProofIds
Remember the last proofs that have been evicted because they had no node attached.
Definition: peermanager.h:234
Map a proof to each utxo.
Definition: proofpool.h:57
ProofRegistrationResult
Definition: peermanager.h:138
static constexpr uint32_t AVALANCHE_MAX_IMMATURE_PROOFS
Maximum number of immature proofs the peer manager will accept from the network.
Definition: peermanager.h:44
std::unordered_set< ProofId, SaltedProofIdHasher > ProofIdSet
Definition: proofpool.h:52
PeerId selectPeerImpl(const std::vector< Slot > &slots, const uint64_t slot, const uint64_t max)
Internal methods that are exposed for testing purposes.
Definition: init.h:28
int64_t NodeId
Definition: nodeid.h:10
Definition: amount.h:19
std::chrono::seconds registration_time
Definition: peermanager.h:93
std::chrono::seconds nextPossibleConflictTime
Definition: peermanager.h:94
uint32_t node_count
Definition: peermanager.h:87
double availabilityScore
Definition: peermanager.h:96
static constexpr auto DANGLING_TIMEOUT
Consider dropping the peer if no node is attached after this timeout expired.
Definition: peermanager.h:102
const ProofId & getProofId() const
Definition: peermanager.h:110
uint32_t index
Definition: peermanager.h:86
uint32_t getScore() const
Definition: peermanager.h:111
ProofRef proof
Definition: peermanager.h:89
Peer(PeerId peerid_, ProofRef proof_, std::chrono::seconds nextPossibleConflictTime_)
Definition: peermanager.h:104
PendingNode(ProofId proofid_, NodeId nodeid_)
Definition: peermanager.h:130
Slot(uint64_t startIn, uint32_t scoreIn, PeerId peeridIn)
Definition: peermanager.h:59
uint32_t score
Definition: peermanager.h:55
uint64_t start
Definition: peermanager.h:54
Slot withPeerId(PeerId peeridIn) const
Definition: peermanager.h:68
uint32_t getScore() const
Definition: peermanager.h:74
bool follows(uint64_t slot) const
Definition: peermanager.h:81
Slot withScore(uint64_t scoreIn) const
Definition: peermanager.h:65
Slot withStart(uint64_t startIn) const
Definition: peermanager.h:62
uint64_t getStop() const
Definition: peermanager.h:73
uint64_t getStart() const
Definition: peermanager.h:72
PeerId getPeerId() const
Definition: peermanager.h:75
bool precedes(uint64_t slot) const
Definition: peermanager.h:80
bool contains(uint64_t slot) const
Definition: peermanager.h:77
result_type operator()(const Peer &p) const
Definition: peermanager.h:116
result_type operator()(const Peer &p) const
Definition: peermanager.h:121
static int count
Definition: tests.c:31
T GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:71