BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
net_processing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <net_processing.h>
7 
8 #include <addrman.h>
9 #include <arith_uint256.h>
10 #include <blockencodings.h>
11 #include <chainparams.h>
12 #include <consensus/validation.h>
13 #include <hash.h>
14 #include <validation.h>
15 #include <merkleblock.h>
16 #include <netmessagemaker.h>
17 #include <netbase.h>
18 #include <policy/fees.h>
19 #include <policy/policy.h>
20 #include <primitives/block.h>
21 #include <primitives/transaction.h>
22 #include <random.h>
23 #include <reverse_iterator.h>
24 #include <scheduler.h>
25 #include <tinyformat.h>
26 #include <txmempool.h>
27 #include <ui_interface.h>
28 #include <util.h>
29 #include <utilmoneystr.h>
30 #include <utilstrencodings.h>
31 
32 #include <memory>
33 
34 #if defined(NDEBUG)
35 # error "BSHA3 cannot be compiled without assertions."
36 #endif
37 
39 static constexpr int64_t ORPHAN_TX_EXPIRE_TIME = 20 * 60;
41 static constexpr int64_t ORPHAN_TX_EXPIRE_INTERVAL = 5 * 60;
44 static constexpr int64_t HEADERS_DOWNLOAD_TIMEOUT_BASE = 15 * 60 * 1000000; // 15 minutes
45 static constexpr int64_t HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1000; // 1ms/header
49 static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
51 static constexpr int64_t CHAIN_SYNC_TIMEOUT = 20 * 60; // 20 minutes
53 static constexpr int64_t STALE_CHECK_INTERVAL = 10 * 60; // 10 minutes
55 static constexpr int64_t EXTRA_PEER_CHECK_INTERVAL = 45;
57 static constexpr int64_t MINIMUM_CONNECT_TIME = 30;
59 static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
62 static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
65 static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
66 
67 struct COrphanTx {
68  // When modifying, adapt the copy of this definition in tests/DoS_tests.
71  int64_t nTimeExpire;
72 };
74 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
75 
76 void EraseOrphansFor(NodeId peer);
77 
79 void Misbehaving(NodeId nodeid, int howmuch, const std::string& message="") EXCLUSIVE_LOCKS_REQUIRED(cs_main);
80 
82 static constexpr unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 60 * 60;
84 static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
87 static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5;
90 static constexpr unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_INTERVAL;
92 static constexpr unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
94 static constexpr unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
95 
96 // Internal stuff
97 namespace {
99  int nSyncStarted GUARDED_BY(cs_main) = 0;
100 
107  std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main);
108 
128  std::unique_ptr<CRollingBloomFilter> recentRejects GUARDED_BY(cs_main);
129  uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main);
130 
132  struct QueuedBlock {
133  uint256 hash;
134  const CBlockIndex* pindex;
135  bool fValidatedHeaders;
136  std::unique_ptr<PartiallyDownloadedBlock> partialBlock;
137  };
138  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main);
139 
141  std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main);
142 
144  int nPreferredDownload GUARDED_BY(cs_main) = 0;
145 
147  int nPeersWithValidatedDownloads GUARDED_BY(cs_main) = 0;
148 
150  int g_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0;
151 
153  std::atomic<int64_t> g_last_tip_update(0);
154 
156  typedef std::map<uint256, CTransactionRef> MapRelay;
157  MapRelay mapRelay GUARDED_BY(cs_main);
159  std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration GUARDED_BY(cs_main);
160 
161  std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
162 
163  struct IteratorComparator
164  {
165  template<typename I>
166  bool operator()(const I& a, const I& b) const
167  {
168  return &(*a) < &(*b);
169  }
170  };
171  std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(g_cs_orphans);
172 
173  static size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
174  static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
175 } // namespace
176 
177 namespace {
178 struct CBlockReject {
179  unsigned char chRejectCode;
180  std::string strRejectReason;
181  uint256 hashBlock;
182 };
183 
190 struct CNodeState {
192  const CService address;
194  bool fCurrentlyConnected;
196  int nMisbehavior;
198  bool fShouldBan;
200  const std::string name;
202  std::vector<CBlockReject> rejects;
204  const CBlockIndex *pindexBestKnownBlock;
206  uint256 hashLastUnknownBlock;
208  const CBlockIndex *pindexLastCommonBlock;
210  const CBlockIndex *pindexBestHeaderSent;
212  int nUnconnectingHeaders;
214  bool fSyncStarted;
216  int64_t nHeadersSyncTimeout;
218  int64_t nStallingSince;
219  std::list<QueuedBlock> vBlocksInFlight;
221  int64_t nDownloadingSince;
222  int nBlocksInFlight;
223  int nBlocksInFlightValidHeaders;
225  bool fPreferredDownload;
227  bool fPreferHeaders;
229  bool fPreferHeaderAndIDs;
235  bool fProvidesHeaderAndIDs;
237  bool fHaveWitness;
239  bool fWantsCmpctWitness;
244  bool fSupportsDesiredCmpctVersion;
245 
260  struct ChainSyncTimeoutState {
262  int64_t m_timeout;
264  const CBlockIndex * m_work_header;
266  bool m_sent_getheaders;
268  bool m_protect;
269  };
270 
271  ChainSyncTimeoutState m_chain_sync;
272 
274  int64_t m_last_block_announcement;
275 
276  CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
277  fCurrentlyConnected = false;
278  nMisbehavior = 0;
279  fShouldBan = false;
280  pindexBestKnownBlock = nullptr;
281  hashLastUnknownBlock.SetNull();
282  pindexLastCommonBlock = nullptr;
283  pindexBestHeaderSent = nullptr;
284  nUnconnectingHeaders = 0;
285  fSyncStarted = false;
286  nHeadersSyncTimeout = 0;
287  nStallingSince = 0;
288  nDownloadingSince = 0;
289  nBlocksInFlight = 0;
290  nBlocksInFlightValidHeaders = 0;
291  fPreferredDownload = false;
292  fPreferHeaders = false;
293  fPreferHeaderAndIDs = false;
294  fProvidesHeaderAndIDs = false;
295  fHaveWitness = false;
296  fWantsCmpctWitness = false;
297  fSupportsDesiredCmpctVersion = false;
298  m_chain_sync = { 0, nullptr, false, false };
299  m_last_block_announcement = 0;
300  }
301 };
302 
304 static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main);
305 
306 static CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
307  std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
308  if (it == mapNodeState.end())
309  return nullptr;
310  return &it->second;
311 }
312 
313 static void UpdatePreferredDownload(CNode* node, CNodeState* state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
314 {
315  nPreferredDownload -= state->fPreferredDownload;
316 
317  // Whether this node should be marked as a preferred download node.
318  state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
319 
320  nPreferredDownload += state->fPreferredDownload;
321 }
322 
323 static void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
324 {
325  ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
326  uint64_t nonce = pnode->GetLocalNonce();
327  int nNodeStartingHeight = pnode->GetMyStartingHeight();
328  NodeId nodeid = pnode->GetId();
329  CAddress addr = pnode->addr;
330 
331  CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
332  CAddress addrMe = CAddress(CService(), nLocalNodeServices);
333 
334  connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
335  nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
336 
337  if (fLogIPs) {
338  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);
339  } else {
340  LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
341  }
342 }
343 
344 // Returns a bool indicating whether we requested this block.
345 // Also used if a block was /not/ received and timed out or started with another peer
346 static bool MarkBlockAsReceived(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
347  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
348  if (itInFlight != mapBlocksInFlight.end()) {
349  CNodeState *state = State(itInFlight->second.first);
350  assert(state != nullptr);
351  state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
352  if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
353  // Last validated block on the queue was received.
354  nPeersWithValidatedDownloads--;
355  }
356  if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
357  // First block on the queue was received, update the start download time for the next one
358  state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
359  }
360  state->vBlocksInFlight.erase(itInFlight->second.second);
361  state->nBlocksInFlight--;
362  state->nStallingSince = 0;
363  mapBlocksInFlight.erase(itInFlight);
364  return true;
365  }
366  return false;
367 }
368 
369 // returns false, still setting pit, if the block was already in flight from the same peer
370 // pit will only be valid as long as the same cs_main lock is being held
371 static bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
372  CNodeState *state = State(nodeid);
373  assert(state != nullptr);
374 
375  // Short-circuit most stuff in case it is from the same node
376  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
377  if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
378  if (pit) {
379  *pit = &itInFlight->second.second;
380  }
381  return false;
382  }
383 
384  // Make sure it's not listed somewhere already.
385  MarkBlockAsReceived(hash);
386 
387  std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
388  {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
389  state->nBlocksInFlight++;
390  state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
391  if (state->nBlocksInFlight == 1) {
392  // We're starting a block download (batch) from this peer.
393  state->nDownloadingSince = GetTimeMicros();
394  }
395  if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
396  nPeersWithValidatedDownloads++;
397  }
398  itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
399  if (pit)
400  *pit = &itInFlight->second.second;
401  return true;
402 }
403 
405 static void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
406  CNodeState *state = State(nodeid);
407  assert(state != nullptr);
408 
409  if (!state->hashLastUnknownBlock.IsNull()) {
410  const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock);
411  if (pindex && pindex->nChainWork > 0) {
412  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
413  state->pindexBestKnownBlock = pindex;
414  }
415  state->hashLastUnknownBlock.SetNull();
416  }
417  }
418 }
419 
421 static void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
422  CNodeState *state = State(nodeid);
423  assert(state != nullptr);
424 
425  ProcessBlockAvailability(nodeid);
426 
427  const CBlockIndex* pindex = LookupBlockIndex(hash);
428  if (pindex && pindex->nChainWork > 0) {
429  // An actually better block was announced.
430  if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) {
431  state->pindexBestKnownBlock = pindex;
432  }
433  } else {
434  // An unknown block was announced; just assume that the latest one is the best one.
435  state->hashLastUnknownBlock = hash;
436  }
437 }
438 
445 static void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
446 {
448  CNodeState* nodestate = State(nodeid);
449  if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
450  // Never ask from peers who can't provide witnesses.
451  return;
452  }
453  if (nodestate->fProvidesHeaderAndIDs) {
454  for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
455  if (*it == nodeid) {
456  lNodesAnnouncingHeaderAndIDs.erase(it);
457  lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
458  return;
459  }
460  }
461  connman->ForNode(nodeid, [connman](CNode* pfrom){
463  uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
464  if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
465  // As per BIP152, we only get 3 of our peers to announce
466  // blocks using compact encodings.
467  connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
469  connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
470  return true;
471  });
472  lNodesAnnouncingHeaderAndIDs.pop_front();
473  }
474  connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
475  lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
476  return true;
477  });
478  }
479 }
480 
481 static bool TipMayBeStale(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
482 {
484  if (g_last_tip_update == 0) {
485  g_last_tip_update = GetTime();
486  }
487  return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
488 }
489 
490 static bool CanDirectFetch(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
491 {
492  return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
493 }
494 
495 static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
496 {
497  if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
498  return true;
499  if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
500  return true;
501  return false;
502 }
503 
506 static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
507 {
508  if (count == 0)
509  return;
510 
511  vBlocks.reserve(vBlocks.size() + count);
512  CNodeState *state = State(nodeid);
513  assert(state != nullptr);
514 
515  // Make sure pindexBestKnownBlock is up to date, we'll need it.
516  ProcessBlockAvailability(nodeid);
517 
518  if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
519  // This peer has nothing interesting.
520  return;
521  }
522 
523  if (state->pindexLastCommonBlock == nullptr) {
524  // Bootstrap quickly by guessing a parent of our best tip is the forking point.
525  // Guessing wrong in either direction is not a problem.
526  state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
527  }
528 
529  // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
530  // of its current tip anymore. Go back enough to fix that.
531  state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
532  if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
533  return;
534 
535  std::vector<const CBlockIndex*> vToFetch;
536  const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
537  // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
538  // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
539  // download that next block if the window were 1 larger.
540  int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
541  int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
542  NodeId waitingfor = -1;
543  while (pindexWalk->nHeight < nMaxHeight) {
544  // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
545  // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
546  // as iterating over ~100 CBlockIndex* entries anyway.
547  int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
548  vToFetch.resize(nToFetch);
549  pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
550  vToFetch[nToFetch - 1] = pindexWalk;
551  for (unsigned int i = nToFetch - 1; i > 0; i--) {
552  vToFetch[i - 1] = vToFetch[i]->pprev;
553  }
554 
555  // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
556  // are not yet downloaded and not in flight to vBlocks. In the meantime, update
557  // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
558  // already part of our chain (and therefore don't need it even if pruned).
559  for (const CBlockIndex* pindex : vToFetch) {
560  if (!pindex->IsValid(BLOCK_VALID_TREE)) {
561  // We consider the chain that this peer is on invalid.
562  return;
563  }
564  if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
565  // We wouldn't download this block or its descendants from this peer.
566  return;
567  }
568  if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
569  if (pindex->nChainTx)
570  state->pindexLastCommonBlock = pindex;
571  } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
572  // The block is not already downloaded, and not yet in flight.
573  if (pindex->nHeight > nWindowEnd) {
574  // We reached the end of the window.
575  if (vBlocks.size() == 0 && waitingfor != nodeid) {
576  // We aren't able to fetch anything, but we would be if the download window was one larger.
577  nodeStaller = waitingfor;
578  }
579  return;
580  }
581  vBlocks.push_back(pindex);
582  if (vBlocks.size() == count) {
583  return;
584  }
585  } else if (waitingfor == -1) {
586  // This is the first already-in-flight block.
587  waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
588  }
589  }
590  }
591 }
592 
593 } // namespace
594 
595 // This function is used for testing the stale tip eviction logic, see
596 // denialofservice_tests.cpp
597 void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
598 {
599  LOCK(cs_main);
600  CNodeState *state = State(node);
601  if (state) state->m_last_block_announcement = time_in_seconds;
602 }
603 
604 // Returns true for outbound peers, excluding manual connections, feelers, and
605 // one-shots
606 static bool IsOutboundDisconnectionCandidate(const CNode *node)
607 {
608  return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
609 }
610 
612  CAddress addr = pnode->addr;
613  std::string addrName = pnode->GetAddrName();
614  NodeId nodeid = pnode->GetId();
615  {
616  LOCK(cs_main);
617  mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
618  }
619  if(!pnode->fInbound)
620  PushNodeVersion(pnode, connman, GetTime());
621 }
622 
623 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
624  fUpdateConnectionTime = false;
625  LOCK(cs_main);
626  CNodeState *state = State(nodeid);
627  assert(state != nullptr);
628 
629  if (state->fSyncStarted)
630  nSyncStarted--;
631 
632  if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
633  fUpdateConnectionTime = true;
634  }
635 
636  for (const QueuedBlock& entry : state->vBlocksInFlight) {
637  mapBlocksInFlight.erase(entry.hash);
638  }
639  EraseOrphansFor(nodeid);
640  nPreferredDownload -= state->fPreferredDownload;
641  nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
642  assert(nPeersWithValidatedDownloads >= 0);
643  g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
644  assert(g_outbound_peers_with_protect_from_disconnect >= 0);
645 
646  mapNodeState.erase(nodeid);
647 
648  if (mapNodeState.empty()) {
649  // Do a consistency check after the last peer is removed.
650  assert(mapBlocksInFlight.empty());
651  assert(nPreferredDownload == 0);
652  assert(nPeersWithValidatedDownloads == 0);
653  assert(g_outbound_peers_with_protect_from_disconnect == 0);
654  }
655  LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
656 }
657 
659  LOCK(cs_main);
660  CNodeState *state = State(nodeid);
661  if (state == nullptr)
662  return false;
663  stats.nMisbehavior = state->nMisbehavior;
664  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
665  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
666  for (const QueuedBlock& queue : state->vBlocksInFlight) {
667  if (queue.pindex)
668  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
669  }
670  return true;
671 }
672 
674 //
675 // mapOrphanTransactions
676 //
677 
678 static void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
679 {
680  size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
681  if (max_extra_txn <= 0)
682  return;
683  if (!vExtraTxnForCompact.size())
684  vExtraTxnForCompact.resize(max_extra_txn);
685  vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
686  vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
687 }
688 
690 {
691  const uint256& hash = tx->GetHash();
692  if (mapOrphanTransactions.count(hash))
693  return false;
694 
695  // Ignore big transactions, to avoid a
696  // send-big-orphans memory exhaustion attack. If a peer has a legitimate
697  // large transaction with a missing parent then we assume
698  // it will rebroadcast it later, after the parent transaction(s)
699  // have been mined or received.
700  // 100 orphans, each of which is at most 100,000 bytes big is
701  // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
702  unsigned int sz = GetTransactionWeight(*tx);
703  if (sz > MAX_STANDARD_TX_WEIGHT)
704  {
705  LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
706  return false;
707  }
708 
709  auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
710  assert(ret.second);
711  for (const CTxIn& txin : tx->vin) {
712  mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
713  }
714 
715  AddToCompactExtraTransactions(tx);
716 
717  LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
718  mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
719  return true;
720 }
721 
722 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
723 {
724  std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
725  if (it == mapOrphanTransactions.end())
726  return 0;
727  for (const CTxIn& txin : it->second.tx->vin)
728  {
729  auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
730  if (itPrev == mapOrphanTransactionsByPrev.end())
731  continue;
732  itPrev->second.erase(it);
733  if (itPrev->second.empty())
734  mapOrphanTransactionsByPrev.erase(itPrev);
735  }
736  mapOrphanTransactions.erase(it);
737  return 1;
738 }
739 
741 {
743  int nErased = 0;
744  std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
745  while (iter != mapOrphanTransactions.end())
746  {
747  std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
748  if (maybeErase->second.fromPeer == peer)
749  {
750  nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
751  }
752  }
753  if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
754 }
755 
756 
757 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
758 {
760 
761  unsigned int nEvicted = 0;
762  static int64_t nNextSweep;
763  int64_t nNow = GetTime();
764  if (nNextSweep <= nNow) {
765  // Sweep out expired orphan pool entries:
766  int nErased = 0;
767  int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
768  std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
769  while (iter != mapOrphanTransactions.end())
770  {
771  std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
772  if (maybeErase->second.nTimeExpire <= nNow) {
773  nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
774  } else {
775  nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
776  }
777  }
778  // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
779  nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
780  if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
781  }
782  while (mapOrphanTransactions.size() > nMaxOrphans)
783  {
784  // Evict a random orphan:
785  uint256 randomhash = GetRandHash();
786  std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
787  if (it == mapOrphanTransactions.end())
788  it = mapOrphanTransactions.begin();
789  EraseOrphanTx(it->first);
790  ++nEvicted;
791  }
792  return nEvicted;
793 }
794 
798 void Misbehaving(NodeId pnode, int howmuch, const std::string& message) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
799 {
800  if (howmuch == 0)
801  return;
802 
803  CNodeState *state = State(pnode);
804  if (state == nullptr)
805  return;
806 
807  state->nMisbehavior += howmuch;
808  int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
809  std::string message_prefixed = message.empty() ? "" : (": " + message);
810  if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
811  {
812  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);
813  state->fShouldBan = true;
814  } else
815  LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d)%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed);
816 }
817 
818 
819 
820 
821 
822 
823 
824 
826 //
827 // blockchain -> download logic notification
828 //
829 
830 // To prevent fingerprinting attacks, only send blocks/headers outside of the
831 // active chain if they are no more than a month older (both in time, and in
832 // best equivalent proof of work) than the best header chain we know about and
833 // we fully-validated them at some point.
834 static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
835 {
837  if (chainActive.Contains(pindex)) return true;
838  return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
839  (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
840  (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
841 }
842 
843 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler, bool enable_bip61)
844  : connman(connmanIn), m_stale_tip_check_time(0), m_enable_bip61(enable_bip61) {
845 
846  // Initialize global variables that cannot be constructed at startup.
847  recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
848 
849  const Consensus::Params& consensusParams = Params().GetConsensus();
850  // Stale tip checking and peer eviction are on two different timers, but we
851  // don't want them to get out of sync due to drift in the scheduler, so we
852  // combine them in one function and schedule at the quicker (peer-eviction)
853  // timer.
854  static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
855  scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
856 }
857 
862 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
864 
865  std::vector<uint256> vOrphanErase;
866 
867  for (const CTransactionRef& ptx : pblock->vtx) {
868  const CTransaction& tx = *ptx;
869 
870  // Which orphan pool entries must we evict?
871  for (const auto& txin : tx.vin) {
872  auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
873  if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
874  for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
875  const CTransaction& orphanTx = *(*mi)->second.tx;
876  const uint256& orphanHash = orphanTx.GetHash();
877  vOrphanErase.push_back(orphanHash);
878  }
879  }
880  }
881 
882  // Erase orphan transactions included or precluded by this block
883  if (vOrphanErase.size()) {
884  int nErased = 0;
885  for (const uint256& orphanHash : vOrphanErase) {
886  nErased += EraseOrphanTx(orphanHash);
887  }
888  LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
889  }
890 
891  g_last_tip_update = GetTime();
892 }
893 
894 // All of the following cache a recent block, and are protected by cs_most_recent_block
895 static CCriticalSection cs_most_recent_block;
896 static std::shared_ptr<const CBlock> most_recent_block GUARDED_BY(cs_most_recent_block);
897 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block GUARDED_BY(cs_most_recent_block);
898 static uint256 most_recent_block_hash GUARDED_BY(cs_most_recent_block);
899 static bool fWitnessesPresentInMostRecentCompactBlock GUARDED_BY(cs_most_recent_block);
900 
905 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
906  std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
907  const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
908 
909  LOCK(cs_main);
910 
911  static int nHighestFastAnnounce = 0;
912  if (pindex->nHeight <= nHighestFastAnnounce)
913  return;
914  nHighestFastAnnounce = pindex->nHeight;
915 
916  bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
917  uint256 hashBlock(pblock->GetHash());
918 
919  {
920  LOCK(cs_most_recent_block);
921  most_recent_block_hash = hashBlock;
922  most_recent_block = pblock;
923  most_recent_compact_block = pcmpctblock;
924  fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
925  }
926 
927  connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
929 
930  // TODO: Avoid the repeated-serialization here
931  if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
932  return;
933  ProcessBlockAvailability(pnode->GetId());
934  CNodeState &state = *State(pnode->GetId());
935  // If the peer has, or we announced to them the previous block already,
936  // but we don't think they have this one, go ahead and announce it
937  if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
938  !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
939 
940  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
941  hashBlock.ToString(), pnode->GetId());
942  connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
943  state.pindexBestHeaderSent = pindex;
944  }
945  });
946 }
947 
952 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
953  const int nNewHeight = pindexNew->nHeight;
954  connman->SetBestHeight(nNewHeight);
955 
956  SetServiceFlagsIBDCache(!fInitialDownload);
957  if (!fInitialDownload) {
958  // Find the hashes of all blocks that weren't previously in the best chain.
959  std::vector<uint256> vHashes;
960  const CBlockIndex *pindexToAnnounce = pindexNew;
961  while (pindexToAnnounce != pindexFork) {
962  vHashes.push_back(pindexToAnnounce->GetBlockHash());
963  pindexToAnnounce = pindexToAnnounce->pprev;
964  if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
965  // Limit announcements in case of a huge reorganization.
966  // Rely on the peer's synchronization mechanism in that case.
967  break;
968  }
969  }
970  // Relay inventory, but don't relay old inventory during initial block download.
971  connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
972  if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
973  for (const uint256& hash : reverse_iterate(vHashes)) {
974  pnode->PushBlockHash(hash);
975  }
976  }
977  });
979  }
980 
981  nTimeBestReceived = GetTime();
982 }
983 
989  LOCK(cs_main);
990 
991  const uint256 hash(block.GetHash());
992  std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
993 
994  int nDoS = 0;
995  if (state.IsInvalid(nDoS)) {
996  // Don't send reject message with code 0 or an internal reject code.
997  if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
998  CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
999  State(it->second.first)->rejects.push_back(reject);
1000  if (nDoS > 0 && it->second.second)
1001  Misbehaving(it->second.first, nDoS);
1002  }
1003  }
1004  // Check that:
1005  // 1. The block is valid
1006  // 2. We're not in initial block download
1007  // 3. This is currently the best block we're aware of. We haven't updated
1008  // the tip yet so we have no way to check this directly here. Instead we
1009  // just check that there are currently no other blocks in flight.
1010  else if (state.IsValid() &&
1012  mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
1013  if (it != mapBlockSource.end()) {
1014  MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
1015  }
1016  }
1017  if (it != mapBlockSource.end())
1018  mapBlockSource.erase(it);
1019 }
1020 
1022 //
1023 // Messages
1024 //
1025 
1026 
1027 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1028 {
1029  switch (inv.type)
1030  {
1031  case MSG_TX:
1032  case MSG_WITNESS_TX:
1033  {
1034  assert(recentRejects);
1035  if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
1036  {
1037  // If the chain tip has changed previously rejected transactions
1038  // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
1039  // or a double-spend. Reset the rejects filter and give those
1040  // txs a second chance.
1041  hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
1042  recentRejects->reset();
1043  }
1044 
1045  {
1046  LOCK(g_cs_orphans);
1047  if (mapOrphanTransactions.count(inv.hash)) return true;
1048  }
1049 
1050  return recentRejects->contains(inv.hash) ||
1051  mempool.exists(inv.hash) ||
1052  pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
1053  pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
1054  }
1055  case MSG_BLOCK:
1056  case MSG_WITNESS_BLOCK:
1057  return LookupBlockIndex(inv.hash) != nullptr;
1058  }
1059  // Don't know what it is, just say we already got one
1060  return true;
1061 }
1062 
1063 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
1064 {
1065  CInv inv(MSG_TX, tx.GetHash());
1066  connman->ForEachNode([&inv](CNode* pnode)
1067  {
1068  pnode->PushInventory(inv);
1069  });
1070 }
1071 
1072 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
1073 {
1074  unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
1075 
1076  // Relay to a limited number of other nodes
1077  // Use deterministic randomness to send to the same nodes for 24 hours
1078  // at a time so the addrKnowns of the chosen nodes prevent repeats
1079  uint64_t hashAddr = addr.GetHash();
1080  const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
1081  FastRandomContext insecure_rand;
1082 
1083  std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
1084  assert(nRelayNodes <= best.size());
1085 
1086  auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
1087  if (pnode->nVersion >= CADDR_TIME_VERSION) {
1088  uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
1089  for (unsigned int i = 0; i < nRelayNodes; i++) {
1090  if (hashKey > best[i].first) {
1091  std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1092  best[i] = std::make_pair(hashKey, pnode);
1093  break;
1094  }
1095  }
1096  }
1097  };
1098 
1099  auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
1100  for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1101  best[i].second->PushAddress(addr, insecure_rand);
1102  }
1103  };
1104 
1105  connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
1106 }
1107 
1108 void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, const CInv& inv, CConnman* connman)
1109 {
1110  bool send = false;
1111  std::shared_ptr<const CBlock> a_recent_block;
1112  std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1113  bool fWitnessesPresentInARecentCompactBlock;
1114  const Consensus::Params& consensusParams = chainparams.GetConsensus();
1115  {
1116  LOCK(cs_most_recent_block);
1117  a_recent_block = most_recent_block;
1118  a_recent_compact_block = most_recent_compact_block;
1119  fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1120  }
1121 
1122  bool need_activate_chain = false;
1123  {
1124  LOCK(cs_main);
1125  const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1126  if (pindex) {
1127  if (pindex->nChainTx && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
1128  pindex->IsValid(BLOCK_VALID_TREE)) {
1129  // If we have the block and all of its parents, but have not yet validated it,
1130  // we might be in the middle of connecting it (ie in the unlock of cs_main
1131  // before ActivateBestChain but after AcceptBlock).
1132  // In this case, we need to run ActivateBestChain prior to checking the relay
1133  // conditions below.
1134  need_activate_chain = true;
1135  }
1136  }
1137  } // release cs_main before calling ActivateBestChain
1138  if (need_activate_chain) {
1139  CValidationState state;
1140  if (!ActivateBestChain(state, Params(), a_recent_block)) {
1141  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state));
1142  }
1143  }
1144 
1145  LOCK(cs_main);
1146  const CBlockIndex* pindex = LookupBlockIndex(inv.hash);
1147  if (pindex) {
1148  send = BlockRequestAllowed(pindex, consensusParams);
1149  if (!send) {
1150  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1151  }
1152  }
1153  const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1154  // disconnect node in case we have reached the outbound limit for serving historical blocks
1155  // never disconnect whitelisted nodes
1156  if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1157  {
1158  LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1159 
1160  //disconnect node
1161  pfrom->fDisconnect = true;
1162  send = false;
1163  }
1164  // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
1165  if (send && !pfrom->fWhitelisted && (
1166  (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
1167  )) {
1168  LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId());
1169 
1170  //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
1171  pfrom->fDisconnect = true;
1172  send = false;
1173  }
1174  // Pruned nodes may have deleted the block, so check whether
1175  // it's available before trying to send.
1176  if (send && (pindex->nStatus & BLOCK_HAVE_DATA))
1177  {
1178  std::shared_ptr<const CBlock> pblock;
1179  if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) {
1180  pblock = a_recent_block;
1181  } else if (inv.type == MSG_WITNESS_BLOCK) {
1182  // Fast-path: in this case it is possible to serve the block directly from disk,
1183  // as the network format matches the format on disk
1184  std::vector<uint8_t> block_data;
1185  if (!ReadRawBlockFromDisk(block_data, pindex, chainparams.MessageStart())) {
1186  assert(!"cannot load block from disk");
1187  }
1188  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, MakeSpan(block_data)));
1189  // Don't set pblock as we've sent the block
1190  } else {
1191  // Send block from disk
1192  std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1193  if (!ReadBlockFromDisk(*pblockRead, pindex, consensusParams))
1194  assert(!"cannot load block from disk");
1195  pblock = pblockRead;
1196  }
1197  if (pblock) {
1198  if (inv.type == MSG_BLOCK)
1199  connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1200  else if (inv.type == MSG_WITNESS_BLOCK)
1201  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1202  else if (inv.type == MSG_FILTERED_BLOCK)
1203  {
1204  bool sendMerkleBlock = false;
1205  CMerkleBlock merkleBlock;
1206  {
1207  LOCK(pfrom->cs_filter);
1208  if (pfrom->pfilter) {
1209  sendMerkleBlock = true;
1210  merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1211  }
1212  }
1213  if (sendMerkleBlock) {
1214  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1215  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1216  // This avoids hurting performance by pointlessly requiring a round-trip
1217  // Note that there is currently no way for a node to request any single transactions we didn't send here -
1218  // they must either disconnect and retry or request the full block.
1219  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1220  // however we MUST always provide at least what the remote peer needs
1221  typedef std::pair<unsigned int, uint256> PairType;
1222  for (PairType& pair : merkleBlock.vMatchedTxn)
1223  connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1224  }
1225  // else
1226  // no response
1227  }
1228  else if (inv.type == MSG_CMPCT_BLOCK)
1229  {
1230  // If a peer is asking for old blocks, we're almost guaranteed
1231  // they won't have a useful mempool to match against a compact block,
1232  // and we don't feel like constructing the object for them, so
1233  // instead we respond with the full, non-compact block.
1234  bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1235  int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1236  if (CanDirectFetch(consensusParams) && pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1237  if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) {
1238  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1239  } else {
1240  CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1241  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1242  }
1243  } else {
1244  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1245  }
1246  }
1247  }
1248 
1249  // Trigger the peer node to send a getblocks request for the next batch of inventory
1250  if (inv.hash == pfrom->hashContinue)
1251  {
1252  // Bypass PushInventory, this must send even if redundant,
1253  // and we want it right after the last block so they don't
1254  // wait for other stuff first.
1255  std::vector<CInv> vInv;
1256  vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1257  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1258  pfrom->hashContinue.SetNull();
1259  }
1260  }
1261 }
1262 
1263 void static ProcessGetData(CNode* pfrom, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc) LOCKS_EXCLUDED(cs_main)
1264 {
1266 
1267  std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1268  std::vector<CInv> vNotFound;
1269  const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1270  {
1271  LOCK(cs_main);
1272 
1273  while (it != pfrom->vRecvGetData.end() && (it->type == MSG_TX || it->type == MSG_WITNESS_TX)) {
1274  if (interruptMsgProc)
1275  return;
1276  // Don't bother if send buffer is too full to respond anyway
1277  if (pfrom->fPauseSend)
1278  break;
1279 
1280  const CInv &inv = *it;
1281  it++;
1282 
1283  // Send stream from relay memory
1284  bool push = false;
1285  auto mi = mapRelay.find(inv.hash);
1286  int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1287  if (mi != mapRelay.end()) {
1288  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1289  push = true;
1290  } else if (pfrom->timeLastMempoolReq) {
1291  auto txinfo = mempool.info(inv.hash);
1292  // To protect privacy, do not answer getdata using the mempool when
1293  // that TX couldn't have been INVed in reply to a MEMPOOL request.
1294  if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1295  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1296  push = true;
1297  }
1298  }
1299  if (!push) {
1300  vNotFound.push_back(inv);
1301  }
1302  }
1303  } // release cs_main
1304 
1305  if (it != pfrom->vRecvGetData.end() && !pfrom->fPauseSend) {
1306  const CInv &inv = *it;
1307  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK) {
1308  it++;
1309  ProcessGetBlockData(pfrom, chainparams, inv, connman);
1310  }
1311  }
1312 
1313  pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1314 
1315  if (!vNotFound.empty()) {
1316  // Let the peer know that we didn't find what it asked for, so it doesn't
1317  // have to wait around forever. Currently only SPV clients actually care
1318  // about this message: it's needed when they are recursively walking the
1319  // dependencies of relevant unconfirmed transactions. SPV clients want to
1320  // do that because they want to know about (and store and rebroadcast and
1321  // risk analyze) the dependencies of transactions relevant to them, without
1322  // having to download the entire memory pool.
1323  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1324  }
1325 }
1326 
1327 static uint32_t GetFetchFlags(CNode* pfrom) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1328  uint32_t nFetchFlags = 0;
1329  if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1330  nFetchFlags |= MSG_WITNESS_FLAG;
1331  }
1332  return nFetchFlags;
1333 }
1334 
1335 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
1336  BlockTransactions resp(req);
1337  for (size_t i = 0; i < req.indexes.size(); i++) {
1338  if (req.indexes[i] >= block.vtx.size()) {
1339  LOCK(cs_main);
1340  Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId()));
1341  return;
1342  }
1343  resp.txn[i] = block.vtx[req.indexes[i]];
1344  }
1345  LOCK(cs_main);
1346  const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1347  int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1348  connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1349 }
1350 
1351 bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
1352 {
1353  const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1354  size_t nCount = headers.size();
1355 
1356  if (nCount == 0) {
1357  // Nothing interesting. Stop asking this peers for more headers.
1358  return true;
1359  }
1360 
1361  bool received_new_header = false;
1362  const CBlockIndex *pindexLast = nullptr;
1363  {
1364  LOCK(cs_main);
1365  CNodeState *nodestate = State(pfrom->GetId());
1366 
1367  // If this looks like it could be a block announcement (nCount <
1368  // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1369  // don't connect:
1370  // - Send a getheaders message in response to try to connect the chain.
1371  // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1372  // don't connect before giving DoS points
1373  // - Once a headers message is received that is valid and does connect,
1374  // nUnconnectingHeaders gets reset back to 0.
1375  if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1376  nodestate->nUnconnectingHeaders++;
1378  LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1379  headers[0].GetHash().ToString(),
1380  headers[0].hashPrevBlock.ToString(),
1382  pfrom->GetId(), nodestate->nUnconnectingHeaders);
1383  // Set hashLastUnknownBlock for this peer, so that if we
1384  // eventually get the headers - even from a different peer -
1385  // we can use this peer to download.
1386  UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
1387 
1388  if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
1389  Misbehaving(pfrom->GetId(), 20);
1390  }
1391  return true;
1392  }
1393 
1394  uint256 hashLastBlock;
1395  for (const CBlockHeader& header : headers) {
1396  if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
1397  Misbehaving(pfrom->GetId(), 20, "non-continuous headers sequence");
1398  return false;
1399  }
1400  hashLastBlock = header.GetHash();
1401  }
1402 
1403  // If we don't have the last header, then they'll have given us
1404  // something new (if these headers are valid).
1405  if (!LookupBlockIndex(hashLastBlock)) {
1406  received_new_header = true;
1407  }
1408  }
1409 
1410  CValidationState state;
1411  CBlockHeader first_invalid_header;
1412  if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) {
1413  int nDoS;
1414  if (state.IsInvalid(nDoS)) {
1415  LOCK(cs_main);
1416  if (nDoS > 0) {
1417  Misbehaving(pfrom->GetId(), nDoS, "invalid header received");
1418  } else {
1419  LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId());
1420  }
1421  if (punish_duplicate_invalid && LookupBlockIndex(first_invalid_header.GetHash())) {
1422  // Goal: don't allow outbound peers to use up our outbound
1423  // connection slots if they are on incompatible chains.
1424  //
1425  // We ask the caller to set punish_invalid appropriately based
1426  // on the peer and the method of header delivery (compact
1427  // blocks are allowed to be invalid in some circumstances,
1428  // under BIP 152).
1429  // Here, we try to detect the narrow situation that we have a
1430  // valid block header (ie it was valid at the time the header
1431  // was received, and hence stored in mapBlockIndex) but know the
1432  // block is invalid, and that a peer has announced that same
1433  // block as being on its active chain.
1434  // Disconnect the peer in such a situation.
1435  //
1436  // Note: if the header that is invalid was not accepted to our
1437  // mapBlockIndex at all, that may also be grounds for
1438  // disconnecting the peer, as the chain they are on is likely
1439  // to be incompatible. However, there is a circumstance where
1440  // that does not hold: if the header's timestamp is more than
1441  // 2 hours ahead of our current time. In that case, the header
1442  // may become valid in the future, and we don't want to
1443  // disconnect a peer merely for serving us one too-far-ahead
1444  // block header, to prevent an attacker from splitting the
1445  // network by mining a block right at the 2 hour boundary.
1446  //
1447  // TODO: update the DoS logic (or, rather, rewrite the
1448  // DoS-interface between validation and net_processing) so that
1449  // the interface is cleaner, and so that we disconnect on all the
1450  // reasons that a peer's headers chain is incompatible
1451  // with ours (eg block->nVersion softforks, MTP violations,
1452  // etc), and not just the duplicate-invalid case.
1453  pfrom->fDisconnect = true;
1454  }
1455  return false;
1456  }
1457  }
1458 
1459  {
1460  LOCK(cs_main);
1461  CNodeState *nodestate = State(pfrom->GetId());
1462  if (nodestate->nUnconnectingHeaders > 0) {
1463  LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
1464  }
1465  nodestate->nUnconnectingHeaders = 0;
1466 
1467  //assert(pindexLast);
1468  if (!pindexLast) return true;
1469  UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1470 
1471  // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1472  // because it is set in UpdateBlockAvailability. Some nullptr checks
1473  // are still present, however, as belt-and-suspenders.
1474 
1475  if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) {
1476  nodestate->m_last_block_announcement = GetTime();
1477  }
1478 
1479  if (nCount == MAX_HEADERS_RESULTS) {
1480  // Headers message had its maximum size; the peer may have more headers.
1481  // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1482  // from there instead.
1483  LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1484  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
1485  }
1486 
1487  bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
1488  // If this set of headers is valid and ends in a block with at least as
1489  // much work as our tip, download as much as possible.
1490  if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
1491  std::vector<const CBlockIndex*> vToFetch;
1492  const CBlockIndex *pindexWalk = pindexLast;
1493  // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1494  while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1495  if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
1496  !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
1497  (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
1498  // We don't have this block, and it's not yet in flight.
1499  vToFetch.push_back(pindexWalk);
1500  }
1501  pindexWalk = pindexWalk->pprev;
1502  }
1503  // If pindexWalk still isn't on our main chain, we're looking at a
1504  // very large reorg at a time we think we're close to caught up to
1505  // the main chain -- this shouldn't really happen. Bail out on the
1506  // direct fetch and rely on parallel download instead.
1507  if (!chainActive.Contains(pindexWalk)) {
1508  LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
1509  pindexLast->GetBlockHash().ToString(),
1510  pindexLast->nHeight);
1511  } else {
1512  std::vector<CInv> vGetData;
1513  // Download as much as possible, from earliest to latest.
1514  for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
1515  if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1516  // Can't download any more from this peer
1517  break;
1518  }
1519  uint32_t nFetchFlags = GetFetchFlags(pfrom);
1520  vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
1521  MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
1522  LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1523  pindex->GetBlockHash().ToString(), pfrom->GetId());
1524  }
1525  if (vGetData.size() > 1) {
1526  LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1527  pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
1528  }
1529  if (vGetData.size() > 0) {
1530  if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1531  // In any case, we want to download using a compact block, not a regular one
1532  vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
1533  }
1534  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
1535  }
1536  }
1537  }
1538  // If we're in IBD, we want outbound peers that will serve us a useful
1539  // chain. Disconnect peers that are on chains with insufficient work.
1540  if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
1541  // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1542  // headers to fetch from this peer.
1543  if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1544  // This peer has too little work on their headers chain to help
1545  // us sync -- disconnect if using an outbound slot (unless
1546  // whitelisted or addnode).
1547  // Note: We compare their tip to nMinimumChainWork (rather than
1548  // chainActive.Tip()) because we won't start block download
1549  // until we have a headers chain that has at least
1550  // nMinimumChainWork, even if a peer has a chain past our tip,
1551  // as an anti-DoS measure.
1552  if (IsOutboundDisconnectionCandidate(pfrom)) {
1553  LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
1554  pfrom->fDisconnect = true;
1555  }
1556  }
1557  }
1558 
1559  if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
1560  // If this is an outbound peer, check to see if we should protect
1561  // it from the bad/lagging chain logic.
1562  if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
1563  LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId());
1564  nodestate->m_chain_sync.m_protect = true;
1565  ++g_outbound_peers_with_protect_from_disconnect;
1566  }
1567  }
1568  }
1569 
1570  return true;
1571 }
1572 
1573 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc, bool enable_bip61)
1574 {
1575  LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1576  if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
1577  {
1578  LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1579  return true;
1580  }
1581 
1582 
1583  if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1584  (strCommand == NetMsgType::FILTERLOAD ||
1585  strCommand == NetMsgType::FILTERADD))
1586  {
1587  if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1588  LOCK(cs_main);
1589  Misbehaving(pfrom->GetId(), 100);
1590  return false;
1591  } else {
1592  pfrom->fDisconnect = true;
1593  return false;
1594  }
1595  }
1596 
1597  if (strCommand == NetMsgType::REJECT)
1598  {
1599  if (LogAcceptCategory(BCLog::NET)) {
1600  try {
1601  std::string strMsg; unsigned char ccode; std::string strReason;
1602  vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1603 
1604  std::ostringstream ss;
1605  ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1606 
1607  if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1608  {
1609  uint256 hash;
1610  vRecv >> hash;
1611  ss << ": hash " << hash.ToString();
1612  }
1613  LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1614  } catch (const std::ios_base::failure&) {
1615  // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1616  LogPrint(BCLog::NET, "Unparseable reject message received\n");
1617  }
1618  }
1619  return true;
1620  }
1621 
1622  if (strCommand == NetMsgType::VERSION) {
1623  // Each connection can only send one version message
1624  if (pfrom->nVersion != 0)
1625  {
1626  if (enable_bip61) {
1627  connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1628  }
1629  LOCK(cs_main);
1630  Misbehaving(pfrom->GetId(), 1);
1631  return false;
1632  }
1633 
1634  int64_t nTime;
1635  CAddress addrMe;
1636  CAddress addrFrom;
1637  uint64_t nNonce = 1;
1638  uint64_t nServiceInt;
1639  ServiceFlags nServices;
1640  int nVersion;
1641  int nSendVersion;
1642  std::string strSubVer;
1643  std::string cleanSubVer;
1644  int nStartingHeight = -1;
1645  bool fRelay = true;
1646 
1647  vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1648  nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1649  nServices = ServiceFlags(nServiceInt);
1650  if (!pfrom->fInbound)
1651  {
1652  connman->SetServices(pfrom->addr, nServices);
1653  }
1654  if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
1655  {
1656  LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
1657  if (enable_bip61) {
1658  connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1659  strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
1660  }
1661  pfrom->fDisconnect = true;
1662  return false;
1663  }
1664 
1665  if (nVersion < MIN_PEER_PROTO_VERSION) {
1666  // disconnect from peers older than this proto version
1667  LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1668  if (enable_bip61) {
1669  connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1670  strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1671  }
1672  pfrom->fDisconnect = true;
1673  return false;
1674  }
1675 
1676  if (!vRecv.empty())
1677  vRecv >> addrFrom >> nNonce;
1678  if (!vRecv.empty()) {
1679  vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1680  cleanSubVer = SanitizeString(strSubVer);
1681  }
1682  if (!vRecv.empty()) {
1683  vRecv >> nStartingHeight;
1684  }
1685  if (!vRecv.empty())
1686  vRecv >> fRelay;
1687  // Disconnect if we connected to ourself
1688  if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
1689  {
1690  LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1691  pfrom->fDisconnect = true;
1692  return true;
1693  }
1694 
1695  if (pfrom->fInbound && addrMe.IsRoutable())
1696  {
1697  SeenLocal(addrMe);
1698  }
1699 
1700  // Be shy and don't send version until we hear
1701  if (pfrom->fInbound)
1702  PushNodeVersion(pfrom, connman, GetAdjustedTime());
1703 
1704  connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1705 
1706  pfrom->nServices = nServices;
1707  pfrom->SetAddrLocal(addrMe);
1708  {
1709  LOCK(pfrom->cs_SubVer);
1710  pfrom->strSubVer = strSubVer;
1711  pfrom->cleanSubVer = cleanSubVer;
1712  }
1713  pfrom->nStartingHeight = nStartingHeight;
1714 
1715  // set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients"
1716  pfrom->fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED));
1717 
1718  // set nodes not capable of serving the complete blockchain history as "limited nodes"
1719  pfrom->m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED));
1720 
1721  {
1722  LOCK(pfrom->cs_filter);
1723  pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1724  }
1725 
1726  // Change version
1727  pfrom->SetSendVersion(nSendVersion);
1728  pfrom->nVersion = nVersion;
1729 
1730  if((nServices & NODE_WITNESS))
1731  {
1732  LOCK(cs_main);
1733  State(pfrom->GetId())->fHaveWitness = true;
1734  }
1735 
1736  // Potentially mark this peer as a preferred download peer.
1737  {
1738  LOCK(cs_main);
1739  UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1740  }
1741 
1742  if (!pfrom->fInbound)
1743  {
1744  // Advertise our address
1745  if (fListen && !IsInitialBlockDownload())
1746  {
1747  CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1748  FastRandomContext insecure_rand;
1749  if (addr.IsRoutable())
1750  {
1751  LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1752  pfrom->PushAddress(addr, insecure_rand);
1753  } else if (IsPeerAddrLocalGood(pfrom)) {
1754  addr.SetIP(addrMe);
1755  LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1756  pfrom->PushAddress(addr, insecure_rand);
1757  }
1758  }
1759 
1760  // Get recent addresses
1761  if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
1762  {
1763  connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1764  pfrom->fGetAddr = true;
1765  }
1766  connman->MarkAddressGood(pfrom->addr);
1767  }
1768 
1769  std::string remoteAddr;
1770  if (fLogIPs)
1771  remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1772 
1773  LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1774  cleanSubVer, pfrom->nVersion,
1775  pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1776  remoteAddr);
1777 
1778  int64_t nTimeOffset = nTime - GetTime();
1779  pfrom->nTimeOffset = nTimeOffset;
1780  AddTimeData(pfrom->addr, nTimeOffset);
1781 
1782  // If the peer is old enough to have the old alert system, send it the final alert.
1783  if (pfrom->nVersion <= 70012) {
1784  CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1785  connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1786  }
1787 
1788  // Feeler connections exist only to verify if address is online.
1789  if (pfrom->fFeeler) {
1790  assert(pfrom->fInbound == false);
1791  pfrom->fDisconnect = true;
1792  }
1793  return true;
1794  }
1795 
1796  if (pfrom->nVersion == 0) {
1797  // Must have a version message before anything else
1798  LOCK(cs_main);
1799  Misbehaving(pfrom->GetId(), 1);
1800  return false;
1801  }
1802 
1803  // At this point, the outgoing message serialization version can't change.
1804  const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1805 
1806  if (strCommand == NetMsgType::VERACK)
1807  {
1808  pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1809 
1810  if (!pfrom->fInbound) {
1811  // Mark this node as currently connected, so we update its timestamp later.
1812  LOCK(cs_main);
1813  State(pfrom->GetId())->fCurrentlyConnected = true;
1814  LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n",
1815  pfrom->nVersion.load(), pfrom->nStartingHeight, pfrom->GetId(),
1816  (fLogIPs ? strprintf(", peeraddr=%s", pfrom->addr.ToString()) : ""));
1817  }
1818 
1819  if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1820  // Tell our peer we prefer to receive headers rather than inv's
1821  // We send this to non-NODE NETWORK peers as well, because even
1822  // non-NODE NETWORK peers can announce blocks (such as pruning
1823  // nodes)
1824  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1825  }
1826  if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1827  // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1828  // However, we do not request new block announcements using
1829  // cmpctblock messages.
1830  // We send this to non-NODE NETWORK peers as well, because
1831  // they may wish to request compact blocks from us
1832  bool fAnnounceUsingCMPCTBLOCK = false;
1833  uint64_t nCMPCTBLOCKVersion = 2;
1834  if (pfrom->GetLocalServices() & NODE_WITNESS)
1835  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1836  nCMPCTBLOCKVersion = 1;
1837  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1838  }
1839  pfrom->fSuccessfullyConnected = true;
1840  return true;
1841  }
1842 
1843  if (!pfrom->fSuccessfullyConnected) {
1844  // Must have a verack message before anything else
1845  LOCK(cs_main);
1846  Misbehaving(pfrom->GetId(), 1);
1847  return false;
1848  }
1849 
1850  if (strCommand == NetMsgType::ADDR) {
1851  std::vector<CAddress> vAddr;
1852  vRecv >> vAddr;
1853 
1854  // Don't want addr from older versions unless seeding
1855  if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
1856  return true;
1857  if (vAddr.size() > 1000)
1858  {
1859  LOCK(cs_main);
1860  Misbehaving(pfrom->GetId(), 20, strprintf("message addr size() = %u", vAddr.size()));
1861  return false;
1862  }
1863 
1864  // Store the new addresses
1865  std::vector<CAddress> vAddrOk;
1866  int64_t nNow = GetAdjustedTime();
1867  int64_t nSince = nNow - 10 * 60;
1868  for (CAddress& addr : vAddr)
1869  {
1870  if (interruptMsgProc)
1871  return true;
1872 
1873  // We only bother storing full nodes, though this may include
1874  // things which we would not make an outbound connection to, in
1875  // part because we may make feeler connections to them.
1876  if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices))
1877  continue;
1878 
1879  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1880  addr.nTime = nNow - 5 * 24 * 60 * 60;
1881  pfrom->AddAddressKnown(addr);
1882  bool fReachable = IsReachable(addr);
1883  if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1884  {
1885  // Relay to a limited number of other nodes
1886  RelayAddress(addr, fReachable, connman);
1887  }
1888  // Do not store addresses outside our network
1889  if (fReachable)
1890  vAddrOk.push_back(addr);
1891  }
1892  connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1893  if (vAddr.size() < 1000)
1894  pfrom->fGetAddr = false;
1895  if (pfrom->fOneShot)
1896  pfrom->fDisconnect = true;
1897  return true;
1898  }
1899 
1900  if (strCommand == NetMsgType::SENDHEADERS) {
1901  LOCK(cs_main);
1902  State(pfrom->GetId())->fPreferHeaders = true;
1903  return true;
1904  }
1905 
1906  if (strCommand == NetMsgType::SENDCMPCT) {
1907  bool fAnnounceUsingCMPCTBLOCK = false;
1908  uint64_t nCMPCTBLOCKVersion = 0;
1909  vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1910  if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1911  LOCK(cs_main);
1912  // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1913  if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1914  State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1915  State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1916  }
1917  if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1918  State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1919  if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1920  if (pfrom->GetLocalServices() & NODE_WITNESS)
1921  State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1922  else
1923  State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1924  }
1925  }
1926  return true;
1927  }
1928 
1929  if (strCommand == NetMsgType::INV) {
1930  std::vector<CInv> vInv;
1931  vRecv >> vInv;
1932  if (vInv.size() > MAX_INV_SZ)
1933  {
1934  LOCK(cs_main);
1935  Misbehaving(pfrom->GetId(), 20, strprintf("message inv size() = %u", vInv.size()));
1936  return false;
1937  }
1938 
1939  bool fBlocksOnly = !fRelayTxes;
1940 
1941  // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1942  if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1943  fBlocksOnly = false;
1944 
1945  LOCK(cs_main);
1946 
1947  uint32_t nFetchFlags = GetFetchFlags(pfrom);
1948 
1949  for (CInv &inv : vInv)
1950  {
1951  if (interruptMsgProc)
1952  return true;
1953 
1954  bool fAlreadyHave = AlreadyHave(inv);
1955  LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1956 
1957  if (inv.type == MSG_TX) {
1958  inv.type |= nFetchFlags;
1959  }
1960 
1961  if (inv.type == MSG_BLOCK) {
1962  UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1963  if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1964  // We used to request the full block here, but since headers-announcements are now the
1965  // primary method of announcement on the network, and since, in the case that a node
1966  // fell back to inv we probably have a reorg which we should get the headers for first,
1967  // we now only provide a getheaders response here. When we receive the headers, we will
1968  // then ask for the blocks we need.
1969  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1970  LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1971  }
1972  }
1973  else
1974  {
1975  pfrom->AddInventoryKnown(inv);
1976  if (fBlocksOnly) {
1977  LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1978  } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1979  pfrom->AskFor(inv);
1980  }
1981  }
1982  }
1983  return true;
1984  }
1985 
1986  if (strCommand == NetMsgType::GETDATA) {
1987  std::vector<CInv> vInv;
1988  vRecv >> vInv;
1989  if (vInv.size() > MAX_INV_SZ)
1990  {
1991  LOCK(cs_main);
1992  Misbehaving(pfrom->GetId(), 20, strprintf("message getdata size() = %u", vInv.size()));
1993  return false;
1994  }
1995 
1996  LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1997 
1998  if (vInv.size() > 0) {
1999  LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
2000  }
2001 
2002  pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
2003  ProcessGetData(pfrom, chainparams, connman, interruptMsgProc);
2004  return true;
2005  }
2006 
2007  if (strCommand == NetMsgType::GETBLOCKS) {
2008  CBlockLocator locator;
2009  uint256 hashStop;
2010  vRecv >> locator >> hashStop;
2011 
2012  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
2013  LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
2014  pfrom->fDisconnect = true;
2015  return true;
2016  }
2017 
2018  // We might have announced the currently-being-connected tip using a
2019  // compact block, which resulted in the peer sending a getblocks
2020  // request, which we would otherwise respond to without the new block.
2021  // To avoid this situation we simply verify that we are on our best
2022  // known chain now. This is super overkill, but we handle it better
2023  // for getheaders requests, and there are no known nodes which support
2024  // compact blocks but still use getblocks to request blocks.
2025  {
2026  std::shared_ptr<const CBlock> a_recent_block;
2027  {
2028  LOCK(cs_most_recent_block);
2029  a_recent_block = most_recent_block;
2030  }
2031  CValidationState state;
2032  if (!ActivateBestChain(state, Params(), a_recent_block)) {
2033  LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state));
2034  }
2035  }
2036 
2037  LOCK(cs_main);
2038 
2039  // Find the last block the caller has in the main chain
2040  const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
2041 
2042  // Send the rest of the chain
2043  if (pindex)
2044  pindex = chainActive.Next(pindex);
2045  int nLimit = 500;
2046  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());
2047  for (; pindex; pindex = chainActive.Next(pindex))
2048  {
2049  if (pindex->GetBlockHash() == hashStop)
2050  {
2051  LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2052  break;
2053  }
2054  // If pruning, don't inv blocks unless we have on disk and are likely to still have
2055  // for some reasonable time window (1 hour) that block relay might require.
2056  const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
2057  if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
2058  {
2059  LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2060  break;
2061  }
2062  pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2063  if (--nLimit <= 0)
2064  {
2065  // When this block is requested, we'll send an inv that'll
2066  // trigger the peer to getblocks the next batch of inventory.
2067  LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2068  pfrom->hashContinue = pindex->GetBlockHash();
2069  break;
2070  }
2071  }
2072  return true;
2073  }
2074 
2075  if (strCommand == NetMsgType::GETBLOCKTXN) {
2077  vRecv >> req;
2078 
2079  std::shared_ptr<const CBlock> recent_block;
2080  {
2081  LOCK(cs_most_recent_block);
2082  if (most_recent_block_hash == req.blockhash)
2083  recent_block = most_recent_block;
2084  // Unlock cs_most_recent_block to avoid cs_main lock inversion
2085  }
2086  if (recent_block) {
2087  SendBlockTransactions(*recent_block, req, pfrom, connman);
2088  return true;
2089  }
2090 
2091  LOCK(cs_main);
2092 
2093  const CBlockIndex* pindex = LookupBlockIndex(req.blockhash);
2094  if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) {
2095  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom->GetId());
2096  return true;
2097  }
2098 
2099  if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
2100  // If an older block is requested (should never happen in practice,
2101  // but can happen in tests) send a block response instead of a
2102  // blocktxn response. Sending a full block response instead of a
2103  // small blocktxn response is preferable in the case where a peer
2104  // might maliciously send lots of getblocktxn requests to trigger
2105  // expensive disk reads, because it will require the peer to
2106  // actually receive all the data read from disk over the network.
2107  LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
2108  CInv inv;
2109  inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
2110  inv.hash = req.blockhash;
2111  pfrom->vRecvGetData.push_back(inv);
2112  // The message processing loop will go around again (without pausing) and we'll respond then (without cs_main)
2113  return true;
2114  }
2115 
2116  CBlock block;
2117  bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus());
2118  assert(ret);
2119 
2120  SendBlockTransactions(block, req, pfrom, connman);
2121  return true;
2122  }
2123 
2124  if (strCommand == NetMsgType::GETHEADERS) {
2125  CBlockLocator locator;
2126  uint256 hashStop;
2127  vRecv >> locator >> hashStop;
2128 
2129  if (locator.vHave.size() > MAX_LOCATOR_SZ) {
2130  LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId());
2131  pfrom->fDisconnect = true;
2132  return true;
2133  }
2134 
2135  LOCK(cs_main);
2136  if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
2137  LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
2138  return true;
2139  }
2140 
2141  CNodeState *nodestate = State(pfrom->GetId());
2142  const CBlockIndex* pindex = nullptr;
2143  if (locator.IsNull())
2144  {
2145  // If locator is null, return the hashStop block
2146  pindex = LookupBlockIndex(hashStop);
2147  if (!pindex) {
2148  return true;
2149  }
2150 
2151  if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
2152  LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
2153  return true;
2154  }
2155  }
2156  else
2157  {
2158  // Find the last block the caller has in the main chain
2159  pindex = FindForkInGlobalIndex(chainActive, locator);
2160  if (pindex)
2161  pindex = chainActive.Next(pindex);
2162  }
2163 
2164  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2165  std::vector<CBlock> vHeaders;
2166  int nLimit = MAX_HEADERS_RESULTS;
2167  LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
2168  for (; pindex; pindex = chainActive.Next(pindex))
2169  {
2170  vHeaders.push_back(pindex->GetBlockHeader());
2171  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2172  break;
2173  }
2174  // pindex can be nullptr either if we sent chainActive.Tip() OR
2175  // if our peer has chainActive.Tip() (and thus we are sending an empty
2176  // headers message). In both cases it's safe to update
2177  // pindexBestHeaderSent to be our tip.
2178  //
2179  // It is important that we simply reset the BestHeaderSent value here,
2180  // and not max(BestHeaderSent, newHeaderSent). We might have announced
2181  // the currently-being-connected tip using a compact block, which
2182  // resulted in the peer sending a headers request, which we respond to
2183  // without the new block. By resetting the BestHeaderSent, we ensure we
2184  // will re-announce the new block via headers (or compact blocks again)
2185  // in the SendMessages logic.
2186  nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
2187  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2188  return true;
2189  }
2190 
2191  if (strCommand == NetMsgType::TX) {
2192  // Stop processing the transaction early if
2193  // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2194  if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
2195  {
2196  LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
2197  return true;
2198  }
2199 
2200  std::deque<COutPoint> vWorkQueue;
2201  std::vector<uint256> vEraseQueue;
2202  CTransactionRef ptx;
2203  vRecv >> ptx;
2204  const CTransaction& tx = *ptx;
2205 
2206  CInv inv(MSG_TX, tx.GetHash());
2207  pfrom->AddInventoryKnown(inv);
2208 
2210 
2211  bool fMissingInputs = false;
2212  CValidationState state;
2213 
2214  pfrom->setAskFor.erase(inv.hash);
2215  mapAlreadyAskedFor.erase(inv.hash);
2216 
2217  std::list<CTransactionRef> lRemovedTxn;
2218 
2219  if (!AlreadyHave(inv) &&
2220  AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2221  mempool.check(pcoinsTip.get());
2222  RelayTransaction(tx, connman);
2223  for (unsigned int i = 0; i < tx.vout.size(); i++) {
2224  vWorkQueue.emplace_back(inv.hash, i);
2225  }
2226 
2227  pfrom->nLastTXTime = GetTime();
2228 
2229  LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2230  pfrom->GetId(),
2231  tx.GetHash().ToString(),
2232  mempool.size(), mempool.DynamicMemoryUsage() / 1000);
2233 
2234  // Recursively process any orphan transactions that depended on this one
2235  std::set<NodeId> setMisbehaving;
2236  while (!vWorkQueue.empty()) {
2237  auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
2238  vWorkQueue.pop_front();
2239  if (itByPrev == mapOrphanTransactionsByPrev.end())
2240  continue;
2241  for (auto mi = itByPrev->second.begin();
2242  mi != itByPrev->second.end();
2243  ++mi)
2244  {
2245  const CTransactionRef& porphanTx = (*mi)->second.tx;
2246  const CTransaction& orphanTx = *porphanTx;
2247  const uint256& orphanHash = orphanTx.GetHash();
2248  NodeId fromPeer = (*mi)->second.fromPeer;
2249  bool fMissingInputs2 = false;
2250  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2251  // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2252  // anyone relaying LegitTxX banned)
2253  CValidationState stateDummy;
2254 
2255 
2256  if (setMisbehaving.count(fromPeer))
2257  continue;
2258  if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2259  LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2260  RelayTransaction(orphanTx, connman);
2261  for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
2262  vWorkQueue.emplace_back(orphanHash, i);
2263  }
2264  vEraseQueue.push_back(orphanHash);
2265  }
2266  else if (!fMissingInputs2)
2267  {
2268  int nDos = 0;
2269  if (stateDummy.IsInvalid(nDos) && nDos > 0)
2270  {
2271  // Punish peer that gave us an invalid orphan tx
2272  Misbehaving(fromPeer, nDos);
2273  setMisbehaving.insert(fromPeer);
2274  LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
2275  }
2276  // Has inputs but not accepted to mempool
2277  // Probably non-standard or insufficient fee
2278  LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2279  vEraseQueue.push_back(orphanHash);
2280  if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
2281  // Do not use rejection cache for witness transactions or
2282  // witness-stripped transactions, as they can have been malleated.
2283  // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2284  assert(recentRejects);
2285  recentRejects->insert(orphanHash);
2286  }
2287  }
2288  mempool.check(pcoinsTip.get());
2289  }
2290  }
2291 
2292  for (const uint256& hash : vEraseQueue)
2293  EraseOrphanTx(hash);
2294  }
2295  else if (fMissingInputs)
2296  {
2297  bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
2298  for (const CTxIn& txin : tx.vin) {
2299  if (recentRejects->contains(txin.prevout.hash)) {
2300  fRejectedParents = true;
2301  break;
2302  }
2303  }
2304  if (!fRejectedParents) {
2305  uint32_t nFetchFlags = GetFetchFlags(pfrom);
2306  for (const CTxIn& txin : tx.vin) {
2307  CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
2308  pfrom->AddInventoryKnown(_inv);
2309  if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
2310  }
2311  AddOrphanTx(ptx, pfrom->GetId());
2312 
2313  // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2314  unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
2315  unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
2316  if (nEvicted > 0) {
2317  LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
2318  }
2319  } else {
2320  LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
2321  // We will continue to reject this tx since it has rejected
2322  // parents so avoid re-requesting it from other peers.
2323  recentRejects->insert(tx.GetHash());
2324  }
2325  } else {
2326  if (!tx.HasWitness() && !state.CorruptionPossible()) {
2327  // Do not use rejection cache for witness transactions or
2328  // witness-stripped transactions, as they can have been malleated.
2329  // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2330  assert(recentRejects);
2331  recentRejects->insert(tx.GetHash());
2332  if (RecursiveDynamicUsage(*ptx) < 100000) {
2333  AddToCompactExtraTransactions(ptx);
2334  }
2335  } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
2336  AddToCompactExtraTransactions(ptx);
2337  }
2338 
2339  if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
2340  // Always relay transactions received from whitelisted peers, even
2341  // if they were already in the mempool or rejected from it due
2342  // to policy, allowing the node to function as a gateway for
2343  // nodes hidden behind it.
2344  //
2345  // Never relay transactions that we would assign a non-zero DoS
2346  // score for, as we expect peers to do the same with us in that
2347  // case.
2348  int nDoS = 0;
2349  if (!state.IsInvalid(nDoS) || nDoS == 0) {
2350  LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
2351  RelayTransaction(tx, connman);
2352  } else {
2353  LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
2354  }
2355  }
2356  }
2357 
2358  for (const CTransactionRef& removedTx : lRemovedTxn)
2359  AddToCompactExtraTransactions(removedTx);
2360 
2361  int nDoS = 0;
2362  if (state.IsInvalid(nDoS))
2363  {
2364  LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
2365  pfrom->GetId(),
2366  FormatStateMessage(state));
2367  if (enable_bip61 && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) { // Never send AcceptToMemoryPool's internal codes over P2P
2368  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
2369  state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
2370  }
2371  if (nDoS > 0) {
2372  Misbehaving(pfrom->GetId(), nDoS);
2373  }
2374  }
2375  return true;
2376  }
2377 
2378  if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2379  {
2380  CBlockHeaderAndShortTxIDs cmpctblock;
2381  vRecv >> cmpctblock;
2382 
2383  bool received_new_header = false;
2384 
2385  {
2386  LOCK(cs_main);
2387 
2388  if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
2389  // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2390  if (!IsInitialBlockDownload())
2392  return true;
2393  }
2394 
2395  if (!LookupBlockIndex(cmpctblock.header.GetHash())) {
2396  received_new_header = true;
2397  }
2398  }
2399 
2400  const CBlockIndex *pindex = nullptr;
2401  CValidationState state;
2402  if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
2403  int nDoS;
2404  if (state.IsInvalid(nDoS)) {
2405  if (nDoS > 0) {
2406  LOCK(cs_main);
2407  Misbehaving(pfrom->GetId(), nDoS, strprintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId()));
2408  } else {
2409  LogPrint(BCLog::NET, "Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2410  }
2411  return true;
2412  }
2413  }
2414 
2415  // When we succeed in decoding a block's txids from a cmpctblock
2416  // message we typically jump to the BLOCKTXN handling code, with a
2417  // dummy (empty) BLOCKTXN message, to re-use the logic there in
2418  // completing processing of the putative block (without cs_main).
2419  bool fProcessBLOCKTXN = false;
2420  CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2421 
2422  // If we end up treating this as a plain headers message, call that as well
2423  // without cs_main.
2424  bool fRevertToHeaderProcessing = false;
2425 
2426  // Keep a CBlock for "optimistic" compactblock reconstructions (see
2427  // below)
2428  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2429  bool fBlockReconstructed = false;
2430 
2431  {
2433  // If AcceptBlockHeader returned true, it set pindex
2434  assert(pindex);
2435  UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2436 
2437  CNodeState *nodestate = State(pfrom->GetId());
2438 
2439  // If this was a new header with more work than our tip, update the
2440  // peer's last block announcement time
2441  if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) {
2442  nodestate->m_last_block_announcement = GetTime();
2443  }
2444 
2445  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2446  bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2447 
2448  if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2449  return true;
2450 
2451  if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2452  pindex->nTx != 0) { // We had this block at some point, but pruned it
2453  if (fAlreadyInFlight) {
2454  // We requested this block for some reason, but our mempool will probably be useless
2455  // so we just grab the block via normal getdata
2456  std::vector<CInv> vInv(1);
2457  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2458  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2459  }
2460  return true;
2461  }
2462 
2463  // If we're not close to tip yet, give up and let parallel block fetch work its magic
2464  if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2465  return true;
2466 
2467  if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2468  // Don't bother trying to process compact blocks from v1 peers
2469  // after segwit activates.
2470  return true;
2471  }
2472 
2473  // We want to be a bit conservative just to be extra careful about DoS
2474  // possibilities in compact block processing...
2475  if (pindex->nHeight <= chainActive.Height() + 2) {
2476  if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2477  (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2478  std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
2479  if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2480  if (!(*queuedBlockIt)->partialBlock)
2481  (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2482  else {
2483  // The block was already in flight using compact blocks from the same peer
2484  LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2485  return true;
2486  }
2487  }
2488 
2489  PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2490  ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2491  if (status == READ_STATUS_INVALID) {
2492  MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2493  Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block\n", pfrom->GetId()));
2494  return true;
2495  } else if (status == READ_STATUS_FAILED) {
2496  // Duplicate txindexes, the block is now in-flight, so just request it
2497  std::vector<CInv> vInv(1);
2498  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2499  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2500  return true;
2501  }
2502 
2504  for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2505  if (!partialBlock.IsTxAvailable(i))
2506  req.indexes.push_back(i);
2507  }
2508  if (req.indexes.empty()) {
2509  // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2510  BlockTransactions txn;
2511  txn.blockhash = cmpctblock.header.GetHash();
2512  blockTxnMsg << txn;
2513  fProcessBLOCKTXN = true;
2514  } else {
2515  req.blockhash = pindex->GetBlockHash();
2516  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2517  }
2518  } else {
2519  // This block is either already in flight from a different
2520  // peer, or this peer has too many blocks outstanding to
2521  // download from.
2522  // Optimistically try to reconstruct anyway since we might be
2523  // able to without any round trips.
2524  PartiallyDownloadedBlock tempBlock(&mempool);
2525  ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2526  if (status != READ_STATUS_OK) {
2527  // TODO: don't ignore failures
2528  return true;
2529  }
2530  std::vector<CTransactionRef> dummy;
2531  status = tempBlock.FillBlock(*pblock, dummy);
2532  if (status == READ_STATUS_OK) {
2533  fBlockReconstructed = true;
2534  }
2535  }
2536  } else {
2537  if (fAlreadyInFlight) {
2538  // We requested this block, but its far into the future, so our
2539  // mempool will probably be useless - request the block normally
2540  std::vector<CInv> vInv(1);
2541  vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2542  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2543  return true;
2544  } else {
2545  // If this was an announce-cmpctblock, we want the same treatment as a header message
2546  fRevertToHeaderProcessing = true;
2547  }
2548  }
2549  } // cs_main
2550 
2551  if (fProcessBLOCKTXN)
2552  return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc, enable_bip61);
2553 
2554  if (fRevertToHeaderProcessing) {
2555  // Headers received from HB compact block peers are permitted to be
2556  // relayed before full validation (see BIP 152), so we don't want to disconnect
2557  // the peer if the header turns out to be for an invalid block.
2558  // Note that if a peer tries to build on an invalid chain, that
2559  // will be detected and the peer will be banned.
2560  return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
2561  }
2562 
2563  if (fBlockReconstructed) {
2564  // If we got here, we were able to optimistically reconstruct a
2565  // block that is in flight from some other peer.
2566  {
2567  LOCK(cs_main);
2568  mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2569  }
2570  bool fNewBlock = false;
2571  // Setting fForceProcessing to true means that we bypass some of
2572  // our anti-DoS protections in AcceptBlock, which filters
2573  // unrequested blocks that might be trying to waste our resources
2574  // (eg disk space). Because we only try to reconstruct blocks when
2575  // we're close to caught up (via the CanDirectFetch() requirement
2576  // above, combined with the behavior of not requesting blocks until
2577  // we have a chain with at least nMinimumChainWork), and we ignore
2578  // compact blocks with less work than our tip, it is safe to treat
2579  // reconstructed compact blocks as having been requested.
2580  ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2581  if (fNewBlock) {
2582  pfrom->nLastBlockTime = GetTime();
2583  } else {
2584  LOCK(cs_main);
2585  mapBlockSource.erase(pblock->GetHash());
2586  }
2587  LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2588  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2589  // Clear download state for this block, which is in
2590  // process from some other peer. We do this after calling
2591  // ProcessNewBlock so that a malleated cmpctblock announcement
2592  // can't be used to interfere with block relay.
2593  MarkBlockAsReceived(pblock->GetHash());
2594  }
2595  }
2596  return true;
2597  }
2598 
2599  if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2600  {
2601  BlockTransactions resp;
2602  vRecv >> resp;
2603 
2604  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2605  bool fBlockRead = false;
2606  {
2607  LOCK(cs_main);
2608 
2609  std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2610  if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2611  it->second.first != pfrom->GetId()) {
2612  LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2613  return true;
2614  }
2615 
2616  PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2617  ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2618  if (status == READ_STATUS_INVALID) {
2619  MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2620  Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId()));
2621  return true;
2622  } else if (status == READ_STATUS_FAILED) {
2623  // Might have collided, fall back to getdata now :(
2624  std::vector<CInv> invs;
2625  invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2626  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2627  } else {
2628  // Block is either okay, or possibly we received
2629  // READ_STATUS_CHECKBLOCK_FAILED.
2630  // Note that CheckBlock can only fail for one of a few reasons:
2631  // 1. bad-proof-of-work (impossible here, because we've already
2632  // accepted the header)
2633  // 2. merkleroot doesn't match the transactions given (already
2634  // caught in FillBlock with READ_STATUS_FAILED, so
2635  // impossible here)
2636  // 3. the block is otherwise invalid (eg invalid coinbase,
2637  // block is too big, too many legacy sigops, etc).
2638  // So if CheckBlock failed, #3 is the only possibility.
2639  // Under BIP 152, we don't DoS-ban unless proof of work is
2640  // invalid (we don't require all the stateless checks to have
2641  // been run). This is handled below, so just treat this as
2642  // though the block was successfully read, and rely on the
2643  // handling in ProcessNewBlock to ensure the block index is
2644  // updated, reject messages go out, etc.
2645  MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2646  fBlockRead = true;
2647  // mapBlockSource is only used for sending reject messages and DoS scores,
2648  // so the race between here and cs_main in ProcessNewBlock is fine.
2649  // BIP 152 permits peers to relay compact blocks after validating
2650  // the header only; we should not punish peers if the block turns
2651  // out to be invalid.
2652  mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2653  }
2654  } // Don't hold cs_main when we call into ProcessNewBlock
2655  if (fBlockRead) {
2656  bool fNewBlock = false;
2657  // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2658  // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2659  // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2660  // disk-space attacks), but this should be safe due to the
2661  // protections in the compact block handler -- see related comment
2662  // in compact block optimistic reconstruction handling.
2663  ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2664  if (fNewBlock) {
2665  pfrom->nLastBlockTime = GetTime();
2666  } else {
2667  LOCK(cs_main);
2668  mapBlockSource.erase(pblock->GetHash());
2669  }
2670  }
2671  return true;
2672  }
2673 
2674  if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2675  {
2676  std::vector<CBlockHeader> headers;
2677 
2678  // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2679  unsigned int nCount = ReadCompactSize(vRecv);
2680  if (nCount > MAX_HEADERS_RESULTS) {
2681  LOCK(cs_main);
2682  Misbehaving(pfrom->GetId(), 20, strprintf("headers message size = %u", nCount));
2683  return false;
2684  }
2685  headers.resize(nCount);
2686  for (unsigned int n = 0; n < nCount; n++) {
2687  vRecv >> headers[n];
2688  ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2689  }
2690 
2691  // Headers received via a HEADERS message should be valid, and reflect
2692  // the chain the peer is on. If we receive a known-invalid header,
2693  // disconnect the peer if it is using one of our outbound connection
2694  // slots.
2695  bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
2696  return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
2697  }
2698 
2699  if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2700  {
2701  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2702  vRecv >> *pblock;
2703 
2704  LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2705 
2706  bool forceProcessing = false;
2707  const uint256 hash(pblock->GetHash());
2708  {
2709  LOCK(cs_main);
2710  // Also always process if we requested the block explicitly, as we may
2711  // need it even though it is not a candidate for a new best tip.
2712  forceProcessing |= MarkBlockAsReceived(hash);
2713  // mapBlockSource is only used for sending reject messages and DoS scores,
2714  // so the race between here and cs_main in ProcessNewBlock is fine.
2715  mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2716  }
2717  bool fNewBlock = false;
2718  ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2719  if (fNewBlock) {
2720  pfrom->nLastBlockTime = GetTime();
2721  } else {
2722  LOCK(cs_main);
2723  mapBlockSource.erase(pblock->GetHash());
2724  }
2725  return true;
2726  }
2727 
2728  if (strCommand == NetMsgType::GETADDR) {
2729  // This asymmetric behavior for inbound and outbound connections was introduced
2730  // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2731  // to users' AddrMan and later request them by sending getaddr messages.
2732  // Making nodes which are behind NAT and can only make outgoing connections ignore
2733  // the getaddr message mitigates the attack.
2734  if (!pfrom->fInbound) {
2735  LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2736  return true;
2737  }
2738 
2739  // Only send one GetAddr response per connection to reduce resource waste
2740  // and discourage addr stamping of INV announcements.
2741  if (pfrom->fSentAddr) {
2742  LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2743  return true;
2744  }
2745  pfrom->fSentAddr = true;
2746 
2747  pfrom->vAddrToSend.clear();
2748  std::vector<CAddress> vAddr = connman->GetAddresses();
2749  FastRandomContext insecure_rand;
2750  for (const CAddress &addr : vAddr)
2751  pfrom->PushAddress(addr, insecure_rand);
2752  return true;
2753  }
2754 
2755  if (strCommand == NetMsgType::MEMPOOL) {
2756  if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2757  {
2758  LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2759  pfrom->fDisconnect = true;
2760  return true;
2761  }
2762 
2763  if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
2764  {
2765  LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2766  pfrom->fDisconnect = true;
2767  return true;
2768  }
2769 
2770  LOCK(pfrom->cs_inventory);
2771  pfrom->fSendMempool = true;
2772  return true;
2773  }
2774 
2775  if (strCommand == NetMsgType::PING) {
2776  if (pfrom->nVersion > BIP0031_VERSION)
2777  {
2778  uint64_t nonce = 0;
2779  vRecv >> nonce;
2780  // Echo the message back with the nonce. This allows for two useful features:
2781  //
2782  // 1) A remote node can quickly check if the connection is operational
2783  // 2) Remote nodes can measure the latency of the network thread. If this node
2784  // is overloaded it won't respond to pings quickly and the remote node can
2785  // avoid sending us more work, like chain download requests.
2786  //
2787  // The nonce stops the remote getting confused between different pings: without
2788  // it, if the remote node sends a ping once per second and this node takes 5
2789  // seconds to respond to each, the 5th ping the remote sends would appear to
2790  // return very quickly.
2791  connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2792  }
2793  return true;
2794  }
2795 
2796  if (strCommand == NetMsgType::PONG) {
2797  int64_t pingUsecEnd = nTimeReceived;
2798  uint64_t nonce = 0;
2799  size_t nAvail = vRecv.in_avail();
2800  bool bPingFinished = false;
2801  std::string sProblem;
2802 
2803  if (nAvail >= sizeof(nonce)) {
2804  vRecv >> nonce;
2805 
2806  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2807  if (pfrom->nPingNonceSent != 0) {
2808  if (nonce == pfrom->nPingNonceSent) {
2809  // Matching pong received, this ping is no longer outstanding
2810  bPingFinished = true;
2811  int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2812  if (pingUsecTime > 0) {
2813  // Successful ping time measurement, replace previous
2814  pfrom->nPingUsecTime = pingUsecTime;
2815  pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2816  } else {
2817  // This should never happen
2818  sProblem = "Timing mishap";
2819  }
2820  } else {
2821  // Nonce mismatches are normal when pings are overlapping
2822  sProblem = "Nonce mismatch";
2823  if (nonce == 0) {
2824  // This is most likely a bug in another implementation somewhere; cancel this ping
2825  bPingFinished = true;
2826  sProblem = "Nonce zero";
2827  }
2828  }
2829  } else {
2830  sProblem = "Unsolicited pong without ping";
2831  }
2832  } else {
2833  // This is most likely a bug in another implementation somewhere; cancel this ping
2834  bPingFinished = true;
2835  sProblem = "Short payload";
2836  }
2837 
2838  if (!(sProblem.empty())) {
2839  LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2840  pfrom->GetId(),
2841  sProblem,
2842  pfrom->nPingNonceSent,
2843  nonce,
2844  nAvail);
2845  }
2846  if (bPingFinished) {
2847  pfrom->nPingNonceSent = 0;
2848  }
2849  return true;
2850  }
2851 
2852  if (strCommand == NetMsgType::FILTERLOAD) {
2854  vRecv >> filter;
2855 
2856  if (!filter.IsWithinSizeConstraints())
2857  {
2858  // There is no excuse for sending a too-large filter
2859  LOCK(cs_main);
2860  Misbehaving(pfrom->GetId(), 100);
2861  }
2862  else
2863  {
2864  LOCK(pfrom->cs_filter);
2865  pfrom->pfilter.reset(new CBloomFilter(filter));
2866  pfrom->pfilter->UpdateEmptyFull();
2867  pfrom->fRelayTxes = true;
2868  }
2869  return true;
2870  }
2871 
2872  if (strCommand == NetMsgType::FILTERADD) {
2873  std::vector<unsigned char> vData;
2874  vRecv >> vData;
2875 
2876  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2877  // and thus, the maximum size any matched object can have) in a filteradd message
2878  bool bad = false;
2879  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2880  bad = true;
2881  } else {
2882  LOCK(pfrom->cs_filter);
2883  if (pfrom->pfilter) {
2884  pfrom->pfilter->insert(vData);
2885  } else {
2886  bad = true;
2887  }
2888  }
2889  if (bad) {
2890  LOCK(cs_main);
2891  Misbehaving(pfrom->GetId(), 100);
2892  }
2893  return true;
2894  }
2895 
2896  if (strCommand == NetMsgType::FILTERCLEAR) {
2897  LOCK(pfrom->cs_filter);
2898  if (pfrom->GetLocalServices() & NODE_BLOOM) {
2899  pfrom->pfilter.reset(new CBloomFilter());
2900  }
2901  pfrom->fRelayTxes = true;
2902  return true;
2903  }
2904 
2905  if (strCommand == NetMsgType::FEEFILTER) {
2906  CAmount newFeeFilter = 0;
2907  vRecv >> newFeeFilter;
2908  if (MoneyRange(newFeeFilter)) {
2909  {
2910  LOCK(pfrom->cs_feeFilter);
2911  pfrom->minFeeFilter = newFeeFilter;
2912  }
2913  LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2914  }
2915  return true;
2916  }
2917 
2918  if (strCommand == NetMsgType::NOTFOUND) {
2919  // We do not care about the NOTFOUND message, but logging an Unknown Command
2920  // message would be undesirable as we transmit it ourselves.
2921  return true;
2922  }
2923 
2924  // Ignore unknown commands for extensibility
2925  LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2926  return true;
2927 }
2928 
2929 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman, bool enable_bip61) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
2930 {
2932  CNodeState &state = *State(pnode->GetId());
2933 
2934  if (enable_bip61) {
2935  for (const CBlockReject& reject : state.rejects) {
2936  connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, std::string(NetMsgType::BLOCK), reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2937  }
2938  }
2939  state.rejects.clear();
2940 
2941  if (state.fShouldBan) {
2942  state.fShouldBan = false;
2943  if (pnode->fWhitelisted)
2944  LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2945  else if (pnode->m_manual_connection)
2946  LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
2947  else {
2948  pnode->fDisconnect = true;
2949  if (pnode->addr.IsLocal())
2950  LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2951  else
2952  {
2953  connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2954  }
2955  }
2956  return true;
2957  }
2958  return false;
2959 }
2960 
2961 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2962 {
2963  const CChainParams& chainparams = Params();
2964  //
2965  // Message format
2966  // (4) message start
2967  // (12) command
2968  // (4) size
2969  // (4) checksum
2970  // (x) data
2971  //
2972  bool fMoreWork = false;
2973 
2974  if (!pfrom->vRecvGetData.empty())
2975  ProcessGetData(pfrom, chainparams, connman, interruptMsgProc);
2976 
2977  if (pfrom->fDisconnect)
2978  return false;
2979 
2980  // this maintains the order of responses
2981  if (!pfrom->vRecvGetData.empty()) return true;
2982 
2983  // Don't bother if send buffer is too full to respond anyway
2984  if (pfrom->fPauseSend)
2985  return false;
2986 
2987  std::list<CNetMessage> msgs;
2988  {
2989  LOCK(pfrom->cs_vProcessMsg);
2990  if (pfrom->vProcessMsg.empty())
2991  return false;
2992  // Just take one message
2993  msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2994  pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2996  fMoreWork = !pfrom->vProcessMsg.empty();
2997  }
2998  CNetMessage& msg(msgs.front());
2999 
3000  msg.SetVersion(pfrom->GetRecvVersion());
3001  // Scan for message start
3002  if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
3003  LogPrint(BCLog::NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
3004  pfrom->fDisconnect = true;
3005  return false;
3006  }
3007 
3008  // Read header
3009  CMessageHeader& hdr = msg.hdr;
3010  if (!hdr.IsValid(chainparams.MessageStart()))
3011  {
3012  LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
3013  return fMoreWork;
3014  }
3015  std::string strCommand = hdr.GetCommand();
3016 
3017  // Message size
3018  unsigned int nMessageSize = hdr.nMessageSize;
3019 
3020  // Checksum
3021  CDataStream& vRecv = msg.vRecv;
3022  const uint256& hash = msg.GetMessageHash();
3023  if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
3024  {
3025  LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
3026  SanitizeString(strCommand), nMessageSize,
3029  return fMoreWork;
3030  }
3031 
3032  // Process message
3033  bool fRet = false;
3034  try
3035  {
3036  fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc, m_enable_bip61);
3037  if (interruptMsgProc)
3038  return false;
3039  if (!pfrom->vRecvGetData.empty())
3040  fMoreWork = true;
3041  }
3042  catch (const std::ios_base::failure& e)
3043  {
3044  if (m_enable_bip61) {
3045  connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
3046  }
3047  if (strstr(e.what(), "end of data"))
3048  {
3049  // Allow exceptions from under-length message on vRecv
3050  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
3051  }
3052  else if (strstr(e.what(), "size too large"))
3053  {
3054  // Allow exceptions from over-long size
3055  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
3056  }
3057  else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
3058  {
3059  // Allow exceptions from non-canonical encoding
3060  LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
3061  }
3062  else
3063  {
3064  PrintExceptionContinue(&e, "ProcessMessages()");
3065  }
3066  }
3067  catch (const std::exception& e) {
3068  PrintExceptionContinue(&e, "ProcessMessages()");
3069  } catch (...) {
3070  PrintExceptionContinue(nullptr, "ProcessMessages()");
3071  }
3072 
3073  if (!fRet) {
3074  LogPrint(BCLog::NET, "%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
3075  }
3076 
3077  LOCK(cs_main);
3078  SendRejectsAndCheckIfBanned(pfrom, connman, m_enable_bip61);
3079 
3080  return fMoreWork;
3081 }
3082 
3083 void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
3084 {
3086 
3087  CNodeState &state = *State(pto->GetId());
3088  const CNetMsgMaker msgMaker(pto->GetSendVersion());
3089 
3090  if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
3091  // This is an outbound peer subject to disconnection if they don't
3092  // announce a block with as much work as the current tip within
3093  // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
3094  // their chain has more work than ours, we should sync to it,
3095  // unless it's invalid, in which case we should find that out and
3096  // disconnect from them elsewhere).
3097  if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
3098  if (state.m_chain_sync.m_timeout != 0) {
3099  state.m_chain_sync.m_timeout = 0;
3100  state.m_chain_sync.m_work_header = nullptr;
3101  state.m_chain_sync.m_sent_getheaders = false;
3102  }
3103  } else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
3104  // Our best block known by this peer is behind our tip, and we're either noticing
3105  // that for the first time, OR this peer was able to catch up to some earlier point
3106  // where we checked against our tip.
3107  // Either way, set a new timeout based on current tip.
3108  state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
3109  state.m_chain_sync.m_work_header = chainActive.Tip();
3110  state.m_chain_sync.m_sent_getheaders = false;
3111  } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
3112  // No evidence yet that our peer has synced to a chain with work equal to that
3113  // of our tip, when we first detected it was behind. Send a single getheaders
3114  // message to give the peer a chance to update us.
3115  if (state.m_chain_sync.m_sent_getheaders) {
3116  // They've run out of time to catch up!
3117  LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
3118  pto->fDisconnect = true;
3119  } else {
3120  assert(state.m_chain_sync.m_work_header);
3121  LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
3122  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
3123  state.m_chain_sync.m_sent_getheaders = true;
3124  constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
3125  // Bump the timeout to allow a response, which could clear the timeout
3126  // (if the response shows the peer has synced), reset the timeout (if
3127  // the peer syncs to the required work but not to our tip), or result
3128  // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3129  // has not sufficiently progressed)
3130  state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
3131  }
3132  }
3133  }
3134 }
3135 
3137 {
3138  // Check whether we have too many outbound peers
3139  int extra_peers = connman->GetExtraOutboundCount();
3140  if (extra_peers > 0) {
3141  // If we have more outbound peers than we target, disconnect one.
3142  // Pick the outbound peer that least recently announced
3143  // us a new block, with ties broken by choosing the more recent
3144  // connection (higher node id)
3145  NodeId worst_peer = -1;
3146  int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
3147 
3148  connman->ForEachNode([&](CNode* pnode) {
3150 
3151  // Ignore non-outbound peers, or nodes marked for disconnect already
3152  if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
3153  CNodeState *state = State(pnode->GetId());
3154  if (state == nullptr) return; // shouldn't be possible, but just in case
3155  // Don't evict our protected peers
3156  if (state->m_chain_sync.m_protect) return;
3157  if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
3158  worst_peer = pnode->GetId();
3159  oldest_block_announcement = state->m_last_block_announcement;
3160  }
3161  });
3162  if (worst_peer != -1) {
3163  bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
3165 
3166  // Only disconnect a peer that has been connected to us for
3167  // some reasonable fraction of our check-frequency, to give
3168  // it time for new information to have arrived.
3169  // Also don't disconnect any peer we're trying to download a
3170  // block from.
3171  CNodeState &state = *State(pnode->GetId());
3172  if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
3173  LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
3174  pnode->fDisconnect = true;
3175  return true;
3176  } else {
3177  LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
3178  return false;
3179  }
3180  });
3181  if (disconnected) {
3182  // If we disconnected an extra peer, that means we successfully
3183  // connected to at least one peer after the last time we
3184  // detected a stale tip. Don't try any more extra peers until
3185  // we next detect a stale tip, to limit the load we put on the
3186  // network from these extra connections.
3188  }
3189  }
3190  }
3191 }
3192 
3194 {
3195  LOCK(cs_main);
3196 
3197  if (connman == nullptr) return;
3198 
3199  int64_t time_in_seconds = GetTime();
3200 
3201  EvictExtraOutboundPeers(time_in_seconds);
3202 
3203  if (time_in_seconds > m_stale_tip_check_time) {
3204  // Check whether our tip is stale, and if so, allow using an extra
3205  // outbound peer
3206  if (!fImporting && !fReindex && connman->GetNetworkActive() && connman->GetUseAddrmanOutgoing() && TipMayBeStale(consensusParams)) {
3207  LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update);
3209  } else if (connman->GetTryNewOutboundPeer()) {
3211  }
3212  m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
3213  }
3214 }
3215 
3216 namespace {
3217 class CompareInvMempoolOrder
3218 {
3219  CTxMemPool *mp;
3220 public:
3221  explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
3222  {
3223  mp = _mempool;
3224  }
3225 
3226  bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
3227  {
3228  /* As std::make_heap produces a max-heap, we want the entries with the
3229  * fewest ancestors/highest fee to sort later. */
3230  return mp->CompareDepthAndScore(*b, *a);
3231  }
3232 };
3233 }
3234 
3236 {
3237  const Consensus::Params& consensusParams = Params().GetConsensus();
3238  {
3239  // Don't send anything until the version handshake is complete
3240  if (!pto->fSuccessfullyConnected || pto->fDisconnect)
3241  return true;
3242 
3243  // If we get here, the outgoing message serialization version is set and can't change.
3244  const CNetMsgMaker msgMaker(pto->GetSendVersion());
3245 
3246  //
3247  // Message: ping
3248  //
3249  bool pingSend = false;
3250  if (pto->fPingQueued) {
3251  // RPC ping request by user
3252  pingSend = true;
3253  }
3254  if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
3255  // Ping automatically sent as a latency probe & keepalive.
3256  pingSend = true;
3257  }
3258  if (pingSend) {
3259  uint64_t nonce = 0;
3260  while (nonce == 0) {
3261  GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
3262  }
3263  pto->fPingQueued = false;
3264  pto->nPingUsecStart = GetTimeMicros();
3265  if (pto->nVersion > BIP0031_VERSION) {
3266  pto->nPingNonceSent = nonce;
3267  connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
3268  } else {
3269  // Peer is too old to support ping command with nonce, pong will never arrive.
3270  pto->nPingNonceSent = 0;
3271  connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
3272  }
3273  }
3274 
3275  TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3276  if (!lockMain)
3277  return true;
3278 
3279  if (SendRejectsAndCheckIfBanned(pto, connman, m_enable_bip61))
3280  return true;
3281  CNodeState &state = *State(pto->GetId());
3282 
3283  // Address refresh broadcast
3284  int64_t nNow = GetTimeMicros();
3285  if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3286  AdvertiseLocal(pto);
3287  pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
3288  }
3289 
3290  //
3291  // Message: addr
3292  //
3293  if (pto->nNextAddrSend < nNow) {
3294  pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
3295  std::vector<CAddress> vAddr;
3296  vAddr.reserve(pto->vAddrToSend.size());
3297  for (const CAddress& addr : pto->vAddrToSend)
3298  {
3299  if (!pto->addrKnown.contains(addr.GetKey()))
3300  {
3301  pto->addrKnown.insert(addr.GetKey());
3302  vAddr.push_back(addr);
3303  // receiver rejects addr messages larger than 1000
3304  if (vAddr.size() >= 1000)
3305  {
3306  connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3307  vAddr.clear();
3308  }
3309  }
3310  }
3311  pto->vAddrToSend.clear();
3312  if (!vAddr.empty())
3313  connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3314  // we only send the big addr message once
3315  if (pto->vAddrToSend.capacity() > 40)
3316  pto->vAddrToSend.shrink_to_fit();
3317  }
3318 
3319  // Start block sync
3320  if (pindexBestHeader == nullptr)
3322  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.
3323  if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
3324  // Only actively request headers from a single peer, unless we're close to today.
3325  if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3326  state.fSyncStarted = true;
3327  state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
3328  nSyncStarted++;
3329  const CBlockIndex *pindexStart = pindexBestHeader;
3330  /* If possible, start at the block preceding the currently
3331  best known header. This ensures that we always get a
3332  non-empty list of headers back as long as the peer
3333  is up-to-date. With a non-empty response, we can initialise
3334  the peer's known best block. This wouldn't be possible
3335  if we requested starting at pindexBestHeader and
3336  got back an empty response. */
3337  if (pindexStart->pprev)
3338  pindexStart = pindexStart->pprev;
3339  LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
3340  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
3341  }
3342  }
3343 
3344  // Resend wallet transactions that haven't gotten in a block yet
3345  // Except during reindex, importing and IBD, when old wallet
3346  // transactions become unconfirmed and spams other nodes.
3348  {
3349  GetMainSignals().Broadcast(nTimeBestReceived, connman);
3350  }
3351 
3352  //
3353  // Try sending block announcements via headers
3354  //
3355  {
3356  // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3357  // list of block hashes we're relaying, and our peer wants
3358  // headers announcements, then find the first header
3359  // not yet known to our peer but would connect, and send.
3360  // If no header would connect, or if we have too many
3361  // blocks, or if the peer doesn't want headers, just
3362  // add all to the inv queue.
3363  LOCK(pto->cs_inventory);
3364  std::vector<CBlock> vHeaders;
3365  bool fRevertToInv = ((!state.fPreferHeaders &&
3366  (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
3367  pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
3368  const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
3369  ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
3370 
3371  if (!fRevertToInv) {
3372  bool fFoundStartingHeader = false;
3373  // Try to find first header that our peer doesn't have, and
3374  // then send all headers past that one. If we come across any
3375  // headers that aren't on chainActive, give up.
3376  for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3377  const CBlockIndex* pindex = LookupBlockIndex(hash);
3378  assert(pindex);
3379  if (chainActive[pindex->nHeight] != pindex) {
3380  // Bail out if we reorged away from this block
3381  fRevertToInv = true;
3382  break;
3383  }
3384  if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
3385  // This means that the list of blocks to announce don't
3386  // connect to each other.
3387  // This shouldn't really be possible to hit during
3388  // regular operation (because reorgs should take us to
3389  // a chain that has some block not on the prior chain,
3390  // which should be caught by the prior check), but one
3391  // way this could happen is by using invalidateblock /
3392  // reconsiderblock repeatedly on the tip, causing it to
3393  // be added multiple times to vBlockHashesToAnnounce.
3394  // Robustly deal with this rare situation by reverting
3395  // to an inv.
3396  fRevertToInv = true;
3397  break;
3398  }
3399  pBestIndex = pindex;
3400  if (fFoundStartingHeader) {
3401  // add this to the headers message
3402  vHeaders.push_back(pindex->GetBlockHeader());
3403  } else if (PeerHasHeader(&state, pindex)) {
3404  continue; // keep looking for the first new block
3405  } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
3406  // Peer doesn't have this header but they do have the prior one.
3407  // Start sending headers.
3408  fFoundStartingHeader = true;
3409  vHeaders.push_back(pindex->GetBlockHeader());
3410  } else {
3411  // Peer doesn't have this header or the prior one -- nothing will
3412  // connect, so bail out.
3413  fRevertToInv = true;
3414  break;
3415  }
3416  }
3417  }
3418  if (!fRevertToInv && !vHeaders.empty()) {
3419  if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
3420  // We only send up to 1 block as header-and-ids, as otherwise
3421  // probably means we're doing an initial-ish-sync or they're slow
3422  LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
3423  vHeaders.front().GetHash().ToString(), pto->GetId());
3424 
3425  int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
3426 
3427  bool fGotBlockFromCache = false;
3428  {
3429  LOCK(cs_most_recent_block);
3430  if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
3431  if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
3432  connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
3433  else {
3434  CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
3435  connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3436  }
3437  fGotBlockFromCache = true;
3438  }
3439  }
3440  if (!fGotBlockFromCache) {
3441  CBlock block;
3442  bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3443  assert(ret);
3444  CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3445  connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3446  }
3447  state.pindexBestHeaderSent = pBestIndex;
3448  } else if (state.fPreferHeaders) {
3449  if (vHeaders.size() > 1) {
3450  LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3451  vHeaders.size(),
3452  vHeaders.front().GetHash().ToString(),
3453  vHeaders.back().GetHash().ToString(), pto->GetId());
3454  } else {
3455  LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3456  vHeaders.front().GetHash().ToString(), pto->GetId());
3457  }
3458  connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3459  state.pindexBestHeaderSent = pBestIndex;
3460  } else
3461  fRevertToInv = true;
3462  }
3463  if (fRevertToInv) {
3464  // If falling back to using an inv, just try to inv the tip.
3465  // The last entry in vBlockHashesToAnnounce was our tip at some point
3466  // in the past.
3467  if (!pto->vBlockHashesToAnnounce.empty()) {
3468  const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3469  const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce);
3470  assert(pindex);
3471 
3472  // Warn if we're announcing a block that is not on the main chain.
3473  // This should be very rare and could be optimized out.
3474  // Just log for now.
3475  if (chainActive[pindex->nHeight] != pindex) {
3476  LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3477  hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3478  }
3479 
3480  // If the peer's chain has this block, don't inv it back.
3481  if (!PeerHasHeader(&state, pindex)) {
3482  pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3483  LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3484  pto->GetId(), hashToAnnounce.ToString());
3485  }
3486  }
3487  }
3488  pto->vBlockHashesToAnnounce.clear();
3489  }
3490 
3491  //
3492  // Message: inventory
3493  //
3494  std::vector<CInv> vInv;
3495  {
3496  LOCK(pto->cs_inventory);
3497  vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3498 
3499  // Add blocks
3500  for (const uint256& hash : pto->vInventoryBlockToSend) {
3501  vInv.push_back(CInv(MSG_BLOCK, hash));
3502  if (vInv.size() == MAX_INV_SZ) {
3503  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3504  vInv.clear();
3505  }
3506  }
3507  pto->vInventoryBlockToSend.clear();
3508 
3509  // Check whether periodic sends should happen
3510  bool fSendTrickle = pto->fWhitelisted;
3511  if (pto->nNextInvSend < nNow) {
3512  fSendTrickle = true;
3513  if (pto->fInbound) {
3514  pto->nNextInvSend = connman->PoissonNextSendInbound(nNow, INVENTORY_BROADCAST_INTERVAL);
3515  } else {
3516  // Use half the delay for outbound peers, as there is less privacy concern for them.
3517  pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> 1);
3518  }
3519  }
3520 
3521  // Time to send but the peer has requested we not relay transactions.
3522  if (fSendTrickle) {
3523  LOCK(pto->cs_filter);
3524  if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3525  }
3526 
3527  // Respond to BIP35 mempool requests
3528  if (fSendTrickle && pto->fSendMempool) {
3529  auto vtxinfo = mempool.infoAll();
3530  pto->fSendMempool = false;
3531  CAmount filterrate = 0;
3532  {
3533  LOCK(pto->cs_feeFilter);
3534  filterrate = pto->minFeeFilter;
3535  }
3536 
3537  LOCK(pto->cs_filter);
3538 
3539  for (const auto& txinfo : vtxinfo) {
3540  const uint256& hash = txinfo.tx->GetHash();
3541  CInv inv(MSG_TX, hash);
3542  pto->setInventoryTxToSend.erase(hash);
3543  if (filterrate) {
3544  if (txinfo.feeRate.GetFeePerK() < filterrate)
3545  continue;
3546  }
3547  if (pto->pfilter) {
3548  if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3549  }
3550  pto->filterInventoryKnown.insert(hash);
3551  vInv.push_back(inv);
3552  if (vInv.size() == MAX_INV_SZ) {
3553  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3554  vInv.clear();
3555  }
3556  }
3557  pto->timeLastMempoolReq = GetTime();
3558  }
3559 
3560  // Determine transactions to relay
3561  if (fSendTrickle) {
3562  // Produce a vector with all candidates for sending
3563  std::vector<std::set<uint256>::iterator> vInvTx;
3564  vInvTx.reserve(pto->setInventoryTxToSend.size());
3565  for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3566  vInvTx.push_back(it);
3567  }
3568  CAmount filterrate = 0;
3569  {
3570  LOCK(pto->cs_feeFilter);
3571  filterrate = pto->minFeeFilter;
3572  }
3573  // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3574  // A heap is used so that not all items need sorting if only a few are being sent.
3575  CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3576  std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3577  // No reason to drain out at many times the network's capacity,
3578  // especially since we have many peers and some will draw much shorter delays.
3579  unsigned int nRelayedTransactions = 0;
3580  LOCK(pto->cs_filter);
3581  while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3582  // Fetch the top element from the heap
3583  std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3584  std::set<uint256>::iterator it = vInvTx.back();
3585  vInvTx.pop_back();
3586  uint256 hash = *it;
3587  // Remove it from the to-be-sent set
3588  pto->setInventoryTxToSend.erase(it);
3589  // Check if not in the filter already
3590  if (pto->filterInventoryKnown.contains(hash)) {
3591  continue;
3592  }
3593  // Not in the mempool anymore? don't bother sending it.
3594  auto txinfo = mempool.info(hash);
3595  if (!txinfo.tx) {
3596  continue;
3597  }
3598  if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3599  continue;
3600  }
3601  if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3602  // Send
3603  vInv.push_back(CInv(MSG_TX, hash));
3604  nRelayedTransactions++;
3605  {
3606  // Expire old relay messages
3607  while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3608  {
3609  mapRelay.erase(vRelayExpiration.front().second);
3610  vRelayExpiration.pop_front();
3611  }
3612 
3613  auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3614  if (ret.second) {
3615  vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3616  }
3617  }
3618  if (vInv.size() == MAX_INV_SZ) {
3619  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3620  vInv.clear();
3621  }
3622  pto->filterInventoryKnown.insert(hash);
3623  }
3624  }
3625  }
3626  if (!vInv.empty())
3627  connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3628 
3629  // Detect whether we're stalling
3630  nNow = GetTimeMicros();
3631  if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3632  // Stalling only triggers when the block download window cannot move. During normal steady state,
3633  // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3634  // should only happen during initial block download.
3635  LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3636  pto->fDisconnect = true;
3637  return true;
3638  }
3639  // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3640  // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3641  // We compensate for other peers to prevent killing off peers due to our own downstream link
3642  // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3643  // to unreasonably increase our timeout.
3644  if (state.vBlocksInFlight.size() > 0) {
3645  QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3646  int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3647  if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3648  LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3649  pto->fDisconnect = true;
3650  return true;
3651  }
3652  }
3653  // Check for headers sync timeouts
3654  if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3655  // Detect whether this is a stalling initial-headers-sync peer
3656  if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3657  if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3658  // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3659  // and we have others we could be using instead.
3660  // Note: If all our peers are inbound, then we won't
3661  // disconnect our sync peer for stalling; we have bigger
3662  // problems if we can't get any outbound peers.
3663  if (!pto->fWhitelisted) {
3664  LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3665  pto->fDisconnect = true;
3666  return true;
3667  } else {
3668  LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3669  // Reset the headers sync state so that we have a
3670  // chance to try downloading from a different peer.
3671  // Note: this will also result in at least one more
3672  // getheaders message to be sent to
3673  // this peer (eventually).
3674  state.fSyncStarted = false;
3675  nSyncStarted--;
3676  state.nHeadersSyncTimeout = 0;
3677  }
3678  }
3679  } else {
3680  // After we've caught up once, reset the timeout so we can't trigger
3681  // disconnect later.
3682  state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3683  }
3684  }
3685 
3686  // Check that outbound peers have reasonable chains
3687  // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3688  ConsiderEviction(pto, GetTime());
3689 
3690  //
3691  // Message: getdata (blocks)
3692  //
3693  std::vector<CInv> vGetData;
3694  if (!pto->fClient && ((fFetch && !pto->m_limited_node) || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3695  std::vector<const CBlockIndex*> vToDownload;
3696  NodeId staller = -1;
3697  FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3698  for (const CBlockIndex *pindex : vToDownload) {
3699  uint32_t nFetchFlags = GetFetchFlags(pto);
3700  vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3701  MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3702  LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3703  pindex->nHeight, pto->GetId());
3704  }
3705  if (state.nBlocksInFlight == 0 && staller != -1) {
3706  if (State(staller)->nStallingSince == 0) {
3707  State(staller)->nStallingSince = nNow;
3708  LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3709  }
3710  }
3711  }
3712 
3713  //
3714  // Message: getdata (non-blocks)
3715  //
3716  while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3717  {
3718  const CInv& inv = (*pto->mapAskFor.begin()).second;
3719  if (!AlreadyHave(inv))
3720  {
3721  LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3722  vGetData.push_back(inv);
3723  if (vGetData.size() >= 1000)
3724  {
3725  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3726  vGetData.clear();
3727  }
3728  } else {
3729  //If we're not going to ask, don't expect a response.
3730  pto->setAskFor.erase(inv.hash);
3731  }
3732  pto->mapAskFor.erase(pto->mapAskFor.begin());
3733  }
3734  if (!vGetData.empty())
3735  connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3736 
3737  //
3738  // Message: feefilter
3739  //
3740  // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3741  if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3742  !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3743  CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3744  int64_t timeNow = GetTimeMicros();
3745  if (timeNow > pto->nextSendTimeFeeFilter) {
3746  static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3747  static FeeFilterRounder filterRounder(default_feerate);
3748  CAmount filterToSend = filterRounder.round(currentFilter);
3749  // We always have a fee filter of at least minRelayTxFee
3750  filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3751  if (filterToSend != pto->lastSentFeeFilter) {
3752  connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3753  pto->lastSentFeeFilter = filterToSend;
3754  }
3755  pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3756  }
3757  // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3758  // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3759  else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3760  (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3761  pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3762  }
3763  }
3764  }
3765  return true;
3766 }
3767 
3769 {
3770 public:
3773  // orphan transactions
3774  mapOrphanTransactions.clear();
3775  mapOrphanTransactionsByPrev.clear();
3776  }
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:195
enum ReadStatus_t ReadStatus
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected...
Definition: protocol.cpp:31
CTxMemPool mempool
void Misbehaving(NodeId nodeid, int howmuch, const std::string &message="") EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Increase a node&#39;s misbehavior score.
std::atomic< uint64_t > nPingNonceSent
Definition: net.h:734
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:502
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:34
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:23
std::atomic_bool fPauseSend
Definition: net.h:688
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:60
int64_t nextSendTimeFeeFilter
Definition: net.h:747
int GetSendVersion() const
Definition: net.cpp:810
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:43
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:228
uint256 GetRandHash()
Definition: random.cpp:374
ReadStatus FillBlock(CBlock &block, const std::vector< CTransactionRef > &vtx_missing)
ServiceFlags
nServices flags
Definition: protocol.h:247
bool IsLocal() const
Definition: netaddress.cpp:174
CCriticalSection cs_filter
Definition: net.h:682
void SetNull()
Definition: uint256.h:40
int64_t GetBlockTime() const
Definition: chain.h:297
CConnman *const connman
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:128
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:784
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: hash.cpp:102
int GetRandInt(int nMax)
Definition: random.cpp:369
#define TRY_LOCK(cs, name)
Definition: sync.h:185
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
size_t GetAddressCount() const
Definition: net.cpp:2501
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:23
void WakeMessageHandler()
Definition: net.cpp:1477
void SetServices(const CService &addr, ServiceFlags nServices)
Definition: net.cpp:2506
std::string ToString() const
Definition: protocol.cpp:193
std::list< CNetMessage > vProcessMsg
Definition: net.h:642
Definition: block.h:74
Defined in BIP144.
Definition: protocol.h:380
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:278
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:29
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
Overridden from CValidationInterface.
int64_t nTimeExpire
Defined in BIP152.
Definition: protocol.h:378
std::vector< uint16_t > indexes
int GetRecvVersion() const
Definition: net.h:795
#define strprintf
Definition: tinyformat.h:1066
void CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
Evict extra outbound peers.
bool SendMessages(CNode *pto) override EXCLUSIVE_LOCKS_REQUIRED(pto -> cs_sendProcessing)
Send queued protocol messages to be sent to a give node.
void insert(const std::vector< unsigned char > &vKey)
Definition: bloom.cpp:245
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:911
CCriticalSection g_cs_orphans
reverse_range< T > reverse_iterate(T &x)
inv message data
Definition: protocol.h:385
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:40
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:155
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
PeerLogicValidation(CConnman *connman, CScheduler &scheduler, bool enable_bip61)
TxMempoolInfo info(const uint256 &hash) const
Definition: txmempool.cpp:807
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:134
std::vector< uint256 > vInventoryBlockToSend
Definition: net.h:714
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
CBlockHeader GetBlockHeader() const
Definition: chain.h:279
void AskFor(const CInv &inv)
Definition: net.cpp:2800
int Height() const
Return the maximal height in the chain.
Definition: chain.h:476
bool IsValid() const
Definition: validation.h:65
Defined in BIP144.
Definition: protocol.h:379
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:44
bool fSendMempool
Definition: net.h:723
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CCriticalSection cs_SubVer
Definition: net.h:665
bool GetTryNewOutboundPeer()
Definition: net.cpp:1728
CTransactionRef tx
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:141
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
Definition: net.cpp:2839
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:239
std::unique_ptr< CBloomFilter > pfilter
Definition: net.h:683
void SetVersion(int nVersionIn)
Definition: net.h:614
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:141
const bool m_enable_bip61
Enable BIP61 (sending reject messages)
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
Definition: bloom.h:115
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: util.cpp:698
std::atomic< int64_t > nPingUsecStart
Definition: net.h:736
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
Definition: net.cpp:153
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:126
CCriticalSection cs_feeFilter
Definition: net.h:745
int64_t GetTimeMicros()
Definition: utiltime.cpp:48
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
bool IsNull() const
Definition: block.h:151
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:221
bool empty() const
Definition: streams.h:313
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:542
void SetTryNewOutboundPeer(bool flag)
Definition: net.cpp:1733
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:364
uint32_t nMessageSize
Definition: protocol.h:59
CCriticalSection cs_inventory
Definition: net.h:715
void Broadcast(int64_t nBestBlockTime, CConnman *connman)
uint64_t GetLocalNonce() const
Definition: net.h:775
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:268
std::set< uint256 > setInventoryTxToSend
Definition: net.h:710
std::vector< CAddress > vAddrToSend
Definition: net.h:699
std::atomic< int > nStartingHeight
Definition: net.h:696
std::string cleanSubVer
Definition: net.h:664
class CNetProcessingCleanup instance_of_cnetprocessingcleanup
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
Definition: net.h:824
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
constexpr Span< A > MakeSpan(A(&a)[N])
Create a span to a container exposing data() and size().
Definition: span.h:55
std::string GetCommand() const
Definition: protocol.cpp:96
void SetRecvVersion(int nVersionIn)
Definition: net.h:791
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:32
unsigned char * begin()
Definition: uint256.h:56
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:402
std::atomic< int64_t > timeLastMempoolReq
Definition: net.h:726
CAmount minFeeFilter
Definition: net.h:744
bool IsValid(const MessageStartChars &messageStart) const
Definition: protocol.cpp:101
bool IsNull() const
Definition: uint256.h:32
bool ProcessMessages(CNode *pfrom, std::atomic< bool > &interrupt) override
Process protocol messages received from a given node.
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:27
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:204
void PushInventory(const CInv &inv)
Definition: net.h:847
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
std::atomic< ServiceFlags > nServices
Definition: net.h:631
const std::vector< CTxIn > vin
Definition: transaction.h:281
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
Definition: net.cpp:675
int64_t nNextLocalAddrSend
Definition: net.h:704
std::deque< CInv > vRecvGetData
Definition: net.h:647
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:21
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:986
bool AddOrphanTx(const CTransactionRef &tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
Definition: net.cpp:2876
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex, CBlockHeader *first_invalid)
Process incoming block headers.
bool contains(const std::vector< unsigned char > &vKey) const
Definition: bloom.cpp:282
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:606
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:298
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
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.h:332
#define AssertLockHeld(cs)
Definition: sync.h:70
bool fSentAddr
Definition: net.h:680
std::atomic< int64_t > nPingUsecTime
Definition: net.h:738
std::atomic< int64_t > nMinPingUsecTime
Definition: net.h:740
int GetMyStartingHeight() const
Definition: net.h:779
#define LOCK2(cs1, cs2)
Definition: sync.h:182
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
Definition: net.cpp:539
isminefilter filter
Definition: rpcwallet.cpp:1011
ServiceFlags GetLocalServices() const
Definition: net.h:871
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:145
bool fClient
Definition: net.h:670
bool fRelayTxes
Definition: net.cpp:85
std::string strSubVer
Definition: net.h:664
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:133
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:25
if(!params[0].isNull()) nMinDepth
void ConsiderEviction(CNode *pto, int64_t time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Consider evicting an outbound peer based on the amount of time they&#39;ve been behind our tip...
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
CCriticalSection cs_main
Definition: validation.cpp:216
size_type size() const
Definition: streams.h:312
size_t nProcessQueueSize
Definition: net.h:643
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:32
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:148
unsigned long size()
Definition: txmempool.h:638
bool IsInvalid() const
Definition: validation.h:68
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:241
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:220
bool exists(const uint256 &hash) const
Definition: txmempool.h:650
bool fOneShot
Definition: net.h:668
An input of a transaction.
Definition: transaction.h:61
#define LOCK(cs)
Definition: sync.h:181
const char * name
Definition: rest.cpp:37
const uint256 & GetHash() const
Definition: transaction.h:316
bool IsPeerAddrLocalGood(CNode *pnode)
Definition: net.cpp:174
int type
Definition: protocol.h:407
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:463
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:142
Fast randomness source.
Definition: random.h:45
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
Definition: net.cpp:2889
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached
Definition: net.cpp:2664
int64_t nPowTargetSpacing
Definition: params.h:60
std::vector< CAddress > GetAddresses()
Definition: net.cpp:2521
CRollingBloomFilter filterInventoryKnown
Definition: net.h:707
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:468
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:38
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:30
NodeId fromPeer
std::string GetRejectReason() const
Definition: validation.h:88
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
Definition: net.h:208
bool IsProxy(const CNetAddr &addr)
Definition: netbase.cpp:581
bool m_manual_connection
Definition: net.h:669
const std::vector< CTxOut > vout
Definition: transaction.h:282
A CService with information about it as peer.
Definition: protocol.h:328
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::map< uint256, COrphanTx > mapOrphanTransactions GUARDED_BY(g_cs_orphans)
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:550
uint256 hash
Definition: protocol.h:408
CMainSignals & GetMainSignals()
std::vector< uint256 > vBlockHashesToAnnounce
Definition: net.h:721
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:20
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:61
int64_t NodeId
Definition: net.h:88
Definition: net.h:115
void AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
Definition: net.cpp:2516
bool GetNetworkActive() const
Definition: net.h:177
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter...
Definition: protocol.cpp:36
bool fGetAddr
Definition: net.h:701
std::atomic_bool fImporting
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:34
std::string ToString() const
Definition: uint256.cpp:62
std::vector< uint256 > vHave
Definition: block.h:130
NodeId GetId() const
Definition: net.h:771
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:33
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Definition: net.cpp:2905
Parameters that influence chain consensus.
Definition: params.h:40
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:28
std::atomic_bool fDisconnect
Definition: net.h:674
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:89
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.cpp:39
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:986
void ForEachNode(Callable &&func)
Definition: net.h:188
bool IsRoutable() const
Definition: netaddress.cpp:227
uint64_t GetHash() const
Definition: netaddress.cpp:385
CRollingBloomFilter addrKnown
Definition: net.h:700
unsigned int GetReceiveFloodSize() const
Definition: net.cpp:2720
const char * REJECT
The reject message informs the receiving node that one of its previous messages has been rejected...
Definition: protocol.cpp:37
bool CheckIncomingNonce(uint64_t nonce)
Definition: net.cpp:346
void EvictExtraOutboundPeers(int64_t time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If we have extra outbound peers, try to disconnect the one with the oldest block announcement.
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:31
const CAddress addr
Definition: net.h:656
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:24
const int64_t nTimeConnected
Definition: net.h:653
int64_t m_stale_tip_check_time
Next time to check for stale tip.
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindexConnected, const std::vector< CTransactionRef > &vtxConflicted) override
Overridden from CValidationInterface.
std::atomic_bool fReindex
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:19
uint256 GetHash() const
Definition: block.cpp:13
Capture information about block/transaction validation.
Definition: validation.h:26
std::atomic< bool > fPingQueued
Definition: net.h:742
256-bit opaque blob.
Definition: uint256.h:122
void AddInventoryKnown(const CInv &inv)
Definition: net.h:839
unsigned int nTime
Definition: protocol.h:360
bool HasWitness() const
Definition: transaction.h:348
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:288
ArgsManager gArgs
Definition: util.cpp:88
ServiceFlags nServices
Definition: protocol.h:357
void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &pblock) override
Overridden from CValidationInterface.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
std::vector< CTransactionRef > vtx
Definition: block.h:78
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:453
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids"...
Definition: protocol.cpp:41
bool fFeeler
Definition: net.h:667
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:441
std::atomic< int64_t > nLastTXTime
Definition: net.h:730
const bool fInbound
Definition: net.h:672
bool CompareDepthAndScore(const uint256 &hasha, const uint256 &hashb)
Definition: txmempool.cpp:722
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:18
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Public only for unit testing and relay testing (not relayed).
Definition: merkleblock.h:146
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
uint256 hashContinue
Definition: net.h:695
void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
bool fWhitelisted
Definition: net.h:666
bool IsTxAvailable(size_t index) const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:278
bool fLogIPs
Definition: logging.cpp:26
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:132
CCriticalSection cs_vProcessMsg
Definition: net.h:641
void SetSendVersion(int nVersionIn)
Definition: net.cpp:796
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
void BlockChecked(const CBlock &block, const CValidationState &state) override
Overridden from CValidationInterface.
void SetBestHeight(int height)
Definition: net.cpp:2710
#define LIMITED_STRING(obj, n)
Definition: serialize.h:413
void EraseOrphansFor(NodeId peer)
CAmount lastSentFeeFilter
Definition: net.h:746
std::atomic< int64_t > nTimeOffset
Definition: net.h:654
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
Definition: net.cpp:2900
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:22
bool fListen
Definition: net.cpp:84
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::atomic_bool fSuccessfullyConnected
Definition: net.h:673
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:23
SipHash-2-4.
Definition: hash.h:247
#define AssertLockNotHeld(cs)
Definition: sync.h:71
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:275
std::atomic< int > nVersion
Definition: net.h:659
bool fRelayTxes
Definition: net.h:679
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
unsigned int GetRejectCode() const
Definition: validation.h:87
ReadStatus InitData(const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector< std::pair< uint256, CTransactionRef >> &extra_txn)
void FinalizeNode(NodeId nodeid, bool &fUpdateConnectionTime) override
Handle removal of a peer by updating various state and removing it from mapNodeState.
static constexpr size_t HEADER_SIZE
Definition: protocol.h:37
bool m_limited_node
Definition: net.h:671
std::string ToString() const
Definition: netaddress.cpp:574
bool CorruptionPossible() const
Definition: validation.h:81
int GetExtraOutboundCount()
Definition: net.cpp:1745
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:26
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:264
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &message_start)
void MarkAddressGood(const CAddress &addr)
Definition: net.cpp:2511
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
Information about a peer.
Definition: net.h:626
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
std::vector< int > vHeightInFlight
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CAmount round(CAmount currentMinFee)
Quantize a minimum fee for privacy purpose before broadcast.
Definition: fees.cpp:1006
int64_t nNextInvSend
Definition: net.h:718
full block available in blk*.dat
Definition: chain.h:154
std::string GetAddrName() const
Definition: net.cpp:658
void AddTimeData(const CNetAddr &ip, int64_t nOffsetSample)
Definition: timedata.cpp:47
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
int64_t nNextAddrSend
Definition: net.h:703
void AddAddressKnown(const CAddress &_addr)
Definition: net.h:819
void InitializeNode(CNode *pnode) override
Initialize a peer by adding it to mapNodeState and pushing a message requesting its version...
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
COutPoint prevout
Definition: transaction.h:64
std::atomic_bool fPauseRecv
Definition: net.h:687
limitedmap< uint256, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
std::atomic< int64_t > nLastBlockTime
Definition: net.h:729
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:717
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
void AdvertiseLocal(CNode *pnode)
Definition: net.cpp:182
bool GetUseAddrmanOutgoing() const
Definition: net.h:178
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
int in_avail() const
Definition: streams.h:410
Defined in BIP37.
Definition: protocol.h:377
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:35
std::string itostr(int n)
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:136
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
std::set< uint256 > setAskFor
Definition: net.h:716
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:42
std::vector< unsigned char > ParseHex(const char *psz)
Message header.
Definition: protocol.h:28
uint256 hash
Definition: transaction.h:21
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.h:431