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