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