PIVX Core  5.6.99
P2P Digital Currency
net_processing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2014-2021 The Dash Core developers
4 // Copyright (c) 2015-2022 The PIVX Core developers
5 // Distributed under the MIT software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 
8 #include "net_processing.h"
9 
10 #include "budget/budgetmanager.h"
11 #include "chain.h"
12 #include "evo/deterministicmns.h"
13 #include "evo/mnauth.h"
17 #include "llmq/quorums_signing.h"
18 #include "masternode-payments.h"
19 #include "masternode-sync.h"
20 #include "masternodeman.h"
21 #include "merkleblock.h"
22 #include "netbase.h"
23 #include "netmessagemaker.h"
24 #include "primitives/block.h"
25 #include "primitives/transaction.h"
26 #include "spork.h"
27 #include "sporkdb.h"
28 #include "streams.h"
30 #include "util/validation.h"
31 #include "validation.h"
32 
33 #include <chrono>
34 
35 using namespace std::chrono_literals;
36 
37 
38 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
39 
41 static constexpr size_t MAX_PCT_ADDR_TO_SEND = 23;
42 
44 {
45  template<typename I>
46  bool operator()(const I& a, const I& b) const
47  {
48  return &(*a) < &(*b);
49  }
50 };
51 
52 struct COrphanTx {
53  // When modifying, adapt the copy of this definition in tests/DoS_tests.
56  int64_t nTimeExpire;
57  size_t list_pos;
58 };
60 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
61 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(g_cs_orphans);
62 std::vector<std::map<uint256, COrphanTx>::iterator> g_orphan_list GUARDED_BY(g_cs_orphans);
63 
64 void EraseOrphansFor(NodeId peer);
65 
66 // Internal stuff
67 namespace {
68 
70 int nSyncStarted = 0;
71 
76 std::map<uint256, NodeId> mapBlockSource;
77 
98 std::unique_ptr<CRollingBloomFilter> recentRejects;
99 uint256 hashRecentRejectsChainTip;
100 
102 struct QueuedBlock {
103  uint256 hash;
104  const CBlockIndex* pindex;
105  int64_t nTime;
106  int nValidatedQueuedBefore;
107  bool fValidatedHeaders;
108 };
109 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
110 
112 int nQueuedValidatedHeaders = 0;
113 
115 int nPreferredDownload = 0;
116 
117 } // anon namespace
118 
119 namespace
120 {
121 
122 class CNodeBlocks
123 {
124 public:
125  CNodeBlocks():
126  maxSize(0),
127  maxAvg(0)
128  {
129  maxSize = gArgs.GetArg("-blockspamfiltermaxsize", DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE);
130  maxAvg = gArgs.GetArg("-blockspamfiltermaxavg", DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG);
131  }
132 
133  bool onBlockReceived(int nHeight) {
134  if(nHeight > 0 && maxSize && maxAvg) {
135  addPoint(nHeight);
136  return true;
137  }
138  return false;
139  }
140 
141  bool updateState(CValidationState& state, bool ret)
142  {
143  // No Blocks
144  size_t size = points.size();
145  if(size == 0)
146  return ret;
147 
148  // Compute the number of the received blocks
149  size_t nBlocks = 0;
150  for (auto point : points) {
151  nBlocks += point.second;
152  }
153 
154  // Compute the average value per height
155  double nAvgValue = (double)nBlocks / size;
156 
157  // Ban the node if try to spam
158  bool banNode = (nAvgValue >= 1.5 * maxAvg && size >= maxAvg) ||
159  (nAvgValue >= maxAvg && nBlocks >= maxSize) ||
160  (nBlocks >= maxSize * 3);
161  if (banNode) {
162  // Clear the points and ban the node
163  points.clear();
164  return state.DoS(100, error("block-spam ban node for sending spam"));
165  }
166 
167  return ret;
168  }
169 
170 private:
171  void addPoint(int height)
172  {
173  // Remove the last element in the list
174  if(points.size() == maxSize)
175  {
176  points.erase(points.begin());
177  }
178 
179  // Add the point to the list
180  int occurrence = 0;
181  auto mi = points.find(height);
182  if (mi != points.end())
183  occurrence = (*mi).second;
184  occurrence++;
185  points[height] = occurrence;
186  }
187 
188 private:
189  std::map<int,int> points;
190  size_t maxSize;
191  size_t maxAvg;
192 };
193 
194 
195 
202 struct CNodeState {
204  const CService address;
206  bool fCurrentlyConnected;
208  int nMisbehavior;
210  bool fShouldBan;
212  const std::string name;
214  const CBlockIndex* pindexBestKnownBlock;
216  uint256 hashLastUnknownBlock;
218  const CBlockIndex* pindexLastCommonBlock;
220  bool fSyncStarted;
222  int64_t nStallingSince;
223  std::list<QueuedBlock> vBlocksInFlight;
224  int nBlocksInFlight;
226  bool fPreferredDownload;
228  uint64_t amt_addr_processed = 0;
230  uint64_t amt_addr_rate_limited = 0;
231 
232  CNodeBlocks nodeBlocks;
233 
234  CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
235  fCurrentlyConnected = false;
236  nMisbehavior = 0;
237  fShouldBan = false;
238  pindexBestKnownBlock = nullptr;
239  hashLastUnknownBlock.SetNull();
240  pindexLastCommonBlock = nullptr;
241  fSyncStarted = false;
242  nStallingSince = 0;
243  nBlocksInFlight = 0;
244  fPreferredDownload = false;
245  }
246 };
247 
249 std::map<NodeId, CNodeState> mapNodeState;
250 
251 // Requires cs_main.
252 CNodeState* State(NodeId pnode)
253 {
254  std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
255  if (it == mapNodeState.end())
256  return nullptr;
257  return &it->second;
258 }
259 
260 void UpdatePreferredDownload(CNode* node, CNodeState* state)
261 {
262  nPreferredDownload -= state->fPreferredDownload;
263 
264  // Whether this node should be marked as a preferred download node.
265  state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
266 
267  nPreferredDownload += state->fPreferredDownload;
268 }
269 
270 void PushNodeVersion(CNode* pnode, CConnman* connman, int64_t nTime)
271 {
272  ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
273  uint64_t nonce = pnode->GetLocalNonce();
274  int nNodeStartingHeight = pnode->GetMyStartingHeight();
275  NodeId nodeid = pnode->GetId();
276  CAddress addr = pnode->addr;
277 
278  CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
279  CAddress addrMe = CAddress(CService(), nLocalNodeServices);
280 
281  // Create the version message
282  auto version_msg = CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
283  nonce, strSubVersion, nNodeStartingHeight, true);
284 
285  // DMN-to-DMN, set auth connection type and create challenge.
286  if (pnode->m_masternode_connection) {
287  uint256 mnauthChallenge;
288  GetRandBytes(mnauthChallenge.begin(), (int) mnauthChallenge.size());
289  WITH_LOCK(pnode->cs_mnauth, pnode->sentMNAuthChallenge = mnauthChallenge);
290  CVectorWriter{SER_NETWORK, 0 | INIT_PROTO_VERSION, version_msg.data, version_msg.data.size(), pnode->sentMNAuthChallenge};
291  }
292 
293  connman->PushMessage(pnode, std::move(version_msg));
294 
295  if (fLogIPs)
296  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
297  else
298  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
299 }
300 
301 // Requires cs_main.
302 void MarkBlockAsReceived(const uint256& hash)
303 {
304  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
305  if (itInFlight != mapBlocksInFlight.end()) {
306  CNodeState* state = State(itInFlight->second.first);
307  assert(state != nullptr);
308  nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
309  state->vBlocksInFlight.erase(itInFlight->second.second);
310  state->nBlocksInFlight--;
311  state->nStallingSince = 0;
312  mapBlocksInFlight.erase(itInFlight);
313  }
314 }
315 
316 // Requires cs_main.
317 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr)
318 {
319  CNodeState* state = State(nodeid);
320  assert(state != nullptr);
321 
322  // Make sure it's not listed somewhere already.
323  MarkBlockAsReceived(hash);
324 
325  QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != nullptr};
326  nQueuedValidatedHeaders += newentry.fValidatedHeaders;
327  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
328  state->nBlocksInFlight++;
329  mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
330 }
331 
333 static void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
334 {
336 
337  CNodeState* state = State(nodeid);
338  assert(state != nullptr);
339 
340  if (!state->hashLastUnknownBlock.IsNull()) {
341  CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
342  if (pindex && pindex->nChainWork > 0) {
343  if (!state->pindexBestKnownBlock || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork)
344  state->pindexBestKnownBlock = pindex;
345  state->hashLastUnknownBlock.SetNull();
346  }
347  }
348 }
349 
351 static void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
352 {
354 
355  CNodeState* state = State(nodeid);
356  assert(state != nullptr);
357 
358  ProcessBlockAvailability(nodeid);
359 
360  CBlockIndex* pindex = LookupBlockIndex(hash);
361  if (pindex && pindex->nChainWork > 0) {
362  // An actually better block was announced.
363  if (!state->pindexBestKnownBlock || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork)
364  state->pindexBestKnownBlock = pindex;
365  } else {
366  // An unknown block was announced; just assume that the latest one is the best one.
367  state->hashLastUnknownBlock = hash;
368  }
369 }
370 
373 static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
374 {
376 
377  if (count == 0)
378  return;
379 
380  vBlocks.reserve(vBlocks.size() + count);
381  CNodeState* state = State(nodeid);
382  assert(state != nullptr);
383 
384  // Make sure pindexBestKnownBlock is up to date, we'll need it.
385  ProcessBlockAvailability(nodeid);
386 
387  if (!state->pindexBestKnownBlock || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
388  // This peer has nothing interesting.
389  return;
390  }
391 
392  if (!state->pindexLastCommonBlock) {
393  // Bootstrap quickly by guessing a parent of our best tip is the forking point.
394  // Guessing wrong in either direction is not a problem.
395  state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
396  }
397 
398  // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
399  // of their current tip anymore. Go back enough to fix that.
400  state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
401  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
402  return;
403 
404  std::vector<const CBlockIndex*> vToFetch;
405  const CBlockIndex* pindexWalk = state->pindexLastCommonBlock;
406  // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
407  // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
408  // download that next block if the window were 1 larger.
409  int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
410  int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
411  NodeId waitingfor = -1;
412  while (pindexWalk->nHeight < nMaxHeight) {
413  // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
414  // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
415  // as iterating over ~100 CBlockIndex* entries anyway.
416  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
417  vToFetch.resize(nToFetch);
418  pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
419  vToFetch[nToFetch - 1] = pindexWalk;
420  for (unsigned int i = nToFetch - 1; i > 0; i--) {
421  vToFetch[i - 1] = vToFetch[i]->pprev;
422  }
423 
424  // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
425  // are not yet downloaded and not in flight to vBlocks. In the mean time, update
426  // pindexLastCommonBlock as long as all ancestors are already downloaded.
427  for (const CBlockIndex* pindex : vToFetch) {
428  if (!pindex->IsValid(BLOCK_VALID_TREE)) {
429  // We consider the chain that this peer is on invalid.
430  return;
431  }
432  if (pindex->nStatus & BLOCK_HAVE_DATA) {
433  if (pindex->nChainTx)
434  state->pindexLastCommonBlock = pindex;
435  } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
436  // The block is not already downloaded, and not yet in flight.
437  if (pindex->nHeight > nWindowEnd) {
438  // We reached the end of the window.
439  if (vBlocks.size() == 0 && waitingfor != nodeid) {
440  // We aren't able to fetch anything, but we would be if the download window was one larger.
441  nodeStaller = waitingfor;
442  }
443  return;
444  }
445  vBlocks.push_back(pindex);
446  if (vBlocks.size() == count) {
447  return;
448  }
449  } else if (waitingfor == -1) {
450  // This is the first already-in-flight block.
451  waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
452  }
453  }
454  }
455 }
456 
457 } // anon namespace
458 
460  CAddress addr = pnode->addr;
461  std::string addrName = pnode->GetAddrName();
462  NodeId nodeid = pnode->GetId();
463  {
464  LOCK(cs_main);
465  mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
466  }
467  if(!pnode->fInbound)
468  PushNodeVersion(pnode, connman, GetTime());
469 }
470 
471 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime)
472 {
473  fUpdateConnectionTime = false;
474  LOCK(cs_main);
475  CNodeState* state = State(nodeid);
476 
477  if (state->fSyncStarted)
478  nSyncStarted--;
479 
480  if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
481  fUpdateConnectionTime = true;
482  }
483 
484  for (const QueuedBlock& entry : state->vBlocksInFlight)
485  mapBlocksInFlight.erase(entry.hash);
486  EraseOrphansFor(nodeid);
487  nPreferredDownload -= state->fPreferredDownload;
488 
489  mapNodeState.erase(nodeid);
490  LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
491 }
492 
494 {
495  LOCK(cs_main);
496  CNodeState* state = State(nodeid);
497  if (!state)
498  return false;
499  stats.nMisbehavior = state->nMisbehavior;
500  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
501  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
502  for (const QueuedBlock& queue : state->vBlocksInFlight) {
503  if (queue.pindex)
504  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
505  }
506 
507  stats.m_addr_processed = state->amt_addr_processed;
508  stats.m_addr_rate_limited = state->amt_addr_rate_limited;
509  return true;
510 }
511 
513 //
514 // mapOrphanTransactions
515 //
516 
518 {
519  const uint256& hash = tx->GetHash();
520  if (mapOrphanTransactions.count(hash))
521  return false;
522 
523  // Ignore big transactions, to avoid a
524  // send-big-orphans memory exhaustion attack. If a peer has a legitimate
525  // large transaction with a missing parent then we assume
526  // it will rebroadcast it later, after the parent transaction(s)
527  // have been mined or received.
528  // 25 orphans, each of which is at most 400,000 bytes big is
529  // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
530  unsigned int sz = tx->GetTotalSize();
531  unsigned int nMaxSize = tx->IsShieldedTx() ? MAX_TX_SIZE_AFTER_SAPLING : MAX_STANDARD_TX_SIZE;
532  if (sz >= nMaxSize) {
533  LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
534  return false;
535  }
536 
537  auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME, g_orphan_list.size()});
538  assert(ret.second);
539  g_orphan_list.emplace_back(ret.first);
540  for (const CTxIn& txin : tx->vin) {
541  mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
542  }
543 
544  LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
545  mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
546  return true;
547 }
548 
549 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
550 {
551  std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
552  if (it == mapOrphanTransactions.end())
553  return 0;
554  for (const CTxIn& txin : it->second.tx->vin) {
555  auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
556  if (itPrev == mapOrphanTransactionsByPrev.end())
557  continue;
558  itPrev->second.erase(it);
559  if (itPrev->second.empty())
560  mapOrphanTransactionsByPrev.erase(itPrev);
561  }
562 
563  size_t old_pos = it->second.list_pos;
564  assert(g_orphan_list[old_pos] == it);
565  if (old_pos + 1 != g_orphan_list.size()) {
566  // Unless we're deleting the last entry in g_orphan_list, move the last
567  // entry to the position we're deleting.
568  auto it_last = g_orphan_list.back();
569  g_orphan_list[old_pos] = it_last;
570  it_last->second.list_pos = old_pos;
571  }
572  g_orphan_list.pop_back();
573 
574  mapOrphanTransactions.erase(it);
575  return 1;
576 }
577 
579 {
581  int nErased = 0;
582  std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
583  while (iter != mapOrphanTransactions.end()) {
584  std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
585  if (maybeErase->second.fromPeer == peer) {
586  nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
587  }
588  }
589  if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer %d\n", nErased, peer);
590 }
591 
592 
593 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
594 {
596 
597  unsigned int nEvicted = 0;
598  static int64_t nNextSweep;
599  int64_t nNow = GetTime();
600  if (nNextSweep <= nNow) {
601  // Sweep out expired orphan pool entries:
602  int nErased = 0;
603  int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
604  auto iter = mapOrphanTransactions.begin();
605  while (iter != mapOrphanTransactions.end()) {
606  auto maybeErase = iter++;
607  if (maybeErase->second.nTimeExpire <= nNow) {
608  nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
609  } else {
610  nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
611  }
612  }
613  // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
614  nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
615  if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
616  }
617  FastRandomContext rng;
618  while (mapOrphanTransactions.size() > nMaxOrphans) {
619  // Evict a random orphan:
620  size_t randompos = rng.randrange(g_orphan_list.size());
621  EraseOrphanTx(g_orphan_list[randompos]->first);
622  ++nEvicted;
623  }
624  return nEvicted;
625 }
626 
627 // Requires cs_main.
628 void Misbehaving(NodeId pnode, int howmuch, const std::string& message) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
629 {
630  if (howmuch == 0)
631  return;
632 
633  CNodeState* state = State(pnode);
634  if (state == nullptr)
635  return;
636 
637  state->nMisbehavior += howmuch;
638  int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
639  std::string message_prefixed = message.empty() ? "" : (": " + message);
640  if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) {
641  LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed);
642  state->fShouldBan = true;
643  } else {
644  LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d)%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed);
645  }
646 }
647 
648 // Requires cs_main.
649 bool IsBanned(NodeId pnode)
650 {
651  CNodeState* state = State(pnode);
652  if (state == nullptr)
653  return false;
654  if (state->fShouldBan) {
655  return true;
656  }
657  return false;
658 }
659 
660 static void CheckBlockSpam(NodeId nodeId, const uint256& hashBlock)
661 {
662  // Block spam filtering
663  if (!gArgs.GetBoolArg("-blockspamfilter", DEFAULT_BLOCK_SPAM_FILTER)) {
664  return;
665  }
666 
667  CNodeState* nodestate = nullptr;
668  int blockReceivedHeight = 0;
669  {
670  LOCK(cs_main);
671  nodestate = State(nodeId);
672  if (!nodestate) { return; }
673 
674  CBlockIndex* pindex = LookupBlockIndex(hashBlock);
675  if (!pindex) { return; }
676  blockReceivedHeight = pindex->nHeight;
677  }
678 
679  nodestate->nodeBlocks.onBlockReceived(blockReceivedHeight);
680  bool nodeStatus = true;
681  // UpdateState will return false if the node is attacking us or update the score and return true.
682  CValidationState state;
683  nodeStatus = nodestate->nodeBlocks.updateState(state, nodeStatus);
684  int nDoS = 0;
685  if (state.IsInvalid(nDoS)) {
686  if (nDoS > 0) {
687  LOCK(cs_main);
688  Misbehaving(nodeId, nDoS);
689  }
690  nodeStatus = false;
691  }
692 
693  if (!nodeStatus) {
694  LogPrintf("Block spam protection: %s\n", hashBlock.ToString());
695  }
696 }
697 
698 
700 //
701 // blockchain -> download logic notification
702 //
703 
705  connman(connmanIn)
706 {
707  // Initialize global variables that cannot be constructed at startup.
708  recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
709 }
710 
711 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
712 {
714 
715  std::vector<uint256> vOrphanErase;
716 
717  for (const CTransactionRef& ptx : pblock->vtx) {
718  const CTransaction& tx = *ptx;
719 
720  // Which orphan pool entries must we evict?
721  for (size_t j = 0; j < tx.vin.size(); j++) {
722  auto itByPrev = mapOrphanTransactionsByPrev.find(tx.vin[j].prevout);
723  if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
724  for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
725  const CTransaction& orphanTx = *(*mi)->second.tx;
726  const uint256& orphanHash = orphanTx.GetHash();
727  vOrphanErase.emplace_back(orphanHash);
728  }
729  }
730  }
731 
732  // Erase orphan transactions include or precluded by this block
733  if (!vOrphanErase.empty()) {
734  int nErased = 0;
735  for (uint256& orphanHash : vOrphanErase) {
736  nErased += EraseOrphanTx(orphanHash);
737  }
738  LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
739  }
740 }
741 
742 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload)
743 {
744  const int nNewHeight = pindexNew->nHeight;
745  connman->SetBestHeight(nNewHeight);
746 
747  if (!fInitialDownload) {
748  const uint256& hashNewTip = pindexNew->GetBlockHash();
749  // Relay inventory, but don't relay old inventory during initial block download.
750  connman->ForEachNode([nNewHeight, hashNewTip](CNode* pnode) {
751  // Don't sync from MN only connections.
752  if (!pnode->CanRelay()) {
753  return;
754  }
755  if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
756  pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
757  }
758  });
759  }
760 }
761 
763 {
764  LOCK(cs_main);
765 
766  const uint256& hash = block.GetHash();
767  std::map<uint256, NodeId>::iterator it = mapBlockSource.find(hash);
768 
769  int nDoS = 0;
770  if (state.IsInvalid(nDoS)) {
771  if (it != mapBlockSource.end() && State(it->second)) {
772  assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
773  if (nDoS > 0) {
774  Misbehaving(it->second, nDoS);
775  }
776 
777  // Spam filter
778  CheckBlockSpam(it->second, block.GetHash());
779  }
780  }
781 
782  if (it != mapBlockSource.end())
783  mapBlockSource.erase(it);
784 }
785 
787 //
788 // Messages
789 //
790 
791 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
792 {
793  switch (inv.type) {
794  case MSG_TX: {
795  assert(recentRejects);
796  if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) {
797  // If the chain tip has changed previously rejected transactions
798  // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
799  // or a double-spend. Reset the rejects filter and give those
800  // txs a second chance.
801  hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
802  recentRejects->reset();
803  }
804 
805  {
807  if (mapOrphanTransactions.count(inv.hash)) return true;
808  }
809 
810  return recentRejects->contains(inv.hash) ||
811  mempool.exists(inv.hash) ||
812  pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
813  pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
814  }
815 
816  case MSG_BLOCK:
817  return LookupBlockIndex(inv.hash) != nullptr;
818  case MSG_TXLOCK_REQUEST:
819  // deprecated
820  return true;
821  case MSG_TXLOCK_VOTE:
822  // deprecated
823  return true;
824  case MSG_SPORK:
825  return mapSporks.count(inv.hash);
829  return true;
830  }
831  return false;
832  case MSG_BUDGET_VOTE:
835  return true;
836  }
837  return false;
838  case MSG_BUDGET_PROPOSAL:
839  if (g_budgetman.HaveProposal(inv.hash)) {
841  return true;
842  }
843  return false;
847  return true;
848  }
849  return false;
853  return true;
854  }
855  return false;
857  if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
859  return true;
860  }
861  return false;
862  case MSG_MASTERNODE_PING:
863  return mnodeman.mapSeenMasternodePing.count(inv.hash);
865  return llmq::quorumBlockProcessor->HasMinableCommitment(inv.hash);
866  case MSG_QUORUM_CONTRIB:
870  return llmq::quorumDKGSessionManager->AlreadyHave(inv);
872  return llmq::quorumSigningManager->AlreadyHave(inv);
873  case MSG_CLSIG:
874  return llmq::chainLocksHandler->AlreadyHave(inv);
875  }
876 
877  // Don't know what it is, just say we already got one
878  return true;
879 }
880 
881 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
882 {
883  CInv inv(MSG_TX, tx.GetHash());
884  connman->RelayInv(inv);
885 }
886 
887 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
888 {
889  if (!fReachable && !addr.IsRelayable()) return;
890  unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
891 
892  // Relay to a limited number of other nodes
893  // Use deterministic randomness to send to the same nodes for 24 hours
894  // at a time so the addrKnowns of the chosen nodes prevent repeats
895  uint64_t hashAddr = addr.GetHash();
896  const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
897  FastRandomContext insecure_rand;
898 
899  std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
900 
901  auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
902  uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
903  for (unsigned int i = 0; i < nRelayNodes; i++) {
904  if (hashKey > best[i].first) {
905  std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
906  best[i] = std::make_pair(hashKey, pnode);
907  break;
908  }
909  }
910  };
911 
912  auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
913  for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
914  best[i].second->PushAddress(addr, insecure_rand);
915  }
916  };
917 
918  connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
919 }
920 
921 bool static PushTierTwoGetDataRequest(const CInv& inv,
922  CNode* pfrom,
923  CConnman* connman,
924  CNetMsgMaker& msgMaker)
925 {
926  if (inv.type == MSG_SPORK) {
927  if (mapSporks.count(inv.hash)) {
928  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
929  ss.reserve(1000);
930  ss << mapSporks[inv.hash];
931  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SPORK, ss));
932  return true;
933  }
934  }
935 
936  if (inv.type == MSG_QUORUM_FINAL_COMMITMENT) {
937  // Only respond if v6.0.0 is enforced and SPORK 22 is not active
938  if (!deterministicMNManager->IsDIP3Enforced()) return false;
941  if (llmq::quorumBlockProcessor->GetMinableCommitmentByHash(inv.hash, o)) {
942  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QFCOMMITMENT, o));
943  return true;
944  }
945  }
946 
947  if (inv.type == MSG_QUORUM_CONTRIB) {
948  // Only respond if v6.0.0 is enforced.
949  if (!deterministicMNManager->IsDIP3Enforced()) return false;
951  if (llmq::quorumDKGSessionManager->GetContribution(inv.hash, o)) {
952  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QCONTRIB, o));
953  return true;
954  }
955  }
956 
957  if (inv.type == MSG_QUORUM_COMPLAINT) {
958  // Only respond if v6.0.0 is enforced.
959  if (!deterministicMNManager->IsDIP3Enforced()) return false;
961  if (llmq::quorumDKGSessionManager->GetComplaint(inv.hash, o)) {
962  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QCOMPLAINT, o));
963  return true;
964  }
965  }
966 
967  if (inv.type == MSG_QUORUM_JUSTIFICATION) {
968  // Only respond if v6.0.0 is enforced.
969  if (!deterministicMNManager->IsDIP3Enforced()) return false;
971  if (llmq::quorumDKGSessionManager->GetJustification(inv.hash, o)) {
972  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QJUSTIFICATION, o));
973  return true;
974  }
975  }
976 
978  // Only respond if v6.0.0 is enforced.
979  if (!deterministicMNManager->IsDIP3Enforced()) return false;
981  if (llmq::quorumDKGSessionManager->GetPrematureCommitment(inv.hash, o)) {
982  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QPCOMMITMENT, o));
983  return true;
984  }
985  }
986 
987  // !TODO: remove when transition to DMN is complete
988  if (inv.type == MSG_MASTERNODE_WINNER && !deterministicMNManager->LegacyMNObsolete()) {
990  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
991  ss.reserve(1000);
993  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MNWINNER, ss));
994  return true;
995  }
996  }
997 
998  if (inv.type == MSG_BUDGET_VOTE) {
1001  return true;
1002  }
1003  }
1004 
1005  if (inv.type == MSG_BUDGET_PROPOSAL) {
1006  if (g_budgetman.HaveProposal(inv.hash)) {
1008  return true;
1009  }
1010  }
1011 
1012  if (inv.type == MSG_BUDGET_FINALIZED_VOTE) {
1015  return true;
1016  }
1017  }
1018 
1019  if (inv.type == MSG_BUDGET_FINALIZED) {
1022  return true;
1023  }
1024  }
1025 
1026  // !TODO: remove when transition to DMN is complete
1027  if (inv.type == MSG_MASTERNODE_ANNOUNCE && !deterministicMNManager->LegacyMNObsolete()) {
1028  auto it = mnodeman.mapSeenMasternodeBroadcast.find(inv.hash);
1029  if (it != mnodeman.mapSeenMasternodeBroadcast.end()) {
1030  const auto& mnb = it->second;
1031 
1032  int version = !mnb.addr.IsAddrV1Compatible() ? PROTOCOL_VERSION | ADDRV2_FORMAT : PROTOCOL_VERSION;
1033  CDataStream ss(SER_NETWORK, version);
1034  ss.reserve(1000);
1035  ss << mnb;
1036  std::string msgType = !mnb.addr.IsAddrV1Compatible() ? NetMsgType::MNBROADCAST2 : NetMsgType::MNBROADCAST;
1037  connman->PushMessage(pfrom, msgMaker.Make(msgType, ss));
1038  return true;
1039  }
1040  }
1041 
1042  // !TODO: remove when transition to DMN is complete
1043  if (inv.type == MSG_MASTERNODE_PING && !deterministicMNManager->LegacyMNObsolete()) {
1044  if (mnodeman.mapSeenMasternodePing.count(inv.hash)) {
1045  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1046  ss.reserve(1000);
1047  ss << mnodeman.mapSeenMasternodePing[inv.hash];
1048  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MNPING, ss));
1049  return true;
1050  }
1051  }
1052  if (inv.type == MSG_QUORUM_RECOVERED_SIG) {
1053  if (!deterministicMNManager->IsDIP3Enforced()) return false;
1055  if (llmq::quorumSigningManager->GetRecoveredSigForGetData(inv.hash, o)) {
1056  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QSIGREC, o));
1057  return true;
1058  }
1059  }
1060  if (inv.type == MSG_CLSIG) {
1062  if (llmq::chainLocksHandler->GetChainLockByHash(inv.hash, o)) {
1063  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::CLSIG, o));
1064  }
1065  }
1066  // nothing was pushed.
1067  return false;
1068 }
1069 
1070 void static ProcessGetBlockData(CNode* pfrom, const CInv& inv, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1071 {
1072  LOCK(cs_main);
1073  CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1074 
1075  bool send = false;
1076  CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1077  if (pindex) {
1078  if (chainActive.Contains(pindex)) {
1079  send = true;
1080  } else {
1081  // To prevent fingerprinting attacks, only send blocks outside of the active
1082  // chain if they are valid, and no more than a max reorg depth than the best header
1083  // chain we know about.
1084  send = pindex->IsValid(BLOCK_VALID_SCRIPTS) && pindexBestHeader &&
1085  (chainActive.Height() - pindex->nHeight < gArgs.GetArg("-maxreorg", DEFAULT_MAX_REORG_DEPTH));
1086  if (!send) {
1087  LogPrint(BCLog::NET, "ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
1088  }
1089  }
1090  }
1091  // Don't send not-validated blocks
1092  if (send && (pindex->nStatus & BLOCK_HAVE_DATA)) {
1093  // Send block from disk
1094  CBlock block;
1095  if (!ReadBlockFromDisk(block, pindex))
1096  assert(!"cannot load block from disk");
1097  if (inv.type == MSG_BLOCK)
1098  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, block));
1099  else // MSG_FILTERED_BLOCK)
1100  {
1101  bool send_ = false;
1102  CMerkleBlock merkleBlock;
1103  {
1104  LOCK(pfrom->cs_filter);
1105  if (pfrom->pfilter) {
1106  send_ = true;
1107  merkleBlock = CMerkleBlock(block, *pfrom->pfilter);
1108  }
1109  }
1110  if (send_) {
1111  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1112  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1113  // This avoids hurting performance by pointlessly requiring a round-trip
1114  // Note that there is currently no way for a node to request any single transactions we didn't send here -
1115  // they must either disconnect and retry or request the full block.
1116  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1117  // however we MUST always provide at least what the remote peer needs
1118  for (std::pair<unsigned int, uint256>& pair : merkleBlock.vMatchedTxn)
1119  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::TX, *block.vtx[pair.first]));
1120  }
1121  // else
1122  // no response
1123  }
1124 
1125  // Trigger them to send a getblocks request for the next batch of inventory
1126  if (inv.hash == pfrom->hashContinue) {
1127  // Bypass PushInventory, this must send even if redundant,
1128  // and we want it right after the last block so they don't
1129  // wait for other stuff first.
1130  std::vector<CInv> vInv;
1131  vInv.emplace_back(MSG_BLOCK, chainActive.Tip()->GetBlockHash());
1132  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1133  pfrom->hashContinue.SetNull();
1134  }
1135  }
1136 }
1137 
1138 // Only return true if the inv type can be answered, not supported types return false.
1139 bool static IsTierTwoInventoryTypeKnown(int type)
1140 {
1141  return type == MSG_SPORK ||
1142  type == MSG_MASTERNODE_WINNER ||
1143  type == MSG_BUDGET_VOTE ||
1144  type == MSG_BUDGET_PROPOSAL ||
1145  type == MSG_BUDGET_FINALIZED ||
1146  type == MSG_BUDGET_FINALIZED_VOTE ||
1147  type == MSG_MASTERNODE_ANNOUNCE ||
1148  type == MSG_MASTERNODE_PING ||
1149  type == MSG_QUORUM_FINAL_COMMITMENT ||
1150  type == MSG_QUORUM_CONTRIB ||
1151  type == MSG_QUORUM_COMPLAINT ||
1152  type == MSG_QUORUM_JUSTIFICATION ||
1154  type == MSG_QUORUM_RECOVERED_SIG ||
1155  type == MSG_CLSIG;
1156 }
1157 
1158 void static ProcessGetData(CNode* pfrom, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1159 {
1161 
1162  std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1163  std::vector<CInv> vNotFound;
1164  CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1165  {
1166  LOCK(cs_main);
1167 
1168  while (it != pfrom->vRecvGetData.end() && (it->type == MSG_TX || IsTierTwoInventoryTypeKnown(it->type))) {
1169  if (interruptMsgProc)
1170  return;
1171  // Don't bother if send buffer is too full to respond anyway
1172  if (pfrom->fPauseSend)
1173  break;
1174 
1175  const CInv &inv = *it;
1176  it++;
1177 
1178  // Send stream from relay memory
1179  bool pushed = false;
1180  if (inv.type == MSG_TX) {
1181  auto txinfo = mempool.info(inv.hash);
1182  if (txinfo.tx) { // future: add timeLastMempoolReq check
1183  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1184  ss.reserve(1000);
1185  ss << *txinfo.tx;
1186  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::TX, ss));
1187  pushed = true;
1188  }
1189  }
1190 
1191  if (!pushed) {
1192  // Now check if it's a tier two data request and push it.
1193  pushed = PushTierTwoGetDataRequest(inv, pfrom, connman, msgMaker);
1194  }
1195 
1196  if (!pushed) {
1197  vNotFound.push_back(inv);
1198  }
1199 
1200  // todo: inventory signal
1201  }
1202  } // release cs_main
1203 
1204  if (it != pfrom->vRecvGetData.end() && !pfrom->fPauseSend) {
1205  const CInv &inv = *it;
1206  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) {
1207  it++;
1208  ProcessGetBlockData(pfrom, inv, connman, interruptMsgProc);
1209  }
1210  }
1211 
1212  pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1213 
1214  if (!vNotFound.empty()) {
1215  // Let the peer know that we didn't find what it asked for, so it doesn't
1216  // have to wait around forever. Currently only SPV clients actually care
1217  // about this message: it's needed when they are recursively walking the
1218  // dependencies of relevant unconfirmed transactions. SPV clients want to
1219  // do that because they want to know about (and store and rebroadcast and
1220  // risk analyze) the dependencies of transactions relevant to them, without
1221  // having to download the entire memory pool.
1222  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1223  }
1224 }
1225 
1226 bool fRequestedSporksIDB = false;
1227 bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv, int64_t nTimeReceived, CConnman* connman, std::atomic<bool>& interruptMsgProc)
1228 {
1229  LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1230  if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0) {
1231  LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1232  return true;
1233  }
1234 
1235  if (strCommand == NetMsgType::VERSION) {
1236  // Each connection can only send one version message
1237  if (pfrom->nVersion != 0) {
1238  LOCK(cs_main);
1239  Misbehaving(pfrom->GetId(), 1);
1240  return false;
1241  }
1242 
1243  int64_t nTime;
1244  CAddress addrMe;
1245  CAddress addrFrom;
1246  uint64_t nNonce = 1;
1247  uint64_t nServiceInt;
1248  ServiceFlags nServices;
1249  int nVersion;
1250  int nSendVersion;
1251  std::string strSubVer;
1252  std::string cleanSubVer;
1253  int nStartingHeight = -1;
1254  bool fRelay = true;
1255  vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1256  nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1257  nServices = ServiceFlags(nServiceInt);
1258  if (!pfrom->fInbound) {
1259  connman->SetServices(pfrom->addr, nServices);
1260  }
1261  if (pfrom->nServicesExpected & ~nServices) {
1262  LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, pfrom->nServicesExpected);
1263  pfrom->fDisconnect = true;
1264  return false;
1265  }
1266 
1267  if (pfrom->DisconnectOldProtocol(nVersion, ActiveProtocol())) {
1268  return false;
1269  }
1270 
1271  if (nVersion == 10300)
1272  nVersion = 300;
1273  if (!vRecv.empty())
1274  vRecv >> addrFrom >> nNonce;
1275  if (!vRecv.empty()) {
1276  vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1277  cleanSubVer = SanitizeString(strSubVer);
1278  }
1279  if (!vRecv.empty()) {
1280  vRecv >> nStartingHeight;
1281  }
1282  if (!vRecv.empty()) {
1283  vRecv >> fRelay;
1284  }
1285  // Check if this is a quorum connection
1286  if (!vRecv.empty()) {
1287  WITH_LOCK(pfrom->cs_mnauth, vRecv >> pfrom->receivedMNAuthChallenge;);
1288  bool fOtherMasternode = !pfrom->receivedMNAuthChallenge.IsNull();
1289  if (pfrom->fInbound) {
1290  pfrom->m_masternode_connection = fOtherMasternode;
1291  if (fOtherMasternode) {
1292  LogPrint(BCLog::NET, "peer=%d is an inbound masternode connection, not relaying anything to it\n", pfrom->GetId());
1293  if (!fMasterNode) { // global MN flag
1294  LogPrint(BCLog::NET, "but we're not a masternode, disconnecting\n");
1295  pfrom->fDisconnect = true;
1296  return true;
1297  }
1298  }
1299  }
1300  }
1301 
1302  // Disconnect if we connected to ourself
1303  if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce)) {
1304  LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1305  pfrom->fDisconnect = true;
1306  return true;
1307  }
1308 
1309  if (pfrom->fInbound && addrMe.IsRoutable()) {
1310  SeenLocal(addrMe);
1311  }
1312 
1313  // Be shy and don't send version until we hear
1314  if (pfrom->fInbound)
1315  PushNodeVersion(pfrom, connman, GetAdjustedTime());
1316 
1317  CNetMsgMaker msg_maker(INIT_PROTO_VERSION);
1318 
1319  if (nVersion >= 70923) {
1320  // BIP155 defines addrv2 and sendaddrv2 for all protocol versions, but some
1321  // implementations reject messages they don't know. As a courtesy, don't send
1322  // it to nodes with a version before 70923 (v5.2.99), as no software is known to support
1323  // BIP155 that doesn't announce at least that protocol version number.
1324 
1325  connman->PushMessage(pfrom, msg_maker.Make(NetMsgType::SENDADDRV2));
1326  }
1327 
1328  connman->PushMessage(pfrom, msg_maker.Make(NetMsgType::VERACK));
1329 
1330  pfrom->nServices = nServices;
1331  pfrom->SetAddrLocal(addrMe);
1332  {
1333  LOCK(pfrom->cs_SubVer);
1334  pfrom->strSubVer = strSubVer;
1335  pfrom->cleanSubVer = cleanSubVer;
1336  }
1337  pfrom->nStartingHeight = nStartingHeight;
1338  pfrom->fClient = !(nServices & NODE_NETWORK);
1339 
1340  {
1341  LOCK(pfrom->cs_filter);
1342  pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1343  }
1344 
1345  // Change version
1346  pfrom->SetSendVersion(nSendVersion);
1347  pfrom->nVersion = nVersion;
1348 
1349  {
1350  LOCK(cs_main);
1351  // Potentially mark this peer as a preferred download peer.
1352  UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1353  }
1354 
1355  if (!pfrom->fInbound) {
1356  // Advertise our address
1357  if (fListen && !IsInitialBlockDownload()) {
1358  CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1359  FastRandomContext insecure_rand;
1360  if (addr.IsRoutable()) {
1361  LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString());
1362  pfrom->PushAddress(addr, insecure_rand);
1363  } else if (IsPeerAddrLocalGood(pfrom)) {
1364  addr.SetIP(addrMe);
1365  LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString());
1366  pfrom->PushAddress(addr, insecure_rand);
1367  }
1368  }
1369 
1370  // Get recent addresses
1371  connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1372  pfrom->fGetAddr = true;
1373  // When requesting a getaddr, accept an additional MAX_ADDR_TO_SEND addresses in response
1374  // (bypassing the MAX_ADDR_PROCESSING_TOKEN_BUCKET limit).
1375  pfrom->m_addr_token_bucket += MAX_ADDR_TO_SEND;
1376  connman->MarkAddressGood(pfrom->addr);
1377  }
1378 
1379  std::string remoteAddr;
1380  if (fLogIPs)
1381  remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1382 
1383  LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1384  cleanSubVer, pfrom->nVersion,
1385  pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1386  remoteAddr);
1387 
1388  int64_t nTimeOffset = nTime - GetTime();
1389  pfrom->nTimeOffset = nTimeOffset;
1390  const int nTimeSlotLength = Params().GetConsensus().nTimeSlotLength;
1391  if (abs64(nTimeOffset) < 2 * nTimeSlotLength) {
1392  AddTimeData(pfrom->addr, nTimeOffset, nTimeSlotLength);
1393  } else {
1394  LogPrintf("timeOffset (%d seconds) too large. Disconnecting node %s\n",
1395  nTimeOffset, pfrom->addr.ToString().c_str());
1396  pfrom->fDisconnect = true;
1398  }
1399 
1400  // Feeler connections exist only to verify if address is online.
1401  if (pfrom->fFeeler) {
1402  assert(pfrom->fInbound == false);
1403  pfrom->fDisconnect = true;
1404  }
1405 
1406  // PIVX: We use certain sporks during IBD, so check to see if they are
1407  // available. If not, ask the first peer connected for them.
1408  // TODO: Move this to an instant broadcast of the sporks.
1409  bool fMissingSporks = !pSporkDB->SporkExists(SPORK_14_NEW_PROTOCOL_ENFORCEMENT) ||
1411  !pSporkDB->SporkExists(SPORK_19_COLDSTAKING_MAINTENANCE) ||
1412  !pSporkDB->SporkExists(SPORK_20_SAPLING_MAINTENANCE);
1413 
1414  if (fMissingSporks || !fRequestedSporksIDB){
1415  LogPrintf("asking peer for sporks\n");
1416  connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETSPORKS));
1417  fRequestedSporksIDB = true;
1418  }
1419 
1420  return true;
1421  }
1422 
1423 
1424  else if (pfrom->nVersion == 0) {
1425  // Must have a version message before anything else
1426  LOCK(cs_main);
1427  Misbehaving(pfrom->GetId(), 1);
1428  return false;
1429  }
1430 
1431  // At this point, the outgoing message serialization version can't change.
1432  CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1433 
1434  if (strCommand == NetMsgType::VERACK) {
1435  pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1436 
1437  if (!pfrom->fInbound) {
1438  // Mark this node as currently connected, so we update its timestamp later.
1439  LOCK(cs_main);
1440  State(pfrom->GetId())->fCurrentlyConnected = true;
1441  }
1442 
1443  if (pfrom->nVersion >= MNAUTH_NODE_VER_VERSION && !pfrom->m_masternode_probe_connection) {
1444  // Only relayed if this is a mn connection
1445  CMNAuth::PushMNAUTH(pfrom, *connman);
1446  }
1447 
1448  pfrom->fSuccessfullyConnected = true;
1449  LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n",
1450  pfrom->nVersion.load(), pfrom->nStartingHeight, pfrom->GetId(),
1451  (fLogIPs ? strprintf(", peeraddr=%s", pfrom->addr.ToString()) : ""));
1452  return true;
1453  }
1454 
1455  else if (strCommand == NetMsgType::SENDADDRV2) {
1456  pfrom->m_wants_addrv2 = true;
1457  return true;
1458  }
1459 
1460  else if (!pfrom->fSuccessfullyConnected)
1461  {
1462  // Must have a verack message before anything else
1463  LOCK(cs_main);
1464  Misbehaving(pfrom->GetId(), 1);
1465  return false;
1466  }
1467 
1468  else if (strCommand == NetMsgType::QSENDRECSIGS) {
1469  bool b;
1470  vRecv >> b;
1471  if (pfrom->m_wants_recsigs == b) return true;
1472  // Only accept recsigs messages every 20 min to prevent spam.
1473  int64_t nNow = GetAdjustedTime();
1474  if (pfrom->m_last_wants_recsigs_recv > 0 &&
1475  nNow - pfrom->m_last_wants_recsigs_recv < 20 * 60) {
1476  LOCK(cs_main);
1477  Misbehaving(pfrom->GetId(), 20, "sendrecssigs msg is only accepted every 20 minutes");
1478  return false;
1479  }
1480  pfrom->m_wants_recsigs = b;
1481  pfrom->m_last_wants_recsigs_recv = nNow;
1482  // Check if this is a iqr connection, and update the value
1483  // if we haven't updated the connection during:
1484  // (1) the relay quorum set function call, and (2) the verack receive.
1485  connman->UpdateQuorumRelayMemberIfNeeded(pfrom);
1486  return true;
1487  }
1488 
1489  if (strCommand != NetMsgType::GETSPORKS &&
1490  strCommand != NetMsgType::SPORK &&
1491  !pfrom->fFirstMessageReceived.exchange(true)) {
1492  // First message after VERSION/VERACK (without counting the GETSPORKS/SPORK messages)
1493  pfrom->fFirstMessageReceived = true;
1494  pfrom->fFirstMessageIsMNAUTH = strCommand == NetMsgType::MNAUTH;
1495  if (pfrom->m_masternode_probe_connection && !pfrom->fFirstMessageIsMNAUTH) {
1496  LogPrint(BCLog::NET, "masternode probe connection first received message is not a MNAUTH, disconnecting peer=%d\n", pfrom->GetId());
1497  pfrom->fDisconnect = true;
1498  return false;
1499  }
1500  }
1501 
1502  if (strCommand == NetMsgType::ADDR || strCommand == NetMsgType::ADDRV2) {
1503  int stream_version = vRecv.GetVersion();
1504  if (strCommand == NetMsgType::ADDRV2) {
1505  // Add ADDRV2_FORMAT to the version so that the CNetAddr and CAddress
1506  // unserialize methods know that an address in v2 format is coming.
1507  stream_version |= ADDRV2_FORMAT;
1508  }
1509 
1510  OverrideStream<CDataStream> s(&vRecv, vRecv.GetType(), stream_version);
1511  std::vector<CAddress> vAddr;
1512  s >> vAddr;
1513 
1514  if (vAddr.size() > MAX_ADDR_TO_SEND) {
1515  LOCK(cs_main);
1516  Misbehaving(pfrom->GetId(), 20, strprintf("%s message size = %u", strCommand, vAddr.size()));
1517  return false;
1518  }
1519 
1520  // Store the new addresses
1521  std::vector<CAddress> vAddrOk;
1522  int64_t nNow = GetAdjustedTime();
1523  int64_t nSince = nNow - 10 * 60;
1524 
1525  // Update/increment addr rate limiting bucket.
1526  // TODO: Slight time improvement calculation, continue backporting
1527  const auto current_time = GetTime<std::chrono::microseconds>();
1528  if (pfrom->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
1529  // Don't increment bucket if it's already full
1530  const auto time_diff = std::max(current_time - pfrom->m_addr_token_timestamp, 0us);
1531  const double increment = CountSecondsDouble(time_diff) * MAX_ADDR_RATE_PER_SECOND;
1532  pfrom->m_addr_token_bucket = std::min<double>(pfrom->m_addr_token_bucket + increment, MAX_ADDR_PROCESSING_TOKEN_BUCKET);
1533  }
1534  pfrom->m_addr_token_timestamp = current_time;
1535 
1536  uint64_t num_proc = 0;
1537  uint64_t num_rate_limit = 0;
1538  Shuffle(vAddr.begin(), vAddr.end(), FastRandomContext());
1539 
1540  for (CAddress& addr : vAddr) {
1541  if (interruptMsgProc)
1542  return true;
1543 
1544  // Apply rate limiting.
1545  if (pfrom->m_addr_token_bucket < 1.0) {
1546  ++num_rate_limit;
1547  continue;
1548  } else {
1549  pfrom->m_addr_token_bucket -= 1.0;
1550  }
1551 
1552  if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1553  continue;
1554 
1555  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1556  addr.nTime = nNow - 5 * 24 * 60 * 60;
1557  pfrom->AddAddressKnown(addr);
1558  if (connman->IsBanned(addr)) continue; // Do not process banned addresses beyond remembering we received them
1559  ++num_proc;
1560  bool fReachable = IsReachable(addr);
1561  if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) {
1562  // Relay to a limited number of other nodes
1563  RelayAddress(addr, fReachable, connman);
1564  }
1565  // Do not store addresses outside our network
1566  if (fReachable)
1567  vAddrOk.push_back(addr);
1568  }
1569  CNodeState* state = State(pfrom->GetId());
1570  state->amt_addr_processed += num_proc;
1571  state->amt_addr_rate_limited += num_rate_limit;
1572  LogPrint(BCLog::NET, "Received addr: %u addresses (%u processed, %u rate-limited) from peer=%d\n",
1573  vAddr.size(), num_proc, num_rate_limit, pfrom->GetId());
1574  connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1575  if (vAddr.size() < 1000)
1576  pfrom->fGetAddr = false;
1577  if (pfrom->fOneShot)
1578  pfrom->fDisconnect = true;
1579  }
1580 
1581  else if (strCommand == NetMsgType::INV) {
1582  std::vector<CInv> vInv;
1583  vRecv >> vInv;
1584  if (vInv.size() > MAX_INV_SZ) {
1585  LOCK(cs_main);
1586  Misbehaving(pfrom->GetId(), 20, strprintf("message inv size() = %u", vInv.size()));
1587  return false;
1588  }
1589 
1590  LOCK(cs_main);
1591 
1592  std::vector<CInv> vToFetch;
1593 
1594  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
1595  const CInv& inv = vInv[nInv];
1596 
1597  if (interruptMsgProc)
1598  return true;
1599 
1600  // Reject deprecated messages
1601  if (inv.type == MSG_TXLOCK_REQUEST || inv.type == MSG_TXLOCK_VOTE) {
1602  Misbehaving(pfrom->GetId(), 100, strprintf("message inv deprecated %d", (int)inv.type));
1603  return false;
1604  }
1605 
1606  pfrom->AddInventoryKnown(inv);
1607 
1608  bool fAlreadyHave = AlreadyHave(inv);
1609  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1610 
1611  if (inv.type == MSG_BLOCK) {
1612  UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1613  if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1614  // Add this to the list of blocks to request
1615  vToFetch.push_back(inv);
1616  LogPrint(BCLog::NET, "getblocks (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1617  }
1618  } else {
1619  // Allowed inv request types while we are in IBD
1620  static std::set<int> allowWhileInIBDObjs = {
1621  MSG_SPORK
1622  };
1623 
1624  // Can be safely removed post v6.0.0 enforcement
1625  // Disallowed inv request
1626  static std::set<int> disallowedRequestsUntilV6 = {
1628  };
1629  if (disallowedRequestsUntilV6.count(inv.type) &&
1630  !deterministicMNManager->IsDIP3Enforced()) {
1631  continue; // Move to next inv
1632  }
1633 
1634  // If we don't have it, check if we should ask for it now or
1635  // wait until we are sync
1636  if (!fAlreadyHave) {
1637  bool allowWhileInIBD = allowWhileInIBDObjs.count(inv.type);
1638  if (allowWhileInIBD || !IsInitialBlockDownload()) {
1639  int64_t doubleRequestDelay = 2 * 60 * 1000000;
1640  // some messages need to be re-requested faster when the first announcing peer did not answer to GETDATA
1641  switch (inv.type) {
1643  doubleRequestDelay = 5 * 1000000;
1644  break;
1645  case MSG_CLSIG:
1646  doubleRequestDelay = 5 * 1000000;
1647  break;
1648  }
1649  pfrom->AskFor(inv, doubleRequestDelay);
1650  }
1651  }
1652  }
1653 
1654  }
1655 
1656  if (!vToFetch.empty())
1657  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vToFetch));
1658  }
1659 
1660 
1661  else if (strCommand == NetMsgType::GETDATA) {
1662  std::vector<CInv> vInv;
1663  vRecv >> vInv;
1664  if (vInv.size() > MAX_INV_SZ) {
1665  LOCK(cs_main);
1666  Misbehaving(pfrom->GetId(), 20, strprintf("message getdata size() = %u", vInv.size()));
1667  return false;
1668  }
1669 
1670  if (vInv.size() != 1)
1671  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1672 
1673  if (vInv.size() > 0)
1674  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1675 
1676  pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1677  ProcessGetData(pfrom, connman, interruptMsgProc);
1678  }
1679 
1680 
1681  else if (strCommand == NetMsgType::GETBLOCKS || strCommand == NetMsgType::GETHEADERS) {
1682 
1683  // Don't relay blocks inv to masternode-only connections
1684  if (!pfrom->CanRelay()) {
1685  LogPrint(BCLog::NET, "getblocks, don't relay blocks inv to masternode connection. peer=%d\n", pfrom->GetId());
1686  return true;
1687  }
1688 
1689  CBlockLocator locator;
1690  uint256 hashStop;
1691  vRecv >> locator >> hashStop;
1692 
1693  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
1694  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
1695  pfrom->fDisconnect = true;
1696  return true;
1697  }
1698 
1699  LOCK(cs_main);
1700 
1701  // Find the last block the caller has in the main chain
1702  CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1703 
1704  // Send the rest of the chain
1705  if (pindex)
1706  pindex = chainActive.Next(pindex);
1707  int nLimit = 500;
1708  LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->GetId());
1709  for (; pindex; pindex = chainActive.Next(pindex)) {
1710  if (pindex->GetBlockHash() == hashStop) {
1711  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1712  break;
1713  }
1714  pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1715  if (--nLimit <= 0) {
1716  // When this block is requested, we'll send an inv that'll make them
1717  // getblocks the next batch of inventory.
1718  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1719  pfrom->hashContinue = pindex->GetBlockHash();
1720  break;
1721  }
1722  }
1723  }
1724 
1725 
1726  else if (strCommand == NetMsgType::HEADERS && Params().HeadersFirstSyncingActive()) {
1727  CBlockLocator locator;
1728  uint256 hashStop;
1729  vRecv >> locator >> hashStop;
1730 
1731  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
1732  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
1733  pfrom->fDisconnect = true;
1734  return true;
1735  }
1736 
1737  LOCK(cs_main);
1738 
1739  if (IsInitialBlockDownload())
1740  return true;
1741 
1742  CBlockIndex* pindex = nullptr;
1743  if (locator.IsNull()) {
1744  // If locator is null, return the hashStop block
1745  CBlockIndex* pindex = LookupBlockIndex(hashStop);
1746  if (!pindex)
1747  return true;
1748  } else {
1749  // Find the last block the caller has in the main chain
1750  pindex = FindForkInGlobalIndex(chainActive, locator);
1751  if (pindex)
1752  pindex = chainActive.Next(pindex);
1753  }
1754 
1755  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1756  std::vector<CBlock> vHeaders;
1757  int nLimit = MAX_HEADERS_RESULTS;
1758  LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->GetId());
1759  for (; pindex; pindex = chainActive.Next(pindex)) {
1760  vHeaders.push_back(pindex->GetBlockHeader());
1761  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
1762  break;
1763  }
1764  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
1765  }
1766 
1767 
1768  else if (strCommand == NetMsgType::TX) {
1769  std::deque<COutPoint> vWorkQueue;
1770  std::vector<uint256> vEraseQueue;
1771  CTransaction tx(deserialize, vRecv);
1772  CTransactionRef ptx = MakeTransactionRef(tx);
1773 
1774  CInv inv(MSG_TX, tx.GetHash());
1775  pfrom->AddInventoryKnown(inv);
1776 
1778 
1779  bool ignoreFees = false;
1780  bool fMissingInputs = false;
1781  CValidationState state;
1782 
1783  pfrom->setAskFor.erase(inv.hash);
1784  mapAlreadyAskedFor.erase(inv);
1785 
1786  if (ptx->ContainsZerocoins()) {
1787  // Don't even try to check zerocoins at all.
1788  Misbehaving(pfrom->GetId(), 100, strprintf("received a zc transaction"));
1789  return false;
1790  }
1791 
1792  if (AcceptToMemoryPool(mempool, state, ptx, true, &fMissingInputs, false, ignoreFees)) {
1793  mempool.check(pcoinsTip.get());
1794  RelayTransaction(tx, connman);
1795  for (unsigned int i = 0; i < tx.vout.size(); i++) {
1796  vWorkQueue.emplace_back(inv.hash, i);
1797  }
1798 
1799  LogPrint(BCLog::MEMPOOL, "%s : peer=%d %s : accepted %s (poolsz %u txn, %u kB)\n",
1800  __func__, pfrom->GetId(), pfrom->cleanSubVer, tx.GetHash().ToString(),
1801  mempool.size(), mempool.DynamicMemoryUsage() / 1000);
1802 
1803  // Recursively process any orphan transactions that depended on this one
1804  std::set<NodeId> setMisbehaving;
1805  while (!vWorkQueue.empty()) {
1806  auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
1807  vWorkQueue.pop_front();
1808  if(itByPrev == mapOrphanTransactionsByPrev.end())
1809  continue;
1810  for (auto mi = itByPrev->second.begin();
1811  mi != itByPrev->second.end();
1812  ++mi) {
1813  const CTransactionRef& orphanTx = (*mi)->second.tx;
1814  const uint256& orphanHash = orphanTx->GetHash();
1815  NodeId fromPeer = (*mi)->second.fromPeer;
1816  bool fMissingInputs2 = false;
1817  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1818  // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1819  // anyone relaying LegitTxX banned)
1820  CValidationState stateDummy;
1821 
1822 
1823  if (setMisbehaving.count(fromPeer))
1824  continue;
1825  if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
1826  LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
1827  RelayTransaction(*orphanTx, connman);
1828  for (unsigned int i = 0; i < orphanTx->vout.size(); i++) {
1829  vWorkQueue.emplace_back(orphanHash, i);
1830  }
1831  vEraseQueue.push_back(orphanHash);
1832  } else if (!fMissingInputs2) {
1833  int nDos = 0;
1834  if(stateDummy.IsInvalid(nDos) && nDos > 0) {
1835  // Punish peer that gave us an invalid orphan tx
1836  Misbehaving(fromPeer, nDos);
1837  setMisbehaving.insert(fromPeer);
1838  LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
1839  }
1840  // Has inputs but not accepted to mempool
1841  // Probably non-standard or insufficient fee
1842  LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
1843  vEraseQueue.push_back(orphanHash);
1844  assert(recentRejects);
1845  recentRejects->insert(orphanHash);
1846  }
1847  mempool.check(pcoinsTip.get());
1848  }
1849  }
1850 
1851  for (uint256& hash : vEraseQueue) EraseOrphanTx(hash);
1852 
1853  } else if (fMissingInputs) {
1854  bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
1855 
1856  // Deduplicate parent txids, so that we don't have to loop over
1857  // the same parent txid more than once down below.
1858  std::vector<uint256> unique_parents;
1859  unique_parents.reserve(tx.vin.size());
1860  for (const CTxIn& txin : ptx->vin) {
1861  // We start with all parents, and then remove duplicates below.
1862  unique_parents.emplace_back(txin.prevout.hash);
1863  }
1864  std::sort(unique_parents.begin(), unique_parents.end());
1865  unique_parents.erase(std::unique(unique_parents.begin(), unique_parents.end()), unique_parents.end());
1866  for (const uint256& parent_txid : unique_parents) {
1867  if (recentRejects->contains(parent_txid)) {
1868  fRejectedParents = true;
1869  break;
1870  }
1871  }
1872  if (!fRejectedParents) {
1873  for (const uint256& parent_txid : unique_parents) {
1874  CInv _inv(MSG_TX, parent_txid);
1875  pfrom->AddInventoryKnown(_inv);
1876  if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
1877  }
1878  AddOrphanTx(ptx, pfrom->GetId());
1879 
1880  // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1881  unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
1882  unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
1883  if (nEvicted > 0)
1884  LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
1885  } else {
1886  LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
1887  }
1888  } else {
1889  // AcceptToMemoryPool() returned false, possibly because the tx is
1890  // already in the mempool; if the tx isn't in the mempool that
1891  // means it was rejected and we shouldn't ask for it again.
1892  if (!mempool.exists(tx.GetHash())) {
1893  assert(recentRejects);
1894  recentRejects->insert(tx.GetHash());
1895  }
1896  if (pfrom->fWhitelisted) {
1897  // Always relay transactions received from whitelisted peers, even
1898  // if they were rejected from the mempool, allowing the node to
1899  // function as a gateway for nodes hidden behind it.
1900  //
1901  // FIXME: This includes invalid transactions, which means a
1902  // whitelisted peer could get us banned! We may want to change
1903  // that.
1904  RelayTransaction(tx, connman);
1905  }
1906  }
1907 
1908  int nDoS = 0;
1909  if (state.IsInvalid(nDoS)) {
1910  LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
1911  pfrom->GetId(), pfrom->cleanSubVer,
1912  FormatStateMessage(state));
1913  if (nDoS > 0) {
1914  Misbehaving(pfrom->GetId(), nDoS);
1915  }
1916  }
1917  }
1918 
1919  else if (strCommand == NetMsgType::HEADERS && Params().HeadersFirstSyncingActive() && !fImporting && !fReindex) // Ignore headers received while importing
1920  {
1921  std::vector<CBlockHeader> headers;
1922 
1923  // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
1924  unsigned int nCount = ReadCompactSize(vRecv);
1925  if (nCount > MAX_HEADERS_RESULTS) {
1926  LOCK(cs_main);
1927  Misbehaving(pfrom->GetId(), 20, strprintf("headers message size = %u", nCount));
1928  return false;
1929  }
1930  headers.resize(nCount);
1931  for (unsigned int n = 0; n < nCount; n++) {
1932  vRecv >> headers[n];
1933  ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
1934  }
1935 
1936  LOCK(cs_main);
1937 
1938  if (nCount == 0) {
1939  // Nothing interesting. Stop asking this peers for more headers.
1940  return true;
1941  }
1942  CBlockIndex* pindexLast = nullptr;
1943  for (const CBlockHeader& header : headers) {
1944  CValidationState state;
1945  if (pindexLast && header.hashPrevBlock != pindexLast->GetBlockHash()) {
1946  Misbehaving(pfrom->GetId(), 20, "non-continuous headers sequence");
1947  return false;
1948  }
1949 
1950  /*TODO: this has a CBlock cast on it so that it will compile. There should be a solution for this
1951  * before headers are reimplemented on mainnet
1952  */
1953  if (!AcceptBlockHeader((CBlock)header, state, &pindexLast)) {
1954  int nDoS;
1955  if (state.IsInvalid(nDoS)) {
1956  if (nDoS > 0) {
1957  Misbehaving(pfrom->GetId(), nDoS, "invalid header received");
1958  } else {
1959  LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId());
1960  }
1961  return false;
1962  }
1963  }
1964  }
1965 
1966  if (pindexLast)
1967  UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1968 
1969  if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
1970  // Headers message had its maximum size; the peer may have more headers.
1971  // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1972  // from there instead.
1973  LogPrintf("more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1974  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), UINT256_ZERO));
1975  }
1976  }
1977 
1978  else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
1979  {
1980  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
1981  vRecv >> *pblock;
1982  const uint256& hashBlock = pblock->GetHash();
1983  CInv inv(MSG_BLOCK, hashBlock);
1984  LogPrint(BCLog::NET, "received block %s peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1985 
1986  // sometimes we will be sent their most recent block and its not the one we want, in that case tell where we are
1987  if (!mapBlockIndex.count(pblock->hashPrevBlock)) {
1988  CBlockLocator locator = WITH_LOCK(cs_main, return chainActive.GetLocator(););
1989  if (find(pfrom->vBlockRequested.begin(), pfrom->vBlockRequested.end(), hashBlock) != pfrom->vBlockRequested.end()) {
1990  // we already asked for this block, so lets work backwards and ask for the previous block
1991  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKS, locator, pblock->hashPrevBlock));
1992  pfrom->vBlockRequested.emplace_back(pblock->hashPrevBlock);
1993  } else {
1994  // ask to sync to this block
1995  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKS, locator, hashBlock));
1996  pfrom->vBlockRequested.emplace_back(hashBlock);
1997  }
1998  } else {
1999  pfrom->AddInventoryKnown(inv);
2000  if (!mapBlockIndex.count(hashBlock)) {
2001  {
2002  LOCK(cs_main);
2003  MarkBlockAsReceived(hashBlock);
2004  mapBlockSource.emplace(hashBlock, pfrom->GetId());
2005  }
2006  ProcessNewBlock(pblock, nullptr);
2007 
2008  // Disconnect node if its running an old protocol version,
2009  // used during upgrades, when the node is already connected.
2010  pfrom->DisconnectOldProtocol(pfrom->nVersion, ActiveProtocol());
2011  } else {
2012  LogPrint(BCLog::NET, "%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__, pblock->GetHash().GetHex());
2013  }
2014  }
2015  }
2016 
2017  // This asymmetric behavior for inbound and outbound connections was introduced
2018  // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2019  // to users' AddrMan and later request them by sending getaddr messages.
2020  // Making users (which are behind NAT and can only make outgoing connections) ignore
2021  // getaddr message mitigates the attack.
2022  else if ((strCommand == NetMsgType::GETADDR) && (pfrom->fInbound)) {
2023  pfrom->vAddrToSend.clear();
2024  std::vector<CAddress> vAddr = connman->GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND, /* network */ nullopt);
2025  FastRandomContext insecure_rand;
2026  for (const CAddress& addr : vAddr) {
2027  if (!connman->IsBanned(addr)) {
2028  pfrom->PushAddress(addr, insecure_rand);
2029  }
2030  }
2031  }
2032 
2033 
2034  else if (strCommand == NetMsgType::MEMPOOL) {
2035 
2036  if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted) {
2037  LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2038  pfrom->fDisconnect = true;
2039  return true;
2040  }
2041 
2042  // todo: limit mempool request with a bandwidth limit
2043  LOCK(pfrom->cs_inventory);
2044  pfrom->fSendMempool = true;
2045  }
2046 
2047 
2048  else if (strCommand == NetMsgType::PING) {
2049  uint64_t nonce = 0;
2050  vRecv >> nonce;
2051  // Echo the message back with the nonce. This allows for two useful features:
2052  //
2053  // 1) A remote node can quickly check if the connection is operational
2054  // 2) Remote nodes can measure the latency of the network thread. If this node
2055  // is overloaded it won't respond to pings quickly and the remote node can
2056  // avoid sending us more work, like chain download requests.
2057  //
2058  // The nonce stops the remote getting confused between different pings: without
2059  // it, if the remote node sends a ping once per second and this node takes 5
2060  // seconds to respond to each, the 5th ping the remote sends would appear to
2061  // return very quickly.
2062  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2063  }
2064 
2065 
2066  else if (strCommand == NetMsgType::PONG) {
2067  int64_t pingUsecEnd = nTimeReceived;
2068  uint64_t nonce = 0;
2069  size_t nAvail = vRecv.in_avail();
2070  bool bPingFinished = false;
2071  std::string sProblem;
2072 
2073  if (nAvail >= sizeof(nonce)) {
2074  vRecv >> nonce;
2075 
2076  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2077  if (pfrom->nPingNonceSent != 0) {
2078  if (nonce == pfrom->nPingNonceSent) {
2079  // Matching pong received, this ping is no longer outstanding
2080  bPingFinished = true;
2081  int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2082  if (pingUsecTime > 0) {
2083  // Successful ping time measurement, replace previous
2084  pfrom->nPingUsecTime = pingUsecTime;
2085  pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2086  } else {
2087  // This should never happen
2088  sProblem = "Timing mishap";
2089  }
2090  } else {
2091  // Nonce mismatches are normal when pings are overlapping
2092  sProblem = "Nonce mismatch";
2093  if (nonce == 0) {
2094  // This is most likely a bug in another implementation somewhere, cancel this ping
2095  bPingFinished = true;
2096  sProblem = "Nonce zero";
2097  }
2098  }
2099  } else {
2100  sProblem = "Unsolicited pong without ping";
2101  }
2102  } else {
2103  // This is most likely a bug in another implementation somewhere, cancel this ping
2104  bPingFinished = true;
2105  sProblem = "Short payload";
2106  }
2107 
2108  if (!(sProblem.empty())) {
2109  LogPrint(BCLog::NET, "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
2110  pfrom->GetId(),
2111  pfrom->cleanSubVer,
2112  sProblem,
2113  pfrom->nPingNonceSent,
2114  nonce,
2115  nAvail);
2116  }
2117  if (bPingFinished) {
2118  pfrom->nPingNonceSent = 0;
2119  }
2120  }
2121 
2122  else if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
2123  (strCommand == NetMsgType::FILTERLOAD ||
2124  strCommand == NetMsgType::FILTERADD ||
2125  strCommand == NetMsgType::FILTERCLEAR)) {
2126  LOCK(cs_main);
2127  Misbehaving(pfrom->GetId(), 100, "banning, filter received.");
2128  return false;
2129  }
2130 
2131  else if (strCommand == NetMsgType::FILTERLOAD) {
2132  CBloomFilter filter;
2133  vRecv >> filter;
2134 
2135  LOCK(pfrom->cs_filter);
2136 
2137  if (!filter.IsWithinSizeConstraints()) {
2138  // There is no excuse for sending a too-large filter
2139  LOCK(cs_main);
2140  Misbehaving(pfrom->GetId(), 100);
2141  } else {
2142  pfrom->pfilter.reset(new CBloomFilter(filter));
2143  pfrom->pfilter->UpdateEmptyFull();
2144  pfrom->fRelayTxes = true;
2145  }
2146  }
2147 
2148 
2149  else if (strCommand == NetMsgType::FILTERADD) {
2150  std::vector<unsigned char> vData;
2151  vRecv >> vData;
2152 
2153  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2154  // and thus, the maximum size any matched object can have) in a filteradd message
2155  bool bad = false;
2156  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2157  bad = true;
2158  } else {
2159  LOCK(pfrom->cs_filter);
2160  if (pfrom->pfilter) {
2161  pfrom->pfilter->insert(vData);
2162  } else {
2163  bad = true;
2164  }
2165  }
2166  if (bad) {
2167  LOCK(cs_main);
2168  Misbehaving(pfrom->GetId(), 100);
2169  }
2170  }
2171 
2172 
2173  else if (strCommand == NetMsgType::FILTERCLEAR) {
2174  LOCK(pfrom->cs_filter);
2175  pfrom->pfilter.reset(new CBloomFilter());
2176  pfrom->fRelayTxes = true;
2177  }
2178 
2179  else if (strCommand == NetMsgType::NOTFOUND) {
2180  // We do not care about the NOTFOUND message (for now), but logging an Unknown Command
2181  // message is undesirable as we transmit it ourselves.
2182  return true;
2183  }
2184 
2185  else {
2186  // Tier two msg type search
2187  const std::vector<std::string>& allMessages = getTierTwoNetMessageTypes();
2188  if (std::find(allMessages.begin(), allMessages.end(), strCommand) != allMessages.end()) {
2189  // Check if the dispatcher can process this message first. If not, try going with the old flow.
2190  if (!masternodeSync.MessageDispatcher(pfrom, strCommand, vRecv)) {
2191  // Probably one the extensions, future: encapsulate all of this inside tiertwo_networksync.
2192  int dosScore{0};
2193  if (!mnodeman.ProcessMessage(pfrom, strCommand, vRecv, dosScore)) {
2194  WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), dosScore));
2195  return false;
2196  }
2197  if (!g_budgetman.ProcessMessage(pfrom, strCommand, vRecv, dosScore)) {
2198  WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), dosScore));
2199  return false;
2200  }
2201  CValidationState state_payments;
2202  if (!masternodePayments.ProcessMessageMasternodePayments(pfrom, strCommand, vRecv, state_payments)) {
2203  if (state_payments.IsInvalid(dosScore)) {
2204  WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), dosScore));
2205  }
2206  return false;
2207  }
2208  if (!sporkManager.ProcessSpork(pfrom, strCommand, vRecv, dosScore)) {
2209  WITH_LOCK(cs_main, Misbehaving(pfrom->GetId(), dosScore));
2210  return false;
2211  }
2212 
2213  CValidationState mnauthState;
2214  if (!CMNAuth::ProcessMessage(pfrom, strCommand, vRecv, *connman, mnauthState)) {
2215  int dosScore{0};
2216  if (mnauthState.IsInvalid(dosScore) && dosScore > 0) {
2217  LOCK(cs_main);
2218  Misbehaving(pfrom->GetId(), dosScore, mnauthState.GetRejectReason());
2219  }
2220  }
2221  }
2222  } else {
2223  // Ignore unknown commands for extensibility
2224  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2225  }
2226  }
2227 
2228  return true;
2229 }
2230 
2231 static bool DisconnectIfBanned(CNode* pnode, CConnman* connman)
2232 {
2234  CNodeState &state = *State(pnode->GetId());
2235 
2236  if (state.fShouldBan) {
2237  state.fShouldBan = false;
2238  if (pnode->fWhitelisted) {
2239  LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2240  } else if (pnode->fAddnode) {
2241  LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode->addr.ToString());
2242  } else {
2243  pnode->fDisconnect = true;
2244  if (pnode->addr.IsLocal()) {
2245  LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2246  } else {
2247  connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2248  }
2249  }
2250  return true;
2251  }
2252  return false;
2253 }
2254 
2255 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2256 {
2257  // Message format
2258  // (4) message start
2259  // (12) command
2260  // (4) size
2261  // (4) checksum
2262  // (x) data
2263  //
2264  bool fMoreWork = false;
2265 
2266  if (!pfrom->vRecvGetData.empty())
2267  ProcessGetData(pfrom, connman, interruptMsgProc);
2268 
2269  if (pfrom->fDisconnect)
2270  return false;
2271 
2272  // this maintains the order of responses
2273  if (!pfrom->vRecvGetData.empty()) return true;
2274 
2275  // Don't bother if send buffer is too full to respond anyway
2276  if (pfrom->fPauseSend)
2277  return false;
2278 
2279  std::list<CNetMessage> msgs;
2280  {
2281  LOCK(pfrom->cs_vProcessMsg);
2282  if (pfrom->vProcessMsg.empty())
2283  return false;
2284  // Just take one message
2285  msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2286  pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2288  fMoreWork = !pfrom->vProcessMsg.empty();
2289  }
2290  CNetMessage& msg(msgs.front());
2291 
2292  msg.SetVersion(pfrom->GetRecvVersion());
2293  // Scan for message start
2294  if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2295  LogPrint(BCLog::NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2296  pfrom->fDisconnect = true;
2297  return false;
2298  }
2299 
2300  // Read header
2301  CMessageHeader& hdr = msg.hdr;
2302  if (!hdr.IsValid(Params().MessageStart())) {
2303  LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER '%s' peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2304  return fMoreWork;
2305  }
2306  std::string strCommand = hdr.GetCommand();
2307 
2308  // Message size
2309  unsigned int nMessageSize = hdr.nMessageSize;
2310 
2311  // Checksum
2312  CDataStream& vRecv = msg.vRecv;
2313  uint256 hash = msg.GetMessageHash();
2314  if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2315  {
2316  LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2317  SanitizeString(strCommand), nMessageSize,
2319  HexStr(hdr.pchChecksum));
2320  return fMoreWork;
2321  }
2322 
2323  // Process message
2324  bool fRet = false;
2325  try {
2326  fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, connman, interruptMsgProc);
2327  if (interruptMsgProc)
2328  return false;
2329  if (!pfrom->vRecvGetData.empty())
2330  fMoreWork = true;
2331  } catch (const std::ios_base::failure& e) {
2332  if (strstr(e.what(), "end of data")) {
2333  // Allow exceptions from under-length message on vRecv
2334  LogPrint(BCLog::NET, "ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
2335  } else if (strstr(e.what(), "size too large")) {
2336  // Allow exceptions from over-long size
2337  LogPrint(BCLog::NET, "ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
2338  } else {
2339  PrintExceptionContinue(&e, "ProcessMessages()");
2340  }
2341  } catch (const std::exception& e) {
2342  PrintExceptionContinue(&e, "ProcessMessages()");
2343  } catch (...) {
2344  PrintExceptionContinue(nullptr, "ProcessMessages()");
2345  }
2346 
2347  if (!fRet) {
2348  LogPrint(BCLog::NET, "ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize,
2349  pfrom->GetId());
2350  }
2351 
2352  LOCK(cs_main);
2353  DisconnectIfBanned(pfrom, connman);
2354 
2355  return fMoreWork;
2356 }
2357 
2359 {
2361 public:
2363  {
2364  mp = _mempool;
2365  }
2366 
2367  bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
2368  {
2369  /* As std::make_heap produces a max-heap, we want the entries with the
2370  * fewest ancestors/highest fee to sort later. */
2371  return mp->CompareDepthAndScore(*b, *a);
2372  }
2373 };
2374 
2375 bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
2376 {
2377  {
2378  // Don't send anything until the version handshake is complete
2379  if (!pto->fSuccessfullyConnected || pto->fDisconnect)
2380  return true;
2381 
2382  // If we get here, the outgoing message serialization version is set and can't change.
2383  CNetMsgMaker msgMaker(pto->GetSendVersion());
2384 
2385  //
2386  // Message: ping
2387  //
2388  bool pingSend = false;
2389  if (pto->fPingQueued) {
2390  // RPC ping request by user
2391  pingSend = true;
2392  }
2393  if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
2394  // Ping automatically sent as a latency probe & keepalive.
2395  pingSend = true;
2396  }
2397  if (pingSend) {
2398  uint64_t nonce = 0;
2399  while (nonce == 0) {
2400  GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
2401  }
2402  pto->fPingQueued = false;
2403  pto->nPingUsecStart = GetTimeMicros();
2404  pto->nPingNonceSent = nonce;
2405  connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
2406  }
2407 
2408  TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2409  if (!lockMain)
2410  return true;
2411 
2412  if (DisconnectIfBanned(pto, connman)) {
2413  return true;
2414  }
2415 
2416  CNodeState& state = *State(pto->GetId());
2417 
2418  // Address refresh broadcast
2419  int64_t nNow = GetTimeMicros();
2420  auto current_time = GetTime<std::chrono::microseconds>();
2421 
2422  if (!IsInitialBlockDownload() && pto->m_next_local_addr_send < current_time) {
2423  AdvertiseLocal(pto);
2424  pto->m_next_local_addr_send = PoissonNextSend(current_time, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
2425  }
2426 
2427  //
2428  // Message: addr
2429  //
2430  if (pto->m_next_addr_send < current_time) {
2431  pto->m_next_addr_send = PoissonNextSend(current_time, AVG_ADDRESS_BROADCAST_INTERVAL);
2432  std::vector<CAddress> vAddr;
2433  vAddr.reserve(pto->vAddrToSend.size());
2434 
2435  const char* msg_type;
2436  int make_flags;
2437  if (pto->m_wants_addrv2) {
2438  msg_type = NetMsgType::ADDRV2;
2439  make_flags = ADDRV2_FORMAT;
2440  } else {
2441  msg_type = NetMsgType::ADDR;
2442  make_flags = 0;
2443  }
2444 
2445  for (const CAddress& addr : pto->vAddrToSend) {
2446  if (!pto->addrKnown.contains(addr.GetKey())) {
2447  pto->addrKnown.insert(addr.GetKey());
2448  vAddr.push_back(addr);
2449  // receiver rejects addr messages larger than 1000
2450  if (vAddr.size() >= 1000) {
2451  connman->PushMessage(pto, msgMaker.Make(make_flags, msg_type, vAddr));
2452  vAddr.clear();
2453  }
2454  }
2455  }
2456  pto->vAddrToSend.clear();
2457  if (!vAddr.empty())
2458  connman->PushMessage(pto, msgMaker.Make(make_flags, msg_type, vAddr));
2459  }
2460 
2461  // Start block sync
2462  if (!pindexBestHeader)
2464  bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
2465  if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex && pto->CanRelay()) {
2466  // Only actively request headers from a single peer, unless we're close to end of initial download.
2467  if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin
2468  state.fSyncStarted = true;
2469  nSyncStarted++;
2470  //CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
2471  //LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
2472  //pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), UINT256_ZERO);
2474  }
2475  }
2476 
2477  // Resend wallet transactions that haven't gotten in a block yet
2478  // Except during reindex, importing and IBD, when old wallet
2479  // transactions become unconfirmed and spams other nodes.
2480  if (!fReindex && !fImporting && !IsInitialBlockDownload()) {
2482  }
2483 
2484  //
2485  // Message: inventory
2486  //
2487  std::vector<CInv> vInv;
2488  std::vector<CInv> vInvWait;
2489  {
2490  LOCK2(mempool.cs, pto->cs_inventory);
2491  vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size() + pto->vInventoryTierTwoToSend.size(), INVENTORY_BROADCAST_MAX));
2492 
2493  // Add blocks
2494  for (const uint256& hash : pto->vInventoryBlockToSend) {
2495  vInv.emplace_back(CInv(MSG_BLOCK, hash));
2496  if (vInv.size() == MAX_INV_SZ) {
2497  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2498  vInv.clear();
2499  }
2500  }
2501  pto->vInventoryBlockToSend.clear();
2502 
2503  // Add tier two INVs
2504  for (const CInv& tInv : pto->vInventoryTierTwoToSend) {
2505  vInv.emplace_back(tInv);
2506  if (vInv.size() == MAX_INV_SZ) {
2507  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2508  vInv.clear();
2509  }
2510  }
2511  pto->vInventoryTierTwoToSend.clear();
2512 
2513  // Check whether periodic send should happen
2514  bool fSendTrickle = pto->fWhitelisted;
2515  if (pto->nNextInvSend < current_time) {
2516  fSendTrickle = true;
2517  // Use half the delay for outbound peers, as there is less privacy concern for them.
2518  pto->nNextInvSend = PoissonNextSend(current_time, std::chrono::seconds{INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound});
2519  }
2520 
2521  // Time to send but the peer has requested we not relay transactions.
2522  if (fSendTrickle) {
2523  LOCK(pto->cs_filter);
2524  if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
2525  }
2526 
2527  // Respond to BIP35 mempool requests
2528  if (fSendTrickle && pto->fSendMempool) {
2529  auto vtxinfo = mempool.infoAll();
2530  pto->fSendMempool = false;
2531  // future: back port fee filter rate
2532  LOCK(pto->cs_filter);
2533 
2534  for (const auto& txinfo : vtxinfo) {
2535  const uint256& hash = txinfo.tx->GetHash();
2536  CInv inv(MSG_TX, hash);
2537  pto->setInventoryTxToSend.erase(hash);
2538  // future: add fee filter check here..
2539  if (pto->pfilter) {
2540  if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
2541  }
2542  pto->filterInventoryKnown.insert(hash);
2543  vInv.emplace_back(inv);
2544  if (vInv.size() == MAX_INV_SZ) {
2545  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2546  vInv.clear();
2547  }
2548  }
2549  pto->timeLastMempoolReq = GetTime();
2550  }
2551 
2552  // Determine transactions to relay
2553  if (fSendTrickle) {
2554  // Produce a vector with all candidates for sending
2555  std::vector<std::set<uint256>::iterator> vInvTx;
2556  vInvTx.reserve(pto->setInventoryTxToSend.size());
2557  for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
2558  vInvTx.push_back(it);
2559  }
2560  // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
2561  // A heap is used so that not all items need sorting if only a few are being sent.
2562  CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
2563  std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
2564  // No reason to drain out at many times the network's capacity,
2565  // especially since we have many peers and some will draw much shorter delays.
2566  unsigned int nRelayedTransactions = 0;
2567  LOCK(pto->cs_filter);
2568  while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
2569  // Fetch the top element from the heap
2570  std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
2571  std::set<uint256>::iterator it = vInvTx.back();
2572  vInvTx.pop_back();
2573  uint256 hash = *it;
2574  // Remove it from the to-be-sent set
2575  pto->setInventoryTxToSend.erase(it);
2576  // Check if not in the filter already
2577  if (pto->filterInventoryKnown.contains(hash)) {
2578  continue;
2579  }
2580  // Not in the mempool anymore? don't bother sending it.
2581  auto txinfo = mempool.info(hash);
2582  if (!txinfo.tx) {
2583  continue;
2584  }
2585  // todo: back port feerate filter.
2586  if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
2587  // Send
2588  vInv.emplace_back(CInv(MSG_TX, hash));
2589  nRelayedTransactions++;
2590  if (vInv.size() == MAX_INV_SZ) {
2591  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2592  vInv.clear();
2593  }
2594  pto->filterInventoryKnown.insert(hash);
2595  }
2596  }
2597  }
2598  if (!vInv.empty())
2599  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2600 
2601  // Detect whether we're stalling
2602  current_time = GetTime<std::chrono::microseconds>();
2603  nNow = GetTimeMicros();
2604  if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
2605  // Stalling only triggers when the block download window cannot move. During normal steady state,
2606  // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
2607  // should only happen during initial block download.
2608  LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
2609  pto->fDisconnect = true;
2610  return true;
2611  }
2612  // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
2613  // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
2614  // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
2615  // being saturated. We only count validated in-flight blocks so peers can't advertise nonexisting block hashes
2616  // to unreasonably increase our timeout.
2617  if (state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().GetConsensus().nTargetSpacing * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
2618  LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->GetId());
2619  pto->fDisconnect = true;
2620  return true;
2621  }
2622 
2623  //
2624  // Message: getdata (blocks)
2625  //
2626  std::vector<CInv> vGetData;
2627  if (!pto->fClient && pto->CanRelay() && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2628  std::vector<const CBlockIndex*> vToDownload;
2629  NodeId staller = -1;
2630  FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
2631  for (const CBlockIndex* pindex : vToDownload) {
2632  vGetData.emplace_back(MSG_BLOCK, pindex->GetBlockHash());
2633  MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
2634  LogPrintf("Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
2635  pindex->nHeight, pto->GetId());
2636  }
2637  if (state.nBlocksInFlight == 0 && staller != -1) {
2638  if (State(staller)->nStallingSince == 0) {
2639  State(staller)->nStallingSince = nNow;
2640  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
2641  }
2642  }
2643  }
2644 
2645  //
2646  // Message: getdata (non-blocks)
2647  //
2648  while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) {
2649  const CInv& inv = (*pto->mapAskFor.begin()).second;
2650  if (!AlreadyHave(inv)) {
2651  LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
2652  vGetData.push_back(inv);
2653  if (vGetData.size() >= 1000) {
2654  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2655  vGetData.clear();
2656  }
2657  } else {
2658  //If we're not going to ask, don't expect a response.
2659  pto->setAskFor.erase(inv.hash);
2660  }
2661  pto->mapAskFor.erase(pto->mapAskFor.begin());
2662  }
2663  if (!vGetData.empty())
2664  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2665  }
2666  return true;
2667 }
2668 
2670 {
2671 public:
2674  // orphan transactions
2675  mapOrphanTransactions.clear();
2676  mapOrphanTransactionsByPrev.clear();
2677  }
@ BanReasonNodeMisbehaving
Definition: addrdb.h:24
CBudgetManager g_budgetman
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:337
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:110
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:96
@ BLOCK_HAVE_DATA
Definition: chain.h:117
const CChainParams & Params()
Return the currently selected parameters.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:425
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:449
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:465
uint256 hash
Definition: transaction.h:35
A CService with information about it as peer.
Definition: protocol.h:338
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:430
uint32_t nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:428
int GetType() const
Definition: streams.h:258
bool empty() const
Definition: streams.h:166
size_type size() const
Definition: streams.h:165
int GetVersion() const
Definition: streams.h:260
int in_avail()
Definition: streams.h:255
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
uint256 GetHash() const
Definition: block.cpp:15
Definition: block.h:80
std::vector< CTransactionRef > vtx
Definition: block.h:83
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:139
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:145
CBlockHeader GetBlockHeader() const
Definition: chain.cpp:166
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:163
uint256 GetBlockHash() const
Definition: chain.h:215
int64_t GetBlockTime() const
Definition: chain.h:216
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.cpp:313
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:113
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:151
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:175
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:172
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
bool IsWithinSizeConstraints() const
True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS (c...
Definition: bloom.cpp:118
bool HaveSeenProposalVote(const uint256 &voteHash) const
Definition: budgetmanager.h:73
bool HaveProposal(const uint256 &propHash) const
Definition: budgetmanager.h:72
CDataStream GetProposalVoteSerialized(const uint256 &voteHash) const
bool ProcessMessage(CNode *pfrom, std::string &strCommand, CDataStream &vRecv, int &banScore)
bool HaveFinalizedBudget(const uint256 &budgetHash) const
Definition: budgetmanager.h:74
CDataStream GetProposalSerialized(const uint256 &propHash) const
CDataStream GetFinalizedBudgetSerialized(const uint256 &budgetHash) const
CDataStream GetFinalizedBudgetVoteSerialized(const uint256 &voteHash) const
bool HaveSeenFinalizedBudgetVote(const uint256 &voteHash) const
Definition: budgetmanager.h:75
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:441
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:405
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:27
int Height() const
Return the maximal height in the chain.
Definition: chain.h:450
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:435
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:72
Definition: net.h:145
bool AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2480
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2636
void SetBestHeight(int height)
Definition: net.cpp:2626
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:277
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2465
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, Optional< Network > network)
Return all or many randomly selected addresses, optionally by network.
Definition: net.cpp:2485
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg, bool allowOptimisticSend=DEFAULT_ALLOW_OPTIMISTIC_SEND)
Definition: net.cpp:2758
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2470
void RelayInv(CInv &inv, int minProtoVersion=ActiveProtocol())
Definition: net.cpp:2567
bool IsBanned(CNetAddr ip)
Definition: net.cpp:485
CSipHasher GetDeterministicRandomizer(uint64_t id)
Get a unique deterministic randomizer.
Definition: net.cpp:2877
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:512
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:334
void UpdateQuorumRelayMemberIfNeeded(CNode *pnode)
Update the node to be a iqr member if needed.
Definition: net.cpp:2589
void ForEachNode(Callable &&func)
Definition: net.h:257
inv message data
Definition: protocol.h:466
int type
Definition: protocol.h:479
std::string ToString() const
Definition: protocol.cpp:245
uint256 hash
Definition: protocol.h:480
static void PushMNAUTH(CNode *pnode, CConnman &connman)
Definition: mnauth.cpp:21
static bool ProcessMessage(CNode *pnode, const std::string &strCommand, CDataStream &vRecv, CConnman &connman, CValidationState &state)
Definition: mnauth.cpp:60
void Broadcast(CConnman *connman)
std::map< uint256, CMasternodeBroadcast > mapSeenMasternodeBroadcast
Definition: masternodeman.h:93
bool ProcessMessage(CNode *pfrom, std::string &strCommand, CDataStream &vRecv, int &dosScore)
std::map< uint256, CMasternodePing > mapSeenMasternodePing
Definition: masternodeman.h:95
std::map< uint256, CMasternodePaymentWinner > mapMasternodePayeeVotes
bool ProcessMessageMasternodePayments(CNode *pfrom, std::string &strCommand, CDataStream &vRecv, CValidationState &state)
bool MessageDispatcher(CNode *pfrom, std::string &strCommand, CDataStream &vRecv)
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:118
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:130
Message header.
Definition: protocol.h:31
char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:54
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:36
bool IsValid(const MessageStartChars &messageStart) const
Definition: protocol.cpp:165
static constexpr size_t HEADER_SIZE
Definition: protocol.h:39
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:57
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:33
std::string GetCommand() const
Definition: protocol.cpp:160
uint32_t nMessageSize
Definition: protocol.h:56
bool IsRelayable() const
Whether this address should be relayed to other peers even if we can't reach it ourselves.
Definition: netaddress.h:217
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:122
bool IsRoutable() const
Definition: netaddress.cpp:454
bool IsLocal() const
Definition: netaddress.cpp:402
uint64_t GetHash() const
Definition: netaddress.cpp:762
CDataStream vRecv
Definition: net.h:634
const uint256 & GetMessageHash() const
Definition: net.cpp:848
void SetVersion(int nVersionIn)
Definition: net.h:656
int64_t nTime
Definition: net.h:637
CMessageHeader hdr
Definition: net.h:631
CSerializedNetMsg Make(int nFlags, std::string sCommand, Args &&... args)
Information about a peer.
Definition: net.h:669
RecursiveMutex cs_vProcessMsg
Definition: net.h:684
bool fAddnode
Definition: net.h:709
std::string cleanSubVer
Definition: net.h:704
CRollingBloomFilter filterInventoryKnown
Definition: net.h:765
std::atomic< int > nVersion
Definition: net.h:699
void SetSendVersion(int nVersionIn)
Definition: net.cpp:775
std::atomic< bool > m_masternode_connection
Definition: net.h:710
std::vector< uint256 > vInventoryBlockToSend
Definition: net.h:772
std::atomic_bool fPauseRecv
Definition: net.h:734
NodeId GetId() const
Definition: net.h:825
uint256 hashContinue
Definition: net.h:748
std::atomic< int64_t > nTimeOffset
Definition: net.h:697
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:886
RecursiveMutex cs_inventory
Definition: net.h:775
std::atomic< bool > fPingQueued
Definition: net.h:796
int GetSendVersion() const
Definition: net.cpp:789
bool fFeeler
Definition: net.h:707
bool fOneShot
Definition: net.h:708
size_t nProcessQueueSize
Definition: net.h:686
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:654
std::atomic_bool fSuccessfullyConnected
Definition: net.h:721
ServiceFlags nServicesExpected
Definition: net.h:674
bool DisconnectOldProtocol(int nVersionIn, int nVersionRequired)
Definition: net.cpp:463
uint64_t GetLocalNonce() const
Definition: net.h:830
std::atomic< ServiceFlags > nServices
Definition: net.h:673
bool fGetAddr
Definition: net.h:754
CRollingBloomFilter addrKnown
Definition: net.h:753
RecursiveMutex cs_SubVer
Definition: net.h:705
const CAddress addr
Definition: net.h:698
Mutex cs_mnauth
Definition: net.h:799
std::string GetAddrName() const
Definition: net.cpp:637
std::atomic< bool > fFirstMessageIsMNAUTH
Definition: net.h:742
std::atomic< bool > m_wants_recsigs
Definition: net.h:738
std::atomic< int64_t > m_last_wants_recsigs_recv
Definition: net.h:713
void AskFor(const CInv &inv, int64_t doubleRequestDelay=2 *60 *1000000)
Definition: net.cpp:2707
int GetMyStartingHeight() const
Definition: net.h:834
uint256 sentMNAuthChallenge
Definition: net.h:800
std::atomic< int > nStartingHeight
Definition: net.h:749
bool fClient
Definition: net.h:714
std::atomic_bool fPauseSend
Definition: net.h:735
std::atomic< bool > fFirstMessageReceived
Definition: net.h:740
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:776
std::unique_ptr< CBloomFilter > pfilter
Definition: net.h:730
void PushInventory(const CInv &inv)
Definition: net.h:914
int GetRecvVersion()
Definition: net.h:858
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:784
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:881
void SetRecvVersion(int nVersionIn)
Definition: net.h:854
bool CanRelay() const
Definition: net.h:946
std::deque< CInv > vRecvGetData
Definition: net.h:690
uint256 receivedMNAuthChallenge
Definition: net.h:801
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:794
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:788
std::vector< CAddress > vAddrToSend
Definition: net.h:752
std::set< uint256 > setAskFor
Definition: net.h:777
std::atomic< int64_t > nPingUsecStart
Definition: net.h:790
std::chrono::microseconds nNextInvSend
Definition: net.h:779
ServiceFlags GetLocalServices() const
Definition: net.h:937
bool fRelayTxes
Definition: net.h:727
std::atomic< int64_t > nPingUsecTime
Definition: net.h:792
std::vector< uint256 > vBlockRequested
Definition: net.h:778
void AddInventoryKnown(const CInv &inv)
Definition: net.h:906
std::atomic< bool > m_masternode_probe_connection
Definition: net.h:711
bool fSendMempool
Definition: net.h:781
std::list< CNetMessage > vProcessMsg
Definition: net.h:685
bool fWhitelisted
Definition: net.h:706
RecursiveMutex cs_filter
Definition: net.h:729
std::atomic_bool m_wants_addrv2
Whether the peer has signaled support for receiving ADDRv2 (BIP155) messages, implying a preference t...
Definition: net.h:720
const bool fInbound
Definition: net.h:715
std::atomic_bool fDisconnect
Definition: net.h:722
double m_addr_token_bucket
Number of addresses that can be processed from this peer.
Definition: net.h:760
std::vector< CInv > vInventoryTierTwoToSend
Definition: net.h:774
std::set< uint256 > setInventoryTxToSend
Definition: net.h:768
std::string strSubVer
Definition: net.h:704
std::chrono::microseconds m_addr_token_timestamp
When m_addr_token_bucket was last updated.
Definition: net.h:762
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:72
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:111
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:274
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:311
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:484
std::string ToString() const
Definition: netaddress.cpp:954
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:932
SipHash-2-4.
Definition: siphash.h:14
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
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
bool ProcessSpork(CNode *pfrom, std::string &strCommand, CDataStream &vRecv, int &dosScore)
Definition: spork.cpp:89
bool IsSporkActive(SporkId nSporkID)
Definition: spork.cpp:220
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:244
std::vector< CTxIn > vin
Definition: transaction.h:270
bool IsShieldedTx() const
Definition: transaction.h:319
const uint256 & GetHash() const
Definition: transaction.h:301
unsigned int GetTotalSize() const
std::vector< CTxOut > vout
Definition: transaction.h:271
An input of a transaction.
Definition: transaction.h:94
COutPoint prevout
Definition: transaction.h:96
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:384
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:471
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1327
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:1105
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:1043
bool exists(uint256 hash) const
Definition: txmempool.h:640
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:893
TxMempoolInfo info(const uint256 &hash) const
Definition: txmempool.cpp:1137
unsigned long size() const
Definition: txmempool.h:629
Capture information about block/transaction validation.
Definition: validation.h:24
unsigned int GetRejectCode() const
Definition: validation.h:93
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
Definition: validation.h:39
std::string GetRejectReason() const
Definition: validation.h:94
bool IsInvalid() const
Definition: validation.h:73
bool operator()(std::set< uint256 >::iterator a, std::set< uint256 >::iterator b)
CompareInvMempoolOrder(CTxMemPool *_mempool)
Fast randomness source.
Definition: random.h:107
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:174
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
void FinalizeNode(NodeId nodeid, bool &fUpdateConnectionTime) override
void BlockChecked(const CBlock &block, const CValidationState &state) override
bool SendMessages(CNode *pto, std::atomic< bool > &interrupt) override EXCLUSIVE_LOCKS_REQUIRED(pto -> cs_sendProcessing)
Send queued protocol messages to be sent to a give node.
PeerLogicValidation(CConnman *connman)
void InitializeNode(CNode *pnode) override
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
Notifies listeners when the block chain tip advances.
bool ProcessMessages(CNode *pfrom, std::atomic< bool > &interrupt) override
Process protocol messages received from a given node.
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
void AddedMasternodeList(const uint256 &hash)
void AddedMasternodeWinner(const uint256 &hash)
void AddedBudgetItem(const uint256 &hash)
unsigned int size() const
Definition: uint256.h:83
std::string ToString() const
Definition: uint256.cpp:65
void SetNull()
Definition: uint256.h:44
bool IsNull() const
Definition: uint256.h:36
unsigned char * begin()
Definition: uint256.h:63
256-bit opaque blob.
Definition: uint256.h:138
std::unique_ptr< CDeterministicMNManager > deterministicMNManager
if(!read_stdin(buffer))
Definition: fuzz.cpp:72
@ LOCK
Definition: lockunlock.h:16
bool fLogIPs
Definition: logging.cpp:28
#define LogPrint(category,...)
Definition: logging.h:163
CMasternodePayments masternodePayments
Object for who's going to get paid on which blocks.
CMasternodeSync masternodeSync
CMasternodeMan mnodeman
Masternode manager.
unsigned int nonce
Definition: miner_tests.cpp:28
@ MEMPOOLREJ
Definition: logging.h:53
@ MEMPOOL
Definition: logging.h:43
@ NET
Definition: logging.h:41
const char * QFCOMMITMENT
The qfcommit message is used to propagate LLMQ final commitments.
Definition: protocol.cpp:56
const char * MNBROADCAST2
The mnbroadcast2 message is used to broadcast masternode startup data to connected peers Supporting B...
Definition: protocol.cpp:45
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:38
const char * MNWINNER
The mnwinner message is used to relay and distribute consensus for masternode payout ordering.
Definition: protocol.cpp:47
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:31
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:40
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:30
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:22
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:35
const char * QSENDRECSIGS
The qsendrecsigs message is used to propagate LLMQ intra-quorum partial recovered signatures.
Definition: protocol.cpp:57
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:32
const char * FINALBUDGETVOTE
The finalbudgetvote message is used to broadcast or relay finalized budget votes to connected peers.
Definition: protocol.cpp:53
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:37
const char * QSIGREC
Definition: protocol.cpp:67
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:33
const char * QCONTRIB
Definition: protocol.cpp:59
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:29
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:39
const char * QPCOMMITMENT
Definition: protocol.cpp:62
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:21
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:19
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:27
const char * MNBROADCAST
The mnbroadcast message is used to broadcast masternode startup data to connected peers.
Definition: protocol.cpp:44
const char * QCOMPLAINT
Definition: protocol.cpp:60
const char * FINALBUDGET
The finalbudget message is used to broadcast or relay finalized budget metadata to connected peers.
Definition: protocol.cpp:52
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:28
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:25
const char * MNPING
The mnping message is used to ensure a masternode is still active.
Definition: protocol.cpp:46
const char * QJUSTIFICATION
Definition: protocol.cpp:61
const char * BUDGETVOTE
The budgetvote message is used to broadcast or relay budget proposal votes to connected peers.
Definition: protocol.cpp:50
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:20
const char * BUDGETPROPOSAL
The budgetproposal message is used to broadcast or relay budget proposal metadata to connected peers.
Definition: protocol.cpp:49
const char * CLSIG
Definition: protocol.cpp:69
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:23
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:34
const char * SPORK
The spork message is used to send spork values to connected peers.
Definition: protocol.cpp:42
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:26
const char * GETSPORKS
The getsporks message is used to request spork data from connected peers.
Definition: protocol.cpp:43
const char * MNAUTH
The mnauth message is used authenticate MN connections.
Definition: protocol.cpp:58
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:24
std::unique_ptr< CQuorumBlockProcessor > quorumBlockProcessor
std::unique_ptr< CDKGSessionManager > quorumDKGSessionManager
std::unique_ptr< CSigningManager > quorumSigningManager
std::unique_ptr< CChainLocksHandler > chainLocksHandler
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:158
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:178
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:186
limitedmap< CInv, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
bool fListen
Definition: net.cpp:90
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:2846
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:94
void CheckOffsetDisconnectedPeers(const CNetAddr &ip)
Definition: net.cpp:908
bool IsReachable(enum Network net)
Definition: net.cpp:253
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:265
int NodeId
Definition: net.h:109
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
RecursiveMutex g_cs_orphans
void EraseOrphansFor(NodeId peer)
For random eviction.
class CNetProcessingCleanup instance_of_cnetprocessingcleanup
bool fRequestedSporksIDB
bool AddOrphanTx(const CTransactionRef &tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
void Misbehaving(NodeId pnode, int howmuch, const std::string &message) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Increase a node's misbehavior score.
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
bool IsBanned(NodeId pnode)
std::map< uint256, COrphanTx > mapOrphanTransactions GUARDED_BY(g_cs_orphans)
double CountSecondsDouble(SecondsDouble t)
Helper to count the seconds in any std::chrono::duration type.
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:80
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:639
const std::vector< std::string > & getTierTwoNetMessageTypes()
Definition: protocol.cpp:255
@ MSG_TX
Definition: protocol.h:436
@ MSG_BUDGET_VOTE
Definition: protocol.h:446
@ MSG_FILTERED_BLOCK
Definition: protocol.h:440
@ MSG_QUORUM_JUSTIFICATION
Definition: protocol.h:457
@ MSG_BUDGET_PROPOSAL
Definition: protocol.h:447
@ MSG_QUORUM_COMPLAINT
Definition: protocol.h:456
@ MSG_MASTERNODE_ANNOUNCE
Definition: protocol.h:451
@ MSG_MASTERNODE_WINNER
Definition: protocol.h:444
@ MSG_BLOCK
Definition: protocol.h:437
@ MSG_MASTERNODE_PING
Definition: protocol.h:452
@ MSG_TXLOCK_REQUEST
Definition: protocol.h:441
@ MSG_QUORUM_CONTRIB
Definition: protocol.h:455
@ MSG_BUDGET_FINALIZED_VOTE
Definition: protocol.h:449
@ MSG_TXLOCK_VOTE
Definition: protocol.h:442
@ MSG_QUORUM_PREMATURE_COMMITMENT
Definition: protocol.h:458
@ MSG_QUORUM_RECOVERED_SIG
Definition: protocol.h:459
@ MSG_SPORK
Definition: protocol.h:443
@ MSG_CLSIG
Definition: protocol.h:460
@ MSG_BUDGET_FINALIZED
Definition: protocol.h:448
@ MSG_QUORUM_FINAL_COMMITMENT
Definition: protocol.h:454
ServiceFlags
nServices flags
Definition: protocol.h:312
@ NODE_BLOOM
Definition: protocol.h:321
@ NODE_NETWORK
Definition: protocol.h:318
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:579
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:586
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:217
const char * name
Definition: rest.cpp:37
@ SER_NETWORK
Definition: serialize.h:174
constexpr deserialize_type deserialize
Definition: serialize.h:57
#define LIMITED_STRING(obj, n)
Definition: serialize.h:515
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:359
std::map< uint256, CSporkMessage > mapSporks
Definition: spork.cpp:30
CSporkManager sporkManager
Definition: spork.cpp:29
@ SPORK_22_LLMQ_DKG_MAINTENANCE
Definition: sporkid.h:29
@ SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2
Definition: sporkid.h:22
@ SPORK_14_NEW_PROTOCOL_ENFORCEMENT
Definition: sporkid.h:21
@ SPORK_19_COLDSTAKING_MAINTENANCE
Definition: sporkid.h:26
@ SPORK_20_SAPLING_MAINTENANCE
Definition: sporkid.h:27
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:154
std::vector< uint256 > vHave
Definition: block.h:155
bool IsNull() const
Definition: block.h:177
std::vector< int > vHeightInFlight
uint64_t m_addr_rate_limited
uint64_t m_addr_processed
NodeId fromPeer
int64_t nTimeExpire
size_t list_pos
CTransactionRef tx
int nTimeSlotLength
Definition: params.h:194
bool operator()(const I &a, const I &b) const
#define AssertLockNotHeld(cs)
Definition: sync.h:76
#define LOCK2(cs1, cs2)
Definition: sync.h:221
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:247
#define TRY_LOCK(cs, name)
Definition: sync.h:224
#define AssertLockHeld(cs)
Definition: sync.h:75
ArgsManager gArgs
Definition: system.cpp:89
std::atomic< bool > fMasterNode
Definition: system.cpp:87
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:526
bool error(const char *fmt, const Args &... args)
Definition: system.h:77
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:50
TierTwoSyncState g_tiertwo_sync_state
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample, int nOffsetLimit)
Definition: timedata.cpp:43
int64_t abs64(int64_t n)
Functions to keep track of adjusted P2P time.
Definition: timedata.h:73
#define strprintf
Definition: tinyformat.h:1056
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:456
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:175
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:13
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: utiltime.cpp:74
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: utiltime.cpp:27
int ActiveProtocol()
See whether the protocol update is enforced for connected nodes.
std::unique_ptr< CSporkDB > pSporkDB
Global variable that points to the spork database (protected by cs_main)
Definition: validation.cpp:209
CTxMemPool mempool(::minRelayTxFee)
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: validation.cpp:862
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &pblock, const FlatFilePos *dbp)
Process an incoming block.
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:206
std::atomic< bool > fImporting
Definition: validation.cpp:94
bool AcceptBlockHeader(const CBlock &block, CValidationState &state, CBlockIndex **ppindex, CBlockIndex *pindexPrev)
BlockMap mapBlockIndex
Definition: validation.cpp:82
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectInsaneFee, bool ignoreFees)
(try to) add transaction to memory pool
Definition: validation.cpp:649
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos)
Definition: validation.cpp:758
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:85
std::atomic< bool > fReindex
Definition: validation.cpp:95
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:84
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:181
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:345
CMainSignals & GetMainSignals()