Merge #10522: [wallet] Remove unused variables
[bitcoinplatinum.git] / src / net_processing.cpp
blob4ca02c281d6dd20c192657cac618d9c40f4fe4c2
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.
6 #include "net_processing.h"
8 #include "addrman.h"
9 #include "arith_uint256.h"
10 #include "blockencodings.h"
11 #include "chainparams.h"
12 #include "consensus/validation.h"
13 #include "hash.h"
14 #include "init.h"
15 #include "validation.h"
16 #include "merkleblock.h"
17 #include "net.h"
18 #include "netmessagemaker.h"
19 #include "netbase.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "random.h"
25 #include "tinyformat.h"
26 #include "txmempool.h"
27 #include "ui_interface.h"
28 #include "util.h"
29 #include "utilmoneystr.h"
30 #include "utilstrencodings.h"
31 #include "validationinterface.h"
33 #include <boost/thread.hpp>
35 #if defined(NDEBUG)
36 # error "Bitcoin cannot be compiled without assertions."
37 #endif
39 std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
41 struct IteratorComparator
43 template<typename I>
44 bool operator()(const I& a, const I& b)
46 return &(*a) < &(*b);
50 struct COrphanTx {
51 // When modifying, adapt the copy of this definition in tests/DoS_tests.
52 CTransactionRef tx;
53 NodeId fromPeer;
54 int64_t nTimeExpire;
56 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
57 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
58 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
60 static size_t vExtraTxnForCompactIt = 0;
61 static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
63 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
65 // Internal stuff
66 namespace {
67 /** Number of nodes with fSyncStarted. */
68 int nSyncStarted = 0;
70 /**
71 * Sources of received blocks, saved to be able to send them reject
72 * messages or ban them when processing happens afterwards. Protected by
73 * cs_main.
74 * Set mapBlockSource[hash].second to false if the node should not be
75 * punished if the block is invalid.
77 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
79 /**
80 * Filter for transactions that were recently rejected by
81 * AcceptToMemoryPool. These are not rerequested until the chain tip
82 * changes, at which point the entire filter is reset. Protected by
83 * cs_main.
85 * Without this filter we'd be re-requesting txs from each of our peers,
86 * increasing bandwidth consumption considerably. For instance, with 100
87 * peers, half of which relay a tx we don't accept, that might be a 50x
88 * bandwidth increase. A flooding attacker attempting to roll-over the
89 * filter using minimum-sized, 60byte, transactions might manage to send
90 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
91 * two minute window to send invs to us.
93 * Decreasing the false positive rate is fairly cheap, so we pick one in a
94 * million to make it highly unlikely for users to have issues with this
95 * filter.
97 * Memory used: 1.3 MB
99 std::unique_ptr<CRollingBloomFilter> recentRejects;
100 uint256 hashRecentRejectsChainTip;
102 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
103 struct QueuedBlock {
104 uint256 hash;
105 const CBlockIndex* pindex; //!< Optional.
106 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
107 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
109 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
111 /** Stack of nodes which we have set to announce using compact blocks */
112 std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
114 /** Number of preferable block download peers. */
115 int nPreferredDownload = 0;
117 /** Number of peers from which we're downloading blocks. */
118 int nPeersWithValidatedDownloads = 0;
120 /** Relay map, protected by cs_main. */
121 typedef std::map<uint256, CTransactionRef> MapRelay;
122 MapRelay mapRelay;
123 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
124 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
125 } // anon namespace
127 //////////////////////////////////////////////////////////////////////////////
129 // Registration of network node signals.
132 namespace {
134 struct CBlockReject {
135 unsigned char chRejectCode;
136 std::string strRejectReason;
137 uint256 hashBlock;
141 * Maintain validation-specific state about nodes, protected by cs_main, instead
142 * by CNode's own locks. This simplifies asynchronous operation, where
143 * processing of incoming data is done after the ProcessMessage call returns,
144 * and we're no longer holding the node's locks.
146 struct CNodeState {
147 //! The peer's address
148 const CService address;
149 //! Whether we have a fully established connection.
150 bool fCurrentlyConnected;
151 //! Accumulated misbehaviour score for this peer.
152 int nMisbehavior;
153 //! Whether this peer should be disconnected and banned (unless whitelisted).
154 bool fShouldBan;
155 //! String name of this peer (debugging/logging purposes).
156 const std::string name;
157 //! List of asynchronously-determined block rejections to notify this peer about.
158 std::vector<CBlockReject> rejects;
159 //! The best known block we know this peer has announced.
160 const CBlockIndex *pindexBestKnownBlock;
161 //! The hash of the last unknown block this peer has announced.
162 uint256 hashLastUnknownBlock;
163 //! The last full block we both have.
164 const CBlockIndex *pindexLastCommonBlock;
165 //! The best header we have sent our peer.
166 const CBlockIndex *pindexBestHeaderSent;
167 //! Length of current-streak of unconnecting headers announcements
168 int nUnconnectingHeaders;
169 //! Whether we've started headers synchronization with this peer.
170 bool fSyncStarted;
171 //! When to potentially disconnect peer for stalling headers download
172 int64_t nHeadersSyncTimeout;
173 //! Since when we're stalling block download progress (in microseconds), or 0.
174 int64_t nStallingSince;
175 std::list<QueuedBlock> vBlocksInFlight;
176 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
177 int64_t nDownloadingSince;
178 int nBlocksInFlight;
179 int nBlocksInFlightValidHeaders;
180 //! Whether we consider this a preferred download peer.
181 bool fPreferredDownload;
182 //! Whether this peer wants invs or headers (when possible) for block announcements.
183 bool fPreferHeaders;
184 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
185 bool fPreferHeaderAndIDs;
187 * Whether this peer will send us cmpctblocks if we request them.
188 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
189 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
191 bool fProvidesHeaderAndIDs;
192 //! Whether this peer can give us witnesses
193 bool fHaveWitness;
194 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
195 bool fWantsCmpctWitness;
197 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
198 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
200 bool fSupportsDesiredCmpctVersion;
202 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
203 fCurrentlyConnected = false;
204 nMisbehavior = 0;
205 fShouldBan = false;
206 pindexBestKnownBlock = NULL;
207 hashLastUnknownBlock.SetNull();
208 pindexLastCommonBlock = NULL;
209 pindexBestHeaderSent = NULL;
210 nUnconnectingHeaders = 0;
211 fSyncStarted = false;
212 nHeadersSyncTimeout = 0;
213 nStallingSince = 0;
214 nDownloadingSince = 0;
215 nBlocksInFlight = 0;
216 nBlocksInFlightValidHeaders = 0;
217 fPreferredDownload = false;
218 fPreferHeaders = false;
219 fPreferHeaderAndIDs = false;
220 fProvidesHeaderAndIDs = false;
221 fHaveWitness = false;
222 fWantsCmpctWitness = false;
223 fSupportsDesiredCmpctVersion = false;
227 /** Map maintaining per-node state. Requires cs_main. */
228 std::map<NodeId, CNodeState> mapNodeState;
230 // Requires cs_main.
231 CNodeState *State(NodeId pnode) {
232 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
233 if (it == mapNodeState.end())
234 return NULL;
235 return &it->second;
238 void UpdatePreferredDownload(CNode* node, CNodeState* state)
240 nPreferredDownload -= state->fPreferredDownload;
242 // Whether this node should be marked as a preferred download node.
243 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
245 nPreferredDownload += state->fPreferredDownload;
248 void PushNodeVersion(CNode *pnode, CConnman& connman, int64_t nTime)
250 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
251 uint64_t nonce = pnode->GetLocalNonce();
252 int nNodeStartingHeight = pnode->GetMyStartingHeight();
253 NodeId nodeid = pnode->GetId();
254 CAddress addr = pnode->addr;
256 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
257 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
259 connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
260 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
262 if (fLogIPs) {
263 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
264 } else {
265 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
269 void InitializeNode(CNode *pnode, CConnman& connman) {
270 CAddress addr = pnode->addr;
271 std::string addrName = pnode->GetAddrName();
272 NodeId nodeid = pnode->GetId();
274 LOCK(cs_main);
275 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
277 if(!pnode->fInbound)
278 PushNodeVersion(pnode, connman, GetTime());
281 void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
282 fUpdateConnectionTime = false;
283 LOCK(cs_main);
284 CNodeState *state = State(nodeid);
286 if (state->fSyncStarted)
287 nSyncStarted--;
289 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
290 fUpdateConnectionTime = true;
293 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
294 mapBlocksInFlight.erase(entry.hash);
296 EraseOrphansFor(nodeid);
297 nPreferredDownload -= state->fPreferredDownload;
298 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
299 assert(nPeersWithValidatedDownloads >= 0);
301 mapNodeState.erase(nodeid);
303 if (mapNodeState.empty()) {
304 // Do a consistency check after the last peer is removed.
305 assert(mapBlocksInFlight.empty());
306 assert(nPreferredDownload == 0);
307 assert(nPeersWithValidatedDownloads == 0);
309 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
312 // Requires cs_main.
313 // Returns a bool indicating whether we requested this block.
314 // Also used if a block was /not/ received and timed out or started with another peer
315 bool MarkBlockAsReceived(const uint256& hash) {
316 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
317 if (itInFlight != mapBlocksInFlight.end()) {
318 CNodeState *state = State(itInFlight->second.first);
319 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
320 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
321 // Last validated block on the queue was received.
322 nPeersWithValidatedDownloads--;
324 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
325 // First block on the queue was received, update the start download time for the next one
326 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
328 state->vBlocksInFlight.erase(itInFlight->second.second);
329 state->nBlocksInFlight--;
330 state->nStallingSince = 0;
331 mapBlocksInFlight.erase(itInFlight);
332 return true;
334 return false;
337 // Requires cs_main.
338 // returns false, still setting pit, if the block was already in flight from the same peer
339 // pit will only be valid as long as the same cs_main lock is being held
340 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = NULL, std::list<QueuedBlock>::iterator** pit = NULL) {
341 CNodeState *state = State(nodeid);
342 assert(state != NULL);
344 // Short-circuit most stuff in case its from the same node
345 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
346 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
347 *pit = &itInFlight->second.second;
348 return false;
351 // Make sure it's not listed somewhere already.
352 MarkBlockAsReceived(hash);
354 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
355 {hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)});
356 state->nBlocksInFlight++;
357 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
358 if (state->nBlocksInFlight == 1) {
359 // We're starting a block download (batch) from this peer.
360 state->nDownloadingSince = GetTimeMicros();
362 if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
363 nPeersWithValidatedDownloads++;
365 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
366 if (pit)
367 *pit = &itInFlight->second.second;
368 return true;
371 /** Check whether the last unknown block a peer advertised is not yet known. */
372 void ProcessBlockAvailability(NodeId nodeid) {
373 CNodeState *state = State(nodeid);
374 assert(state != NULL);
376 if (!state->hashLastUnknownBlock.IsNull()) {
377 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
378 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
379 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
380 state->pindexBestKnownBlock = itOld->second;
381 state->hashLastUnknownBlock.SetNull();
386 /** Update tracking information about which blocks a peer is assumed to have. */
387 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
388 CNodeState *state = State(nodeid);
389 assert(state != NULL);
391 ProcessBlockAvailability(nodeid);
393 BlockMap::iterator it = mapBlockIndex.find(hash);
394 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
395 // An actually better block was announced.
396 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
397 state->pindexBestKnownBlock = it->second;
398 } else {
399 // An unknown block was announced; just assume that the latest one is the best one.
400 state->hashLastUnknownBlock = hash;
404 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman& connman) {
405 AssertLockHeld(cs_main);
406 CNodeState* nodestate = State(nodeid);
407 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
408 // Never ask from peers who can't provide witnesses.
409 return;
411 if (nodestate->fProvidesHeaderAndIDs) {
412 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
413 if (*it == nodeid) {
414 lNodesAnnouncingHeaderAndIDs.erase(it);
415 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
416 return;
419 connman.ForNode(nodeid, [&connman](CNode* pfrom){
420 bool fAnnounceUsingCMPCTBLOCK = false;
421 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
422 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
423 // As per BIP152, we only get 3 of our peers to announce
424 // blocks using compact encodings.
425 connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [&connman, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion](CNode* pnodeStop){
426 connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
427 return true;
429 lNodesAnnouncingHeaderAndIDs.pop_front();
431 fAnnounceUsingCMPCTBLOCK = true;
432 connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
433 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
434 return true;
439 // Requires cs_main
440 bool CanDirectFetch(const Consensus::Params &consensusParams)
442 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
445 // Requires cs_main
446 bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
448 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
449 return true;
450 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
451 return true;
452 return false;
455 /** Find the last common ancestor two blocks have.
456 * Both pa and pb must be non-NULL. */
457 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
458 if (pa->nHeight > pb->nHeight) {
459 pa = pa->GetAncestor(pb->nHeight);
460 } else if (pb->nHeight > pa->nHeight) {
461 pb = pb->GetAncestor(pa->nHeight);
464 while (pa != pb && pa && pb) {
465 pa = pa->pprev;
466 pb = pb->pprev;
469 // Eventually all chain branches meet at the genesis block.
470 assert(pa == pb);
471 return pa;
474 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
475 * at most count entries. */
476 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
477 if (count == 0)
478 return;
480 vBlocks.reserve(vBlocks.size() + count);
481 CNodeState *state = State(nodeid);
482 assert(state != NULL);
484 // Make sure pindexBestKnownBlock is up to date, we'll need it.
485 ProcessBlockAvailability(nodeid);
487 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < UintToArith256(consensusParams.nMinimumChainWork)) {
488 // This peer has nothing interesting.
489 return;
492 if (state->pindexLastCommonBlock == NULL) {
493 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
494 // Guessing wrong in either direction is not a problem.
495 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
498 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
499 // of its current tip anymore. Go back enough to fix that.
500 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
501 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
502 return;
504 std::vector<const CBlockIndex*> vToFetch;
505 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
506 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
507 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
508 // download that next block if the window were 1 larger.
509 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
510 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
511 NodeId waitingfor = -1;
512 while (pindexWalk->nHeight < nMaxHeight) {
513 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
514 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
515 // as iterating over ~100 CBlockIndex* entries anyway.
516 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
517 vToFetch.resize(nToFetch);
518 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
519 vToFetch[nToFetch - 1] = pindexWalk;
520 for (unsigned int i = nToFetch - 1; i > 0; i--) {
521 vToFetch[i - 1] = vToFetch[i]->pprev;
524 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
525 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
526 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
527 // already part of our chain (and therefore don't need it even if pruned).
528 BOOST_FOREACH(const CBlockIndex* pindex, vToFetch) {
529 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
530 // We consider the chain that this peer is on invalid.
531 return;
533 if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
534 // We wouldn't download this block or its descendants from this peer.
535 return;
537 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
538 if (pindex->nChainTx)
539 state->pindexLastCommonBlock = pindex;
540 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
541 // The block is not already downloaded, and not yet in flight.
542 if (pindex->nHeight > nWindowEnd) {
543 // We reached the end of the window.
544 if (vBlocks.size() == 0 && waitingfor != nodeid) {
545 // We aren't able to fetch anything, but we would be if the download window was one larger.
546 nodeStaller = waitingfor;
548 return;
550 vBlocks.push_back(pindex);
551 if (vBlocks.size() == count) {
552 return;
554 } else if (waitingfor == -1) {
555 // This is the first already-in-flight block.
556 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
562 } // anon namespace
564 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
565 LOCK(cs_main);
566 CNodeState *state = State(nodeid);
567 if (state == NULL)
568 return false;
569 stats.nMisbehavior = state->nMisbehavior;
570 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
571 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
572 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
573 if (queue.pindex)
574 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
576 return true;
579 void RegisterNodeSignals(CNodeSignals& nodeSignals)
581 nodeSignals.ProcessMessages.connect(&ProcessMessages);
582 nodeSignals.SendMessages.connect(&SendMessages);
583 nodeSignals.InitializeNode.connect(&InitializeNode);
584 nodeSignals.FinalizeNode.connect(&FinalizeNode);
587 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
589 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
590 nodeSignals.SendMessages.disconnect(&SendMessages);
591 nodeSignals.InitializeNode.disconnect(&InitializeNode);
592 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
595 //////////////////////////////////////////////////////////////////////////////
597 // mapOrphanTransactions
600 void AddToCompactExtraTransactions(const CTransactionRef& tx)
602 size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
603 if (max_extra_txn <= 0)
604 return;
605 if (!vExtraTxnForCompact.size())
606 vExtraTxnForCompact.resize(max_extra_txn);
607 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
608 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
611 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
613 const uint256& hash = tx->GetHash();
614 if (mapOrphanTransactions.count(hash))
615 return false;
617 // Ignore big transactions, to avoid a
618 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
619 // large transaction with a missing parent then we assume
620 // it will rebroadcast it later, after the parent transaction(s)
621 // have been mined or received.
622 // 100 orphans, each of which is at most 99,999 bytes big is
623 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
624 unsigned int sz = GetTransactionWeight(*tx);
625 if (sz >= MAX_STANDARD_TX_WEIGHT)
627 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
628 return false;
631 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
632 assert(ret.second);
633 BOOST_FOREACH(const CTxIn& txin, tx->vin) {
634 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
637 AddToCompactExtraTransactions(tx);
639 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
640 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
641 return true;
644 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
646 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
647 if (it == mapOrphanTransactions.end())
648 return 0;
649 BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin)
651 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
652 if (itPrev == mapOrphanTransactionsByPrev.end())
653 continue;
654 itPrev->second.erase(it);
655 if (itPrev->second.empty())
656 mapOrphanTransactionsByPrev.erase(itPrev);
658 mapOrphanTransactions.erase(it);
659 return 1;
662 void EraseOrphansFor(NodeId peer)
664 int nErased = 0;
665 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
666 while (iter != mapOrphanTransactions.end())
668 std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
669 if (maybeErase->second.fromPeer == peer)
671 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
674 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
678 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
680 unsigned int nEvicted = 0;
681 static int64_t nNextSweep;
682 int64_t nNow = GetTime();
683 if (nNextSweep <= nNow) {
684 // Sweep out expired orphan pool entries:
685 int nErased = 0;
686 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
687 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
688 while (iter != mapOrphanTransactions.end())
690 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
691 if (maybeErase->second.nTimeExpire <= nNow) {
692 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
693 } else {
694 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
697 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
698 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
699 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
701 while (mapOrphanTransactions.size() > nMaxOrphans)
703 // Evict a random orphan:
704 uint256 randomhash = GetRandHash();
705 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
706 if (it == mapOrphanTransactions.end())
707 it = mapOrphanTransactions.begin();
708 EraseOrphanTx(it->first);
709 ++nEvicted;
711 return nEvicted;
714 // Requires cs_main.
715 void Misbehaving(NodeId pnode, int howmuch)
717 if (howmuch == 0)
718 return;
720 CNodeState *state = State(pnode);
721 if (state == NULL)
722 return;
724 state->nMisbehavior += howmuch;
725 int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
726 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
728 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
729 state->fShouldBan = true;
730 } else
731 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
741 //////////////////////////////////////////////////////////////////////////////
743 // blockchain -> download logic notification
746 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
747 // Initialize global variables that cannot be constructed at startup.
748 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
751 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
752 LOCK(cs_main);
754 std::vector<uint256> vOrphanErase;
756 for (const CTransactionRef& ptx : pblock->vtx) {
757 const CTransaction& tx = *ptx;
759 // Which orphan pool entries must we evict?
760 for (const auto& txin : tx.vin) {
761 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
762 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
763 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
764 const CTransaction& orphanTx = *(*mi)->second.tx;
765 const uint256& orphanHash = orphanTx.GetHash();
766 vOrphanErase.push_back(orphanHash);
771 // Erase orphan transactions include or precluded by this block
772 if (vOrphanErase.size()) {
773 int nErased = 0;
774 BOOST_FOREACH(uint256 &orphanHash, vOrphanErase) {
775 nErased += EraseOrphanTx(orphanHash);
777 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
781 // All of the following cache a recent block, and are protected by cs_most_recent_block
782 static CCriticalSection cs_most_recent_block;
783 static std::shared_ptr<const CBlock> most_recent_block;
784 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
785 static uint256 most_recent_block_hash;
786 static bool fWitnessesPresentInMostRecentCompactBlock;
788 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
789 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
790 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
792 LOCK(cs_main);
794 static int nHighestFastAnnounce = 0;
795 if (pindex->nHeight <= nHighestFastAnnounce)
796 return;
797 nHighestFastAnnounce = pindex->nHeight;
799 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
800 uint256 hashBlock(pblock->GetHash());
803 LOCK(cs_most_recent_block);
804 most_recent_block_hash = hashBlock;
805 most_recent_block = pblock;
806 most_recent_compact_block = pcmpctblock;
807 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
810 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
811 // TODO: Avoid the repeated-serialization here
812 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
813 return;
814 ProcessBlockAvailability(pnode->GetId());
815 CNodeState &state = *State(pnode->GetId());
816 // If the peer has, or we announced to them the previous block already,
817 // but we don't think they have this one, go ahead and announce it
818 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
819 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
821 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
822 hashBlock.ToString(), pnode->GetId());
823 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
824 state.pindexBestHeaderSent = pindex;
829 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
830 const int nNewHeight = pindexNew->nHeight;
831 connman->SetBestHeight(nNewHeight);
833 if (!fInitialDownload) {
834 // Find the hashes of all blocks that weren't previously in the best chain.
835 std::vector<uint256> vHashes;
836 const CBlockIndex *pindexToAnnounce = pindexNew;
837 while (pindexToAnnounce != pindexFork) {
838 vHashes.push_back(pindexToAnnounce->GetBlockHash());
839 pindexToAnnounce = pindexToAnnounce->pprev;
840 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
841 // Limit announcements in case of a huge reorganization.
842 // Rely on the peer's synchronization mechanism in that case.
843 break;
846 // Relay inventory, but don't relay old inventory during initial block download.
847 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
848 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
849 BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
850 pnode->PushBlockHash(hash);
854 connman->WakeMessageHandler();
857 nTimeBestReceived = GetTime();
860 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
861 LOCK(cs_main);
863 const uint256 hash(block.GetHash());
864 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
866 int nDoS = 0;
867 if (state.IsInvalid(nDoS)) {
868 // Don't send reject message with code 0 or an internal reject code.
869 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
870 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
871 State(it->second.first)->rejects.push_back(reject);
872 if (nDoS > 0 && it->second.second)
873 Misbehaving(it->second.first, nDoS);
876 // Check that:
877 // 1. The block is valid
878 // 2. We're not in initial block download
879 // 3. This is currently the best block we're aware of. We haven't updated
880 // the tip yet so we have no way to check this directly here. Instead we
881 // just check that there are currently no other blocks in flight.
882 else if (state.IsValid() &&
883 !IsInitialBlockDownload() &&
884 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
885 if (it != mapBlockSource.end()) {
886 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, *connman);
889 if (it != mapBlockSource.end())
890 mapBlockSource.erase(it);
893 //////////////////////////////////////////////////////////////////////////////
895 // Messages
899 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
901 switch (inv.type)
903 case MSG_TX:
904 case MSG_WITNESS_TX:
906 assert(recentRejects);
907 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
909 // If the chain tip has changed previously rejected transactions
910 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
911 // or a double-spend. Reset the rejects filter and give those
912 // txs a second chance.
913 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
914 recentRejects->reset();
917 return recentRejects->contains(inv.hash) ||
918 mempool.exists(inv.hash) ||
919 mapOrphanTransactions.count(inv.hash) ||
920 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
921 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
923 case MSG_BLOCK:
924 case MSG_WITNESS_BLOCK:
925 return mapBlockIndex.count(inv.hash);
927 // Don't know what it is, just say we already got one
928 return true;
931 static void RelayTransaction(const CTransaction& tx, CConnman& connman)
933 CInv inv(MSG_TX, tx.GetHash());
934 connman.ForEachNode([&inv](CNode* pnode)
936 pnode->PushInventory(inv);
940 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman& connman)
942 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
944 // Relay to a limited number of other nodes
945 // Use deterministic randomness to send to the same nodes for 24 hours
946 // at a time so the addrKnowns of the chosen nodes prevent repeats
947 uint64_t hashAddr = addr.GetHash();
948 const CSipHasher hasher = connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
949 FastRandomContext insecure_rand;
951 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
952 assert(nRelayNodes <= best.size());
954 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
955 if (pnode->nVersion >= CADDR_TIME_VERSION) {
956 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
957 for (unsigned int i = 0; i < nRelayNodes; i++) {
958 if (hashKey > best[i].first) {
959 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
960 best[i] = std::make_pair(hashKey, pnode);
961 break;
967 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
968 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
969 best[i].second->PushAddress(addr, insecure_rand);
973 connman.ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
976 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
978 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
979 std::vector<CInv> vNotFound;
980 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
981 LOCK(cs_main);
983 while (it != pfrom->vRecvGetData.end()) {
984 // Don't bother if send buffer is too full to respond anyway
985 if (pfrom->fPauseSend)
986 break;
988 const CInv &inv = *it;
990 if (interruptMsgProc)
991 return;
993 it++;
995 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
997 bool send = false;
998 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
999 std::shared_ptr<const CBlock> a_recent_block;
1000 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1001 bool fWitnessesPresentInARecentCompactBlock;
1003 LOCK(cs_most_recent_block);
1004 a_recent_block = most_recent_block;
1005 a_recent_compact_block = most_recent_compact_block;
1006 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1008 if (mi != mapBlockIndex.end())
1010 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1011 mi->second->IsValid(BLOCK_VALID_TREE)) {
1012 // If we have the block and all of its parents, but have not yet validated it,
1013 // we might be in the middle of connecting it (ie in the unlock of cs_main
1014 // before ActivateBestChain but after AcceptBlock).
1015 // In this case, we need to run ActivateBestChain prior to checking the relay
1016 // conditions below.
1017 CValidationState dummy;
1018 ActivateBestChain(dummy, Params(), a_recent_block);
1020 if (chainActive.Contains(mi->second)) {
1021 send = true;
1022 } else {
1023 static const int nOneMonth = 30 * 24 * 60 * 60;
1024 // To prevent fingerprinting attacks, only send blocks outside of the active
1025 // chain if they are valid, and no more than a month older (both in time, and in
1026 // best equivalent proof of work) than the best header chain we know about.
1027 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
1028 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
1029 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
1030 if (!send) {
1031 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1035 // disconnect node in case we have reached the outbound limit for serving historical blocks
1036 // never disconnect whitelisted nodes
1037 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
1038 if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1040 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1042 //disconnect node
1043 pfrom->fDisconnect = true;
1044 send = false;
1046 // Pruned nodes may have deleted the block, so check whether
1047 // it's available before trying to send.
1048 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1050 std::shared_ptr<const CBlock> pblock;
1051 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1052 pblock = a_recent_block;
1053 } else {
1054 // Send block from disk
1055 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1056 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1057 assert(!"cannot load block from disk");
1058 pblock = pblockRead;
1060 if (inv.type == MSG_BLOCK)
1061 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1062 else if (inv.type == MSG_WITNESS_BLOCK)
1063 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1064 else if (inv.type == MSG_FILTERED_BLOCK)
1066 bool sendMerkleBlock = false;
1067 CMerkleBlock merkleBlock;
1069 LOCK(pfrom->cs_filter);
1070 if (pfrom->pfilter) {
1071 sendMerkleBlock = true;
1072 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1075 if (sendMerkleBlock) {
1076 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1077 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1078 // This avoids hurting performance by pointlessly requiring a round-trip
1079 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1080 // they must either disconnect and retry or request the full block.
1081 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1082 // however we MUST always provide at least what the remote peer needs
1083 typedef std::pair<unsigned int, uint256> PairType;
1084 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
1085 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1087 // else
1088 // no response
1090 else if (inv.type == MSG_CMPCT_BLOCK)
1092 // If a peer is asking for old blocks, we're almost guaranteed
1093 // they won't have a useful mempool to match against a compact block,
1094 // and we don't feel like constructing the object for them, so
1095 // instead we respond with the full, non-compact block.
1096 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1097 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1098 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1099 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1100 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1101 } else {
1102 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1103 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1105 } else {
1106 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1110 // Trigger the peer node to send a getblocks request for the next batch of inventory
1111 if (inv.hash == pfrom->hashContinue)
1113 // Bypass PushInventory, this must send even if redundant,
1114 // and we want it right after the last block so they don't
1115 // wait for other stuff first.
1116 std::vector<CInv> vInv;
1117 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1118 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1119 pfrom->hashContinue.SetNull();
1123 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1125 // Send stream from relay memory
1126 bool push = false;
1127 auto mi = mapRelay.find(inv.hash);
1128 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1129 if (mi != mapRelay.end()) {
1130 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1131 push = true;
1132 } else if (pfrom->timeLastMempoolReq) {
1133 auto txinfo = mempool.info(inv.hash);
1134 // To protect privacy, do not answer getdata using the mempool when
1135 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1136 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1137 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1138 push = true;
1141 if (!push) {
1142 vNotFound.push_back(inv);
1146 // Track requests for our stuff.
1147 GetMainSignals().Inventory(inv.hash);
1149 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1150 break;
1154 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1156 if (!vNotFound.empty()) {
1157 // Let the peer know that we didn't find what it asked for, so it doesn't
1158 // have to wait around forever. Currently only SPV clients actually care
1159 // about this message: it's needed when they are recursively walking the
1160 // dependencies of relevant unconfirmed transactions. SPV clients want to
1161 // do that because they want to know about (and store and rebroadcast and
1162 // risk analyze) the dependencies of transactions relevant to them, without
1163 // having to download the entire memory pool.
1164 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1168 uint32_t GetFetchFlags(CNode* pfrom) {
1169 uint32_t nFetchFlags = 0;
1170 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1171 nFetchFlags |= MSG_WITNESS_FLAG;
1173 return nFetchFlags;
1176 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman& connman) {
1177 BlockTransactions resp(req);
1178 for (size_t i = 0; i < req.indexes.size(); i++) {
1179 if (req.indexes[i] >= block.vtx.size()) {
1180 LOCK(cs_main);
1181 Misbehaving(pfrom->GetId(), 100);
1182 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1183 return;
1185 resp.txn[i] = block.vtx[req.indexes[i]];
1187 LOCK(cs_main);
1188 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1189 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1190 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1193 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
1195 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1196 if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
1198 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1199 return true;
1203 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1204 (strCommand == NetMsgType::FILTERLOAD ||
1205 strCommand == NetMsgType::FILTERADD))
1207 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1208 LOCK(cs_main);
1209 Misbehaving(pfrom->GetId(), 100);
1210 return false;
1211 } else {
1212 pfrom->fDisconnect = true;
1213 return false;
1217 if (strCommand == NetMsgType::REJECT)
1219 if (LogAcceptCategory(BCLog::NET)) {
1220 try {
1221 std::string strMsg; unsigned char ccode; std::string strReason;
1222 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1224 std::ostringstream ss;
1225 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1227 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1229 uint256 hash;
1230 vRecv >> hash;
1231 ss << ": hash " << hash.ToString();
1233 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1234 } catch (const std::ios_base::failure&) {
1235 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1236 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1241 else if (strCommand == NetMsgType::VERSION)
1243 // Each connection can only send one version message
1244 if (pfrom->nVersion != 0)
1246 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1247 LOCK(cs_main);
1248 Misbehaving(pfrom->GetId(), 1);
1249 return false;
1252 int64_t nTime;
1253 CAddress addrMe;
1254 CAddress addrFrom;
1255 uint64_t nNonce = 1;
1256 uint64_t nServiceInt;
1257 ServiceFlags nServices;
1258 int nVersion;
1259 int nSendVersion;
1260 std::string strSubVer;
1261 std::string cleanSubVer;
1262 int nStartingHeight = -1;
1263 bool fRelay = true;
1265 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1266 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1267 nServices = ServiceFlags(nServiceInt);
1268 if (!pfrom->fInbound)
1270 connman.SetServices(pfrom->addr, nServices);
1272 if (pfrom->nServicesExpected & ~nServices)
1274 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, pfrom->nServicesExpected);
1275 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1276 strprintf("Expected to offer services %08x", pfrom->nServicesExpected)));
1277 pfrom->fDisconnect = true;
1278 return false;
1281 if (nVersion < MIN_PEER_PROTO_VERSION)
1283 // disconnect from peers older than this proto version
1284 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1285 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1286 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1287 pfrom->fDisconnect = true;
1288 return false;
1291 if (nVersion == 10300)
1292 nVersion = 300;
1293 if (!vRecv.empty())
1294 vRecv >> addrFrom >> nNonce;
1295 if (!vRecv.empty()) {
1296 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1297 cleanSubVer = SanitizeString(strSubVer);
1299 if (!vRecv.empty()) {
1300 vRecv >> nStartingHeight;
1302 if (!vRecv.empty())
1303 vRecv >> fRelay;
1304 // Disconnect if we connected to ourself
1305 if (pfrom->fInbound && !connman.CheckIncomingNonce(nNonce))
1307 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1308 pfrom->fDisconnect = true;
1309 return true;
1312 if (pfrom->fInbound && addrMe.IsRoutable())
1314 SeenLocal(addrMe);
1317 // Be shy and don't send version until we hear
1318 if (pfrom->fInbound)
1319 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1321 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1323 pfrom->nServices = nServices;
1324 pfrom->SetAddrLocal(addrMe);
1326 LOCK(pfrom->cs_SubVer);
1327 pfrom->strSubVer = strSubVer;
1328 pfrom->cleanSubVer = cleanSubVer;
1330 pfrom->nStartingHeight = nStartingHeight;
1331 pfrom->fClient = !(nServices & NODE_NETWORK);
1333 LOCK(pfrom->cs_filter);
1334 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1337 // Change version
1338 pfrom->SetSendVersion(nSendVersion);
1339 pfrom->nVersion = nVersion;
1341 if((nServices & NODE_WITNESS))
1343 LOCK(cs_main);
1344 State(pfrom->GetId())->fHaveWitness = true;
1347 // Potentially mark this peer as a preferred download peer.
1349 LOCK(cs_main);
1350 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1353 if (!pfrom->fInbound)
1355 // Advertise our address
1356 if (fListen && !IsInitialBlockDownload())
1358 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1359 FastRandomContext insecure_rand;
1360 if (addr.IsRoutable())
1362 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1363 pfrom->PushAddress(addr, insecure_rand);
1364 } else if (IsPeerAddrLocalGood(pfrom)) {
1365 addr.SetIP(addrMe);
1366 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1367 pfrom->PushAddress(addr, insecure_rand);
1371 // Get recent addresses
1372 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman.GetAddressCount() < 1000)
1374 connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1375 pfrom->fGetAddr = true;
1377 connman.MarkAddressGood(pfrom->addr);
1380 std::string remoteAddr;
1381 if (fLogIPs)
1382 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1384 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1385 cleanSubVer, pfrom->nVersion,
1386 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1387 remoteAddr);
1389 int64_t nTimeOffset = nTime - GetTime();
1390 pfrom->nTimeOffset = nTimeOffset;
1391 AddTimeData(pfrom->addr, nTimeOffset);
1393 // If the peer is old enough to have the old alert system, send it the final alert.
1394 if (pfrom->nVersion <= 70012) {
1395 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1396 connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1399 // Feeler connections exist only to verify if address is online.
1400 if (pfrom->fFeeler) {
1401 assert(pfrom->fInbound == false);
1402 pfrom->fDisconnect = true;
1404 return true;
1408 else if (pfrom->nVersion == 0)
1410 // Must have a version message before anything else
1411 LOCK(cs_main);
1412 Misbehaving(pfrom->GetId(), 1);
1413 return false;
1416 // At this point, the outgoing message serialization version can't change.
1417 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1419 if (strCommand == NetMsgType::VERACK)
1421 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1423 if (!pfrom->fInbound) {
1424 // Mark this node as currently connected, so we update its timestamp later.
1425 LOCK(cs_main);
1426 State(pfrom->GetId())->fCurrentlyConnected = true;
1429 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1430 // Tell our peer we prefer to receive headers rather than inv's
1431 // We send this to non-NODE NETWORK peers as well, because even
1432 // non-NODE NETWORK peers can announce blocks (such as pruning
1433 // nodes)
1434 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1436 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1437 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1438 // However, we do not request new block announcements using
1439 // cmpctblock messages.
1440 // We send this to non-NODE NETWORK peers as well, because
1441 // they may wish to request compact blocks from us
1442 bool fAnnounceUsingCMPCTBLOCK = false;
1443 uint64_t nCMPCTBLOCKVersion = 2;
1444 if (pfrom->GetLocalServices() & NODE_WITNESS)
1445 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1446 nCMPCTBLOCKVersion = 1;
1447 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1449 pfrom->fSuccessfullyConnected = true;
1452 else if (!pfrom->fSuccessfullyConnected)
1454 // Must have a verack message before anything else
1455 LOCK(cs_main);
1456 Misbehaving(pfrom->GetId(), 1);
1457 return false;
1460 else if (strCommand == NetMsgType::ADDR)
1462 std::vector<CAddress> vAddr;
1463 vRecv >> vAddr;
1465 // Don't want addr from older versions unless seeding
1466 if (pfrom->nVersion < CADDR_TIME_VERSION && connman.GetAddressCount() > 1000)
1467 return true;
1468 if (vAddr.size() > 1000)
1470 LOCK(cs_main);
1471 Misbehaving(pfrom->GetId(), 20);
1472 return error("message addr size() = %u", vAddr.size());
1475 // Store the new addresses
1476 std::vector<CAddress> vAddrOk;
1477 int64_t nNow = GetAdjustedTime();
1478 int64_t nSince = nNow - 10 * 60;
1479 BOOST_FOREACH(CAddress& addr, vAddr)
1481 if (interruptMsgProc)
1482 return true;
1484 if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1485 continue;
1487 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1488 addr.nTime = nNow - 5 * 24 * 60 * 60;
1489 pfrom->AddAddressKnown(addr);
1490 bool fReachable = IsReachable(addr);
1491 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1493 // Relay to a limited number of other nodes
1494 RelayAddress(addr, fReachable, connman);
1496 // Do not store addresses outside our network
1497 if (fReachable)
1498 vAddrOk.push_back(addr);
1500 connman.AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1501 if (vAddr.size() < 1000)
1502 pfrom->fGetAddr = false;
1503 if (pfrom->fOneShot)
1504 pfrom->fDisconnect = true;
1507 else if (strCommand == NetMsgType::SENDHEADERS)
1509 LOCK(cs_main);
1510 State(pfrom->GetId())->fPreferHeaders = true;
1513 else if (strCommand == NetMsgType::SENDCMPCT)
1515 bool fAnnounceUsingCMPCTBLOCK = false;
1516 uint64_t nCMPCTBLOCKVersion = 0;
1517 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1518 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1519 LOCK(cs_main);
1520 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1521 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1522 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1523 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1525 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1526 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1527 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1528 if (pfrom->GetLocalServices() & NODE_WITNESS)
1529 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1530 else
1531 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1537 else if (strCommand == NetMsgType::INV)
1539 std::vector<CInv> vInv;
1540 vRecv >> vInv;
1541 if (vInv.size() > MAX_INV_SZ)
1543 LOCK(cs_main);
1544 Misbehaving(pfrom->GetId(), 20);
1545 return error("message inv size() = %u", vInv.size());
1548 bool fBlocksOnly = !fRelayTxes;
1550 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1551 if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1552 fBlocksOnly = false;
1554 LOCK(cs_main);
1556 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1558 for (CInv &inv : vInv)
1560 if (interruptMsgProc)
1561 return true;
1563 bool fAlreadyHave = AlreadyHave(inv);
1564 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1566 if (inv.type == MSG_TX) {
1567 inv.type |= nFetchFlags;
1570 if (inv.type == MSG_BLOCK) {
1571 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1572 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1573 // We used to request the full block here, but since headers-announcements are now the
1574 // primary method of announcement on the network, and since, in the case that a node
1575 // fell back to inv we probably have a reorg which we should get the headers for first,
1576 // we now only provide a getheaders response here. When we receive the headers, we will
1577 // then ask for the blocks we need.
1578 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1579 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1582 else
1584 pfrom->AddInventoryKnown(inv);
1585 if (fBlocksOnly) {
1586 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1587 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1588 pfrom->AskFor(inv);
1592 // Track requests for our stuff
1593 GetMainSignals().Inventory(inv.hash);
1598 else if (strCommand == NetMsgType::GETDATA)
1600 std::vector<CInv> vInv;
1601 vRecv >> vInv;
1602 if (vInv.size() > MAX_INV_SZ)
1604 LOCK(cs_main);
1605 Misbehaving(pfrom->GetId(), 20);
1606 return error("message getdata size() = %u", vInv.size());
1609 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1611 if (vInv.size() > 0) {
1612 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1615 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1616 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1620 else if (strCommand == NetMsgType::GETBLOCKS)
1622 CBlockLocator locator;
1623 uint256 hashStop;
1624 vRecv >> locator >> hashStop;
1626 // We might have announced the currently-being-connected tip using a
1627 // compact block, which resulted in the peer sending a getblocks
1628 // request, which we would otherwise respond to without the new block.
1629 // To avoid this situation we simply verify that we are on our best
1630 // known chain now. This is super overkill, but we handle it better
1631 // for getheaders requests, and there are no known nodes which support
1632 // compact blocks but still use getblocks to request blocks.
1634 std::shared_ptr<const CBlock> a_recent_block;
1636 LOCK(cs_most_recent_block);
1637 a_recent_block = most_recent_block;
1639 CValidationState dummy;
1640 ActivateBestChain(dummy, Params(), a_recent_block);
1643 LOCK(cs_main);
1645 // Find the last block the caller has in the main chain
1646 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1648 // Send the rest of the chain
1649 if (pindex)
1650 pindex = chainActive.Next(pindex);
1651 int nLimit = 500;
1652 LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->GetId());
1653 for (; pindex; pindex = chainActive.Next(pindex))
1655 if (pindex->GetBlockHash() == hashStop)
1657 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1658 break;
1660 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1661 // for some reasonable time window (1 hour) that block relay might require.
1662 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1663 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1665 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1666 break;
1668 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1669 if (--nLimit <= 0)
1671 // When this block is requested, we'll send an inv that'll
1672 // trigger the peer to getblocks the next batch of inventory.
1673 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1674 pfrom->hashContinue = pindex->GetBlockHash();
1675 break;
1681 else if (strCommand == NetMsgType::GETBLOCKTXN)
1683 BlockTransactionsRequest req;
1684 vRecv >> req;
1686 std::shared_ptr<const CBlock> recent_block;
1688 LOCK(cs_most_recent_block);
1689 if (most_recent_block_hash == req.blockhash)
1690 recent_block = most_recent_block;
1691 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1693 if (recent_block) {
1694 SendBlockTransactions(*recent_block, req, pfrom, connman);
1695 return true;
1698 LOCK(cs_main);
1700 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1701 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1702 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
1703 return true;
1706 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1707 // If an older block is requested (should never happen in practice,
1708 // but can happen in tests) send a block response instead of a
1709 // blocktxn response. Sending a full block response instead of a
1710 // small blocktxn response is preferable in the case where a peer
1711 // might maliciously send lots of getblocktxn requests to trigger
1712 // expensive disk reads, because it will require the peer to
1713 // actually receive all the data read from disk over the network.
1714 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
1715 CInv inv;
1716 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
1717 inv.hash = req.blockhash;
1718 pfrom->vRecvGetData.push_back(inv);
1719 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1720 return true;
1723 CBlock block;
1724 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
1725 assert(ret);
1727 SendBlockTransactions(block, req, pfrom, connman);
1731 else if (strCommand == NetMsgType::GETHEADERS)
1733 CBlockLocator locator;
1734 uint256 hashStop;
1735 vRecv >> locator >> hashStop;
1737 LOCK(cs_main);
1738 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
1739 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
1740 return true;
1743 CNodeState *nodestate = State(pfrom->GetId());
1744 const CBlockIndex* pindex = NULL;
1745 if (locator.IsNull())
1747 // If locator is null, return the hashStop block
1748 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
1749 if (mi == mapBlockIndex.end())
1750 return true;
1751 pindex = (*mi).second;
1753 else
1755 // Find the last block the caller has in the main chain
1756 pindex = FindForkInGlobalIndex(chainActive, locator);
1757 if (pindex)
1758 pindex = chainActive.Next(pindex);
1761 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1762 std::vector<CBlock> vHeaders;
1763 int nLimit = MAX_HEADERS_RESULTS;
1764 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
1765 for (; pindex; pindex = chainActive.Next(pindex))
1767 vHeaders.push_back(pindex->GetBlockHeader());
1768 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
1769 break;
1771 // pindex can be NULL either if we sent chainActive.Tip() OR
1772 // if our peer has chainActive.Tip() (and thus we are sending an empty
1773 // headers message). In both cases it's safe to update
1774 // pindexBestHeaderSent to be our tip.
1776 // It is important that we simply reset the BestHeaderSent value here,
1777 // and not max(BestHeaderSent, newHeaderSent). We might have announced
1778 // the currently-being-connected tip using a compact block, which
1779 // resulted in the peer sending a headers request, which we respond to
1780 // without the new block. By resetting the BestHeaderSent, we ensure we
1781 // will re-announce the new block via headers (or compact blocks again)
1782 // in the SendMessages logic.
1783 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
1784 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
1788 else if (strCommand == NetMsgType::TX)
1790 // Stop processing the transaction early if
1791 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1792 if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
1794 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
1795 return true;
1798 std::deque<COutPoint> vWorkQueue;
1799 std::vector<uint256> vEraseQueue;
1800 CTransactionRef ptx;
1801 vRecv >> ptx;
1802 const CTransaction& tx = *ptx;
1804 CInv inv(MSG_TX, tx.GetHash());
1805 pfrom->AddInventoryKnown(inv);
1807 LOCK(cs_main);
1809 bool fMissingInputs = false;
1810 CValidationState state;
1812 pfrom->setAskFor.erase(inv.hash);
1813 mapAlreadyAskedFor.erase(inv.hash);
1815 std::list<CTransactionRef> lRemovedTxn;
1817 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, ptx, true, &fMissingInputs, &lRemovedTxn)) {
1818 mempool.check(pcoinsTip);
1819 RelayTransaction(tx, connman);
1820 for (unsigned int i = 0; i < tx.vout.size(); i++) {
1821 vWorkQueue.emplace_back(inv.hash, i);
1824 pfrom->nLastTXTime = GetTime();
1826 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1827 pfrom->GetId(),
1828 tx.GetHash().ToString(),
1829 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
1831 // Recursively process any orphan transactions that depended on this one
1832 std::set<NodeId> setMisbehaving;
1833 while (!vWorkQueue.empty()) {
1834 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
1835 vWorkQueue.pop_front();
1836 if (itByPrev == mapOrphanTransactionsByPrev.end())
1837 continue;
1838 for (auto mi = itByPrev->second.begin();
1839 mi != itByPrev->second.end();
1840 ++mi)
1842 const CTransactionRef& porphanTx = (*mi)->second.tx;
1843 const CTransaction& orphanTx = *porphanTx;
1844 const uint256& orphanHash = orphanTx.GetHash();
1845 NodeId fromPeer = (*mi)->second.fromPeer;
1846 bool fMissingInputs2 = false;
1847 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1848 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1849 // anyone relaying LegitTxX banned)
1850 CValidationState stateDummy;
1853 if (setMisbehaving.count(fromPeer))
1854 continue;
1855 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, true, &fMissingInputs2, &lRemovedTxn)) {
1856 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
1857 RelayTransaction(orphanTx, connman);
1858 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
1859 vWorkQueue.emplace_back(orphanHash, i);
1861 vEraseQueue.push_back(orphanHash);
1863 else if (!fMissingInputs2)
1865 int nDos = 0;
1866 if (stateDummy.IsInvalid(nDos) && nDos > 0)
1868 // Punish peer that gave us an invalid orphan tx
1869 Misbehaving(fromPeer, nDos);
1870 setMisbehaving.insert(fromPeer);
1871 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
1873 // Has inputs but not accepted to mempool
1874 // Probably non-standard or insufficient fee
1875 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
1876 vEraseQueue.push_back(orphanHash);
1877 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
1878 // Do not use rejection cache for witness transactions or
1879 // witness-stripped transactions, as they can have been malleated.
1880 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1881 assert(recentRejects);
1882 recentRejects->insert(orphanHash);
1885 mempool.check(pcoinsTip);
1889 BOOST_FOREACH(uint256 hash, vEraseQueue)
1890 EraseOrphanTx(hash);
1892 else if (fMissingInputs)
1894 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
1895 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1896 if (recentRejects->contains(txin.prevout.hash)) {
1897 fRejectedParents = true;
1898 break;
1901 if (!fRejectedParents) {
1902 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1903 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1904 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
1905 pfrom->AddInventoryKnown(_inv);
1906 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
1908 AddOrphanTx(ptx, pfrom->GetId());
1910 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1911 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
1912 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
1913 if (nEvicted > 0) {
1914 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
1916 } else {
1917 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
1918 // We will continue to reject this tx since it has rejected
1919 // parents so avoid re-requesting it from other peers.
1920 recentRejects->insert(tx.GetHash());
1922 } else {
1923 if (!tx.HasWitness() && !state.CorruptionPossible()) {
1924 // Do not use rejection cache for witness transactions or
1925 // witness-stripped transactions, as they can have been malleated.
1926 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1927 assert(recentRejects);
1928 recentRejects->insert(tx.GetHash());
1929 if (RecursiveDynamicUsage(*ptx) < 100000) {
1930 AddToCompactExtraTransactions(ptx);
1932 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
1933 AddToCompactExtraTransactions(ptx);
1936 if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1937 // Always relay transactions received from whitelisted peers, even
1938 // if they were already in the mempool or rejected from it due
1939 // to policy, allowing the node to function as a gateway for
1940 // nodes hidden behind it.
1942 // Never relay transactions that we would assign a non-zero DoS
1943 // score for, as we expect peers to do the same with us in that
1944 // case.
1945 int nDoS = 0;
1946 if (!state.IsInvalid(nDoS) || nDoS == 0) {
1947 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
1948 RelayTransaction(tx, connman);
1949 } else {
1950 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
1955 for (const CTransactionRef& removedTx : lRemovedTxn)
1956 AddToCompactExtraTransactions(removedTx);
1958 int nDoS = 0;
1959 if (state.IsInvalid(nDoS))
1961 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
1962 pfrom->GetId(),
1963 FormatStateMessage(state));
1964 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
1965 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
1966 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
1967 if (nDoS > 0) {
1968 Misbehaving(pfrom->GetId(), nDoS);
1974 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
1976 CBlockHeaderAndShortTxIDs cmpctblock;
1977 vRecv >> cmpctblock;
1980 LOCK(cs_main);
1982 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
1983 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1984 if (!IsInitialBlockDownload())
1985 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1986 return true;
1990 const CBlockIndex *pindex = NULL;
1991 CValidationState state;
1992 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
1993 int nDoS;
1994 if (state.IsInvalid(nDoS)) {
1995 if (nDoS > 0) {
1996 LOCK(cs_main);
1997 Misbehaving(pfrom->GetId(), nDoS);
1999 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2000 return true;
2004 // When we succeed in decoding a block's txids from a cmpctblock
2005 // message we typically jump to the BLOCKTXN handling code, with a
2006 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2007 // completing processing of the putative block (without cs_main).
2008 bool fProcessBLOCKTXN = false;
2009 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2011 // If we end up treating this as a plain headers message, call that as well
2012 // without cs_main.
2013 bool fRevertToHeaderProcessing = false;
2014 CDataStream vHeadersMsg(SER_NETWORK, PROTOCOL_VERSION);
2016 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2017 // below)
2018 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2019 bool fBlockReconstructed = false;
2022 LOCK(cs_main);
2023 // If AcceptBlockHeader returned true, it set pindex
2024 assert(pindex);
2025 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2027 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2028 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2030 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2031 return true;
2033 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2034 pindex->nTx != 0) { // We had this block at some point, but pruned it
2035 if (fAlreadyInFlight) {
2036 // We requested this block for some reason, but our mempool will probably be useless
2037 // so we just grab the block via normal getdata
2038 std::vector<CInv> vInv(1);
2039 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2040 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2042 return true;
2045 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2046 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2047 return true;
2049 CNodeState *nodestate = State(pfrom->GetId());
2051 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2052 // Don't bother trying to process compact blocks from v1 peers
2053 // after segwit activates.
2054 return true;
2057 // We want to be a bit conservative just to be extra careful about DoS
2058 // possibilities in compact block processing...
2059 if (pindex->nHeight <= chainActive.Height() + 2) {
2060 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2061 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2062 std::list<QueuedBlock>::iterator* queuedBlockIt = NULL;
2063 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2064 if (!(*queuedBlockIt)->partialBlock)
2065 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2066 else {
2067 // The block was already in flight using compact blocks from the same peer
2068 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2069 return true;
2073 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2074 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2075 if (status == READ_STATUS_INVALID) {
2076 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2077 Misbehaving(pfrom->GetId(), 100);
2078 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2079 return true;
2080 } else if (status == READ_STATUS_FAILED) {
2081 // Duplicate txindexes, the block is now in-flight, so just request it
2082 std::vector<CInv> vInv(1);
2083 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2084 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2085 return true;
2088 BlockTransactionsRequest req;
2089 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2090 if (!partialBlock.IsTxAvailable(i))
2091 req.indexes.push_back(i);
2093 if (req.indexes.empty()) {
2094 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2095 BlockTransactions txn;
2096 txn.blockhash = cmpctblock.header.GetHash();
2097 blockTxnMsg << txn;
2098 fProcessBLOCKTXN = true;
2099 } else {
2100 req.blockhash = pindex->GetBlockHash();
2101 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2103 } else {
2104 // This block is either already in flight from a different
2105 // peer, or this peer has too many blocks outstanding to
2106 // download from.
2107 // Optimistically try to reconstruct anyway since we might be
2108 // able to without any round trips.
2109 PartiallyDownloadedBlock tempBlock(&mempool);
2110 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2111 if (status != READ_STATUS_OK) {
2112 // TODO: don't ignore failures
2113 return true;
2115 std::vector<CTransactionRef> dummy;
2116 status = tempBlock.FillBlock(*pblock, dummy);
2117 if (status == READ_STATUS_OK) {
2118 fBlockReconstructed = true;
2121 } else {
2122 if (fAlreadyInFlight) {
2123 // We requested this block, but its far into the future, so our
2124 // mempool will probably be useless - request the block normally
2125 std::vector<CInv> vInv(1);
2126 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2127 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2128 return true;
2129 } else {
2130 // If this was an announce-cmpctblock, we want the same treatment as a header message
2131 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
2132 std::vector<CBlock> headers;
2133 headers.push_back(cmpctblock.header);
2134 vHeadersMsg << headers;
2135 fRevertToHeaderProcessing = true;
2138 } // cs_main
2140 if (fProcessBLOCKTXN)
2141 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2143 if (fRevertToHeaderProcessing)
2144 return ProcessMessage(pfrom, NetMsgType::HEADERS, vHeadersMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2146 if (fBlockReconstructed) {
2147 // If we got here, we were able to optimistically reconstruct a
2148 // block that is in flight from some other peer.
2150 LOCK(cs_main);
2151 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2153 bool fNewBlock = false;
2154 ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
2155 if (fNewBlock)
2156 pfrom->nLastBlockTime = GetTime();
2158 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2159 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2160 // Clear download state for this block, which is in
2161 // process from some other peer. We do this after calling
2162 // ProcessNewBlock so that a malleated cmpctblock announcement
2163 // can't be used to interfere with block relay.
2164 MarkBlockAsReceived(pblock->GetHash());
2170 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2172 BlockTransactions resp;
2173 vRecv >> resp;
2175 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2176 bool fBlockRead = false;
2178 LOCK(cs_main);
2180 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2181 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2182 it->second.first != pfrom->GetId()) {
2183 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2184 return true;
2187 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2188 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2189 if (status == READ_STATUS_INVALID) {
2190 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2191 Misbehaving(pfrom->GetId(), 100);
2192 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2193 return true;
2194 } else if (status == READ_STATUS_FAILED) {
2195 // Might have collided, fall back to getdata now :(
2196 std::vector<CInv> invs;
2197 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2198 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2199 } else {
2200 // Block is either okay, or possibly we received
2201 // READ_STATUS_CHECKBLOCK_FAILED.
2202 // Note that CheckBlock can only fail for one of a few reasons:
2203 // 1. bad-proof-of-work (impossible here, because we've already
2204 // accepted the header)
2205 // 2. merkleroot doesn't match the transactions given (already
2206 // caught in FillBlock with READ_STATUS_FAILED, so
2207 // impossible here)
2208 // 3. the block is otherwise invalid (eg invalid coinbase,
2209 // block is too big, too many legacy sigops, etc).
2210 // So if CheckBlock failed, #3 is the only possibility.
2211 // Under BIP 152, we don't DoS-ban unless proof of work is
2212 // invalid (we don't require all the stateless checks to have
2213 // been run). This is handled below, so just treat this as
2214 // though the block was successfully read, and rely on the
2215 // handling in ProcessNewBlock to ensure the block index is
2216 // updated, reject messages go out, etc.
2217 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2218 fBlockRead = true;
2219 // mapBlockSource is only used for sending reject messages and DoS scores,
2220 // so the race between here and cs_main in ProcessNewBlock is fine.
2221 // BIP 152 permits peers to relay compact blocks after validating
2222 // the header only; we should not punish peers if the block turns
2223 // out to be invalid.
2224 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2226 } // Don't hold cs_main when we call into ProcessNewBlock
2227 if (fBlockRead) {
2228 bool fNewBlock = false;
2229 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2230 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2231 ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
2232 if (fNewBlock)
2233 pfrom->nLastBlockTime = GetTime();
2238 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2240 std::vector<CBlockHeader> headers;
2242 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2243 unsigned int nCount = ReadCompactSize(vRecv);
2244 if (nCount > MAX_HEADERS_RESULTS) {
2245 LOCK(cs_main);
2246 Misbehaving(pfrom->GetId(), 20);
2247 return error("headers message size = %u", nCount);
2249 headers.resize(nCount);
2250 for (unsigned int n = 0; n < nCount; n++) {
2251 vRecv >> headers[n];
2252 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2255 if (nCount == 0) {
2256 // Nothing interesting. Stop asking this peers for more headers.
2257 return true;
2260 const CBlockIndex *pindexLast = NULL;
2262 LOCK(cs_main);
2263 CNodeState *nodestate = State(pfrom->GetId());
2265 // If this looks like it could be a block announcement (nCount <
2266 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2267 // don't connect:
2268 // - Send a getheaders message in response to try to connect the chain.
2269 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2270 // don't connect before giving DoS points
2271 // - Once a headers message is received that is valid and does connect,
2272 // nUnconnectingHeaders gets reset back to 0.
2273 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
2274 nodestate->nUnconnectingHeaders++;
2275 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2276 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2277 headers[0].GetHash().ToString(),
2278 headers[0].hashPrevBlock.ToString(),
2279 pindexBestHeader->nHeight,
2280 pfrom->GetId(), nodestate->nUnconnectingHeaders);
2281 // Set hashLastUnknownBlock for this peer, so that if we
2282 // eventually get the headers - even from a different peer -
2283 // we can use this peer to download.
2284 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
2286 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
2287 Misbehaving(pfrom->GetId(), 20);
2289 return true;
2292 uint256 hashLastBlock;
2293 for (const CBlockHeader& header : headers) {
2294 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2295 Misbehaving(pfrom->GetId(), 20);
2296 return error("non-continuous headers sequence");
2298 hashLastBlock = header.GetHash();
2302 CValidationState state;
2303 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast)) {
2304 int nDoS;
2305 if (state.IsInvalid(nDoS)) {
2306 if (nDoS > 0) {
2307 LOCK(cs_main);
2308 Misbehaving(pfrom->GetId(), nDoS);
2310 return error("invalid header received");
2315 LOCK(cs_main);
2316 CNodeState *nodestate = State(pfrom->GetId());
2317 if (nodestate->nUnconnectingHeaders > 0) {
2318 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
2320 nodestate->nUnconnectingHeaders = 0;
2322 assert(pindexLast);
2323 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
2325 if (nCount == MAX_HEADERS_RESULTS) {
2326 // Headers message had its maximum size; the peer may have more headers.
2327 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2328 // from there instead.
2329 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
2330 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
2333 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
2334 // If this set of headers is valid and ends in a block with at least as
2335 // much work as our tip, download as much as possible.
2336 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
2337 std::vector<const CBlockIndex*> vToFetch;
2338 const CBlockIndex *pindexWalk = pindexLast;
2339 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2340 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2341 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2342 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
2343 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
2344 // We don't have this block, and it's not yet in flight.
2345 vToFetch.push_back(pindexWalk);
2347 pindexWalk = pindexWalk->pprev;
2349 // If pindexWalk still isn't on our main chain, we're looking at a
2350 // very large reorg at a time we think we're close to caught up to
2351 // the main chain -- this shouldn't really happen. Bail out on the
2352 // direct fetch and rely on parallel download instead.
2353 if (!chainActive.Contains(pindexWalk)) {
2354 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2355 pindexLast->GetBlockHash().ToString(),
2356 pindexLast->nHeight);
2357 } else {
2358 std::vector<CInv> vGetData;
2359 // Download as much as possible, from earliest to latest.
2360 BOOST_REVERSE_FOREACH(const CBlockIndex *pindex, vToFetch) {
2361 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2362 // Can't download any more from this peer
2363 break;
2365 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2366 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2367 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
2368 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
2369 pindex->GetBlockHash().ToString(), pfrom->GetId());
2371 if (vGetData.size() > 1) {
2372 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2373 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
2375 if (vGetData.size() > 0) {
2376 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
2377 // In any case, we want to download using a compact block, not a regular one
2378 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2380 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2387 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2389 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2390 vRecv >> *pblock;
2392 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2394 // Process all blocks from whitelisted peers, even if not requested,
2395 // unless we're still syncing with the network.
2396 // Such an unrequested block may still be processed, subject to the
2397 // conditions in AcceptBlock().
2398 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
2399 const uint256 hash(pblock->GetHash());
2401 LOCK(cs_main);
2402 // Also always process if we requested the block explicitly, as we may
2403 // need it even though it is not a candidate for a new best tip.
2404 forceProcessing |= MarkBlockAsReceived(hash);
2405 // mapBlockSource is only used for sending reject messages and DoS scores,
2406 // so the race between here and cs_main in ProcessNewBlock is fine.
2407 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2409 bool fNewBlock = false;
2410 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2411 if (fNewBlock)
2412 pfrom->nLastBlockTime = GetTime();
2416 else if (strCommand == NetMsgType::GETADDR)
2418 // This asymmetric behavior for inbound and outbound connections was introduced
2419 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2420 // to users' AddrMan and later request them by sending getaddr messages.
2421 // Making nodes which are behind NAT and can only make outgoing connections ignore
2422 // the getaddr message mitigates the attack.
2423 if (!pfrom->fInbound) {
2424 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2425 return true;
2428 // Only send one GetAddr response per connection to reduce resource waste
2429 // and discourage addr stamping of INV announcements.
2430 if (pfrom->fSentAddr) {
2431 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2432 return true;
2434 pfrom->fSentAddr = true;
2436 pfrom->vAddrToSend.clear();
2437 std::vector<CAddress> vAddr = connman.GetAddresses();
2438 FastRandomContext insecure_rand;
2439 BOOST_FOREACH(const CAddress &addr, vAddr)
2440 pfrom->PushAddress(addr, insecure_rand);
2444 else if (strCommand == NetMsgType::MEMPOOL)
2446 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2448 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2449 pfrom->fDisconnect = true;
2450 return true;
2453 if (connman.OutboundTargetReached(false) && !pfrom->fWhitelisted)
2455 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2456 pfrom->fDisconnect = true;
2457 return true;
2460 LOCK(pfrom->cs_inventory);
2461 pfrom->fSendMempool = true;
2465 else if (strCommand == NetMsgType::PING)
2467 if (pfrom->nVersion > BIP0031_VERSION)
2469 uint64_t nonce = 0;
2470 vRecv >> nonce;
2471 // Echo the message back with the nonce. This allows for two useful features:
2473 // 1) A remote node can quickly check if the connection is operational
2474 // 2) Remote nodes can measure the latency of the network thread. If this node
2475 // is overloaded it won't respond to pings quickly and the remote node can
2476 // avoid sending us more work, like chain download requests.
2478 // The nonce stops the remote getting confused between different pings: without
2479 // it, if the remote node sends a ping once per second and this node takes 5
2480 // seconds to respond to each, the 5th ping the remote sends would appear to
2481 // return very quickly.
2482 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2487 else if (strCommand == NetMsgType::PONG)
2489 int64_t pingUsecEnd = nTimeReceived;
2490 uint64_t nonce = 0;
2491 size_t nAvail = vRecv.in_avail();
2492 bool bPingFinished = false;
2493 std::string sProblem;
2495 if (nAvail >= sizeof(nonce)) {
2496 vRecv >> nonce;
2498 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2499 if (pfrom->nPingNonceSent != 0) {
2500 if (nonce == pfrom->nPingNonceSent) {
2501 // Matching pong received, this ping is no longer outstanding
2502 bPingFinished = true;
2503 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2504 if (pingUsecTime > 0) {
2505 // Successful ping time measurement, replace previous
2506 pfrom->nPingUsecTime = pingUsecTime;
2507 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2508 } else {
2509 // This should never happen
2510 sProblem = "Timing mishap";
2512 } else {
2513 // Nonce mismatches are normal when pings are overlapping
2514 sProblem = "Nonce mismatch";
2515 if (nonce == 0) {
2516 // This is most likely a bug in another implementation somewhere; cancel this ping
2517 bPingFinished = true;
2518 sProblem = "Nonce zero";
2521 } else {
2522 sProblem = "Unsolicited pong without ping";
2524 } else {
2525 // This is most likely a bug in another implementation somewhere; cancel this ping
2526 bPingFinished = true;
2527 sProblem = "Short payload";
2530 if (!(sProblem.empty())) {
2531 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2532 pfrom->GetId(),
2533 sProblem,
2534 pfrom->nPingNonceSent,
2535 nonce,
2536 nAvail);
2538 if (bPingFinished) {
2539 pfrom->nPingNonceSent = 0;
2544 else if (strCommand == NetMsgType::FILTERLOAD)
2546 CBloomFilter filter;
2547 vRecv >> filter;
2549 if (!filter.IsWithinSizeConstraints())
2551 // There is no excuse for sending a too-large filter
2552 LOCK(cs_main);
2553 Misbehaving(pfrom->GetId(), 100);
2555 else
2557 LOCK(pfrom->cs_filter);
2558 delete pfrom->pfilter;
2559 pfrom->pfilter = new CBloomFilter(filter);
2560 pfrom->pfilter->UpdateEmptyFull();
2561 pfrom->fRelayTxes = true;
2566 else if (strCommand == NetMsgType::FILTERADD)
2568 std::vector<unsigned char> vData;
2569 vRecv >> vData;
2571 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2572 // and thus, the maximum size any matched object can have) in a filteradd message
2573 bool bad = false;
2574 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2575 bad = true;
2576 } else {
2577 LOCK(pfrom->cs_filter);
2578 if (pfrom->pfilter) {
2579 pfrom->pfilter->insert(vData);
2580 } else {
2581 bad = true;
2584 if (bad) {
2585 LOCK(cs_main);
2586 Misbehaving(pfrom->GetId(), 100);
2591 else if (strCommand == NetMsgType::FILTERCLEAR)
2593 LOCK(pfrom->cs_filter);
2594 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2595 delete pfrom->pfilter;
2596 pfrom->pfilter = new CBloomFilter();
2598 pfrom->fRelayTxes = true;
2601 else if (strCommand == NetMsgType::FEEFILTER) {
2602 CAmount newFeeFilter = 0;
2603 vRecv >> newFeeFilter;
2604 if (MoneyRange(newFeeFilter)) {
2606 LOCK(pfrom->cs_feeFilter);
2607 pfrom->minFeeFilter = newFeeFilter;
2609 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2613 else if (strCommand == NetMsgType::NOTFOUND) {
2614 // We do not care about the NOTFOUND message, but logging an Unknown Command
2615 // message would be undesirable as we transmit it ourselves.
2618 else {
2619 // Ignore unknown commands for extensibility
2620 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2625 return true;
2628 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman& connman)
2630 AssertLockHeld(cs_main);
2631 CNodeState &state = *State(pnode->GetId());
2633 BOOST_FOREACH(const CBlockReject& reject, state.rejects) {
2634 connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2636 state.rejects.clear();
2638 if (state.fShouldBan) {
2639 state.fShouldBan = false;
2640 if (pnode->fWhitelisted)
2641 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2642 else if (pnode->fAddnode)
2643 LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode->addr.ToString());
2644 else {
2645 pnode->fDisconnect = true;
2646 if (pnode->addr.IsLocal())
2647 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2648 else
2650 connman.Ban(pnode->addr, BanReasonNodeMisbehaving);
2653 return true;
2655 return false;
2658 bool ProcessMessages(CNode* pfrom, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
2660 const CChainParams& chainparams = Params();
2662 // Message format
2663 // (4) message start
2664 // (12) command
2665 // (4) size
2666 // (4) checksum
2667 // (x) data
2669 bool fMoreWork = false;
2671 if (!pfrom->vRecvGetData.empty())
2672 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2674 if (pfrom->fDisconnect)
2675 return false;
2677 // this maintains the order of responses
2678 if (!pfrom->vRecvGetData.empty()) return true;
2680 // Don't bother if send buffer is too full to respond anyway
2681 if (pfrom->fPauseSend)
2682 return false;
2684 std::list<CNetMessage> msgs;
2686 LOCK(pfrom->cs_vProcessMsg);
2687 if (pfrom->vProcessMsg.empty())
2688 return false;
2689 // Just take one message
2690 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2691 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2692 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman.GetReceiveFloodSize();
2693 fMoreWork = !pfrom->vProcessMsg.empty();
2695 CNetMessage& msg(msgs.front());
2697 msg.SetVersion(pfrom->GetRecvVersion());
2698 // Scan for message start
2699 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2700 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2701 pfrom->fDisconnect = true;
2702 return false;
2705 // Read header
2706 CMessageHeader& hdr = msg.hdr;
2707 if (!hdr.IsValid(chainparams.MessageStart()))
2709 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2710 return fMoreWork;
2712 std::string strCommand = hdr.GetCommand();
2714 // Message size
2715 unsigned int nMessageSize = hdr.nMessageSize;
2717 // Checksum
2718 CDataStream& vRecv = msg.vRecv;
2719 const uint256& hash = msg.GetMessageHash();
2720 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2722 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2723 SanitizeString(strCommand), nMessageSize,
2724 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2725 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2726 return fMoreWork;
2729 // Process message
2730 bool fRet = false;
2733 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2734 if (interruptMsgProc)
2735 return false;
2736 if (!pfrom->vRecvGetData.empty())
2737 fMoreWork = true;
2739 catch (const std::ios_base::failure& e)
2741 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2742 if (strstr(e.what(), "end of data"))
2744 // Allow exceptions from under-length message on vRecv
2745 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());
2747 else if (strstr(e.what(), "size too large"))
2749 // Allow exceptions from over-long size
2750 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2752 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2754 // Allow exceptions from non-canonical encoding
2755 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2757 else
2759 PrintExceptionContinue(&e, "ProcessMessages()");
2762 catch (const std::exception& e) {
2763 PrintExceptionContinue(&e, "ProcessMessages()");
2764 } catch (...) {
2765 PrintExceptionContinue(NULL, "ProcessMessages()");
2768 if (!fRet) {
2769 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
2772 LOCK(cs_main);
2773 SendRejectsAndCheckIfBanned(pfrom, connman);
2775 return fMoreWork;
2778 class CompareInvMempoolOrder
2780 CTxMemPool *mp;
2781 public:
2782 CompareInvMempoolOrder(CTxMemPool *_mempool)
2784 mp = _mempool;
2787 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
2789 /* As std::make_heap produces a max-heap, we want the entries with the
2790 * fewest ancestors/highest fee to sort later. */
2791 return mp->CompareDepthAndScore(*b, *a);
2795 bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
2797 const Consensus::Params& consensusParams = Params().GetConsensus();
2799 // Don't send anything until the version handshake is complete
2800 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
2801 return true;
2803 // If we get here, the outgoing message serialization version is set and can't change.
2804 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2807 // Message: ping
2809 bool pingSend = false;
2810 if (pto->fPingQueued) {
2811 // RPC ping request by user
2812 pingSend = true;
2814 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
2815 // Ping automatically sent as a latency probe & keepalive.
2816 pingSend = true;
2818 if (pingSend) {
2819 uint64_t nonce = 0;
2820 while (nonce == 0) {
2821 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
2823 pto->fPingQueued = false;
2824 pto->nPingUsecStart = GetTimeMicros();
2825 if (pto->nVersion > BIP0031_VERSION) {
2826 pto->nPingNonceSent = nonce;
2827 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
2828 } else {
2829 // Peer is too old to support ping command with nonce, pong will never arrive.
2830 pto->nPingNonceSent = 0;
2831 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING));
2835 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2836 if (!lockMain)
2837 return true;
2839 if (SendRejectsAndCheckIfBanned(pto, connman))
2840 return true;
2841 CNodeState &state = *State(pto->GetId());
2843 // Address refresh broadcast
2844 int64_t nNow = GetTimeMicros();
2845 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
2846 AdvertiseLocal(pto);
2847 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
2851 // Message: addr
2853 if (pto->nNextAddrSend < nNow) {
2854 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
2855 std::vector<CAddress> vAddr;
2856 vAddr.reserve(pto->vAddrToSend.size());
2857 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2859 if (!pto->addrKnown.contains(addr.GetKey()))
2861 pto->addrKnown.insert(addr.GetKey());
2862 vAddr.push_back(addr);
2863 // receiver rejects addr messages larger than 1000
2864 if (vAddr.size() >= 1000)
2866 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2867 vAddr.clear();
2871 pto->vAddrToSend.clear();
2872 if (!vAddr.empty())
2873 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2874 // we only send the big addr message once
2875 if (pto->vAddrToSend.capacity() > 40)
2876 pto->vAddrToSend.shrink_to_fit();
2879 // Start block sync
2880 if (pindexBestHeader == NULL)
2881 pindexBestHeader = chainActive.Tip();
2882 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.
2883 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
2884 // Only actively request headers from a single peer, unless we're close to today.
2885 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2886 state.fSyncStarted = true;
2887 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
2888 nSyncStarted++;
2889 const CBlockIndex *pindexStart = pindexBestHeader;
2890 /* If possible, start at the block preceding the currently
2891 best known header. This ensures that we always get a
2892 non-empty list of headers back as long as the peer
2893 is up-to-date. With a non-empty response, we can initialise
2894 the peer's known best block. This wouldn't be possible
2895 if we requested starting at pindexBestHeader and
2896 got back an empty response. */
2897 if (pindexStart->pprev)
2898 pindexStart = pindexStart->pprev;
2899 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
2900 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
2904 // Resend wallet transactions that haven't gotten in a block yet
2905 // Except during reindex, importing and IBD, when old wallet
2906 // transactions become unconfirmed and spams other nodes.
2907 if (!fReindex && !fImporting && !IsInitialBlockDownload())
2909 GetMainSignals().Broadcast(nTimeBestReceived, &connman);
2913 // Try sending block announcements via headers
2916 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2917 // list of block hashes we're relaying, and our peer wants
2918 // headers announcements, then find the first header
2919 // not yet known to our peer but would connect, and send.
2920 // If no header would connect, or if we have too many
2921 // blocks, or if the peer doesn't want headers, just
2922 // add all to the inv queue.
2923 LOCK(pto->cs_inventory);
2924 std::vector<CBlock> vHeaders;
2925 bool fRevertToInv = ((!state.fPreferHeaders &&
2926 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
2927 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
2928 const CBlockIndex *pBestIndex = NULL; // last header queued for delivery
2929 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
2931 if (!fRevertToInv) {
2932 bool fFoundStartingHeader = false;
2933 // Try to find first header that our peer doesn't have, and
2934 // then send all headers past that one. If we come across any
2935 // headers that aren't on chainActive, give up.
2936 BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
2937 BlockMap::iterator mi = mapBlockIndex.find(hash);
2938 assert(mi != mapBlockIndex.end());
2939 const CBlockIndex *pindex = mi->second;
2940 if (chainActive[pindex->nHeight] != pindex) {
2941 // Bail out if we reorged away from this block
2942 fRevertToInv = true;
2943 break;
2945 if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
2946 // This means that the list of blocks to announce don't
2947 // connect to each other.
2948 // This shouldn't really be possible to hit during
2949 // regular operation (because reorgs should take us to
2950 // a chain that has some block not on the prior chain,
2951 // which should be caught by the prior check), but one
2952 // way this could happen is by using invalidateblock /
2953 // reconsiderblock repeatedly on the tip, causing it to
2954 // be added multiple times to vBlockHashesToAnnounce.
2955 // Robustly deal with this rare situation by reverting
2956 // to an inv.
2957 fRevertToInv = true;
2958 break;
2960 pBestIndex = pindex;
2961 if (fFoundStartingHeader) {
2962 // add this to the headers message
2963 vHeaders.push_back(pindex->GetBlockHeader());
2964 } else if (PeerHasHeader(&state, pindex)) {
2965 continue; // keep looking for the first new block
2966 } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
2967 // Peer doesn't have this header but they do have the prior one.
2968 // Start sending headers.
2969 fFoundStartingHeader = true;
2970 vHeaders.push_back(pindex->GetBlockHeader());
2971 } else {
2972 // Peer doesn't have this header or the prior one -- nothing will
2973 // connect, so bail out.
2974 fRevertToInv = true;
2975 break;
2979 if (!fRevertToInv && !vHeaders.empty()) {
2980 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
2981 // We only send up to 1 block as header-and-ids, as otherwise
2982 // probably means we're doing an initial-ish-sync or they're slow
2983 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
2984 vHeaders.front().GetHash().ToString(), pto->GetId());
2986 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
2988 bool fGotBlockFromCache = false;
2990 LOCK(cs_most_recent_block);
2991 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
2992 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
2993 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
2994 else {
2995 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
2996 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
2998 fGotBlockFromCache = true;
3001 if (!fGotBlockFromCache) {
3002 CBlock block;
3003 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3004 assert(ret);
3005 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3006 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3008 state.pindexBestHeaderSent = pBestIndex;
3009 } else if (state.fPreferHeaders) {
3010 if (vHeaders.size() > 1) {
3011 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3012 vHeaders.size(),
3013 vHeaders.front().GetHash().ToString(),
3014 vHeaders.back().GetHash().ToString(), pto->GetId());
3015 } else {
3016 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3017 vHeaders.front().GetHash().ToString(), pto->GetId());
3019 connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3020 state.pindexBestHeaderSent = pBestIndex;
3021 } else
3022 fRevertToInv = true;
3024 if (fRevertToInv) {
3025 // If falling back to using an inv, just try to inv the tip.
3026 // The last entry in vBlockHashesToAnnounce was our tip at some point
3027 // in the past.
3028 if (!pto->vBlockHashesToAnnounce.empty()) {
3029 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3030 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3031 assert(mi != mapBlockIndex.end());
3032 const CBlockIndex *pindex = mi->second;
3034 // Warn if we're announcing a block that is not on the main chain.
3035 // This should be very rare and could be optimized out.
3036 // Just log for now.
3037 if (chainActive[pindex->nHeight] != pindex) {
3038 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3039 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3042 // If the peer's chain has this block, don't inv it back.
3043 if (!PeerHasHeader(&state, pindex)) {
3044 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3045 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3046 pto->GetId(), hashToAnnounce.ToString());
3050 pto->vBlockHashesToAnnounce.clear();
3054 // Message: inventory
3056 std::vector<CInv> vInv;
3058 LOCK(pto->cs_inventory);
3059 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3061 // Add blocks
3062 BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
3063 vInv.push_back(CInv(MSG_BLOCK, hash));
3064 if (vInv.size() == MAX_INV_SZ) {
3065 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3066 vInv.clear();
3069 pto->vInventoryBlockToSend.clear();
3071 // Check whether periodic sends should happen
3072 bool fSendTrickle = pto->fWhitelisted;
3073 if (pto->nNextInvSend < nNow) {
3074 fSendTrickle = true;
3075 // Use half the delay for outbound peers, as there is less privacy concern for them.
3076 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3079 // Time to send but the peer has requested we not relay transactions.
3080 if (fSendTrickle) {
3081 LOCK(pto->cs_filter);
3082 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3085 // Respond to BIP35 mempool requests
3086 if (fSendTrickle && pto->fSendMempool) {
3087 auto vtxinfo = mempool.infoAll();
3088 pto->fSendMempool = false;
3089 CAmount filterrate = 0;
3091 LOCK(pto->cs_feeFilter);
3092 filterrate = pto->minFeeFilter;
3095 LOCK(pto->cs_filter);
3097 for (const auto& txinfo : vtxinfo) {
3098 const uint256& hash = txinfo.tx->GetHash();
3099 CInv inv(MSG_TX, hash);
3100 pto->setInventoryTxToSend.erase(hash);
3101 if (filterrate) {
3102 if (txinfo.feeRate.GetFeePerK() < filterrate)
3103 continue;
3105 if (pto->pfilter) {
3106 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3108 pto->filterInventoryKnown.insert(hash);
3109 vInv.push_back(inv);
3110 if (vInv.size() == MAX_INV_SZ) {
3111 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3112 vInv.clear();
3115 pto->timeLastMempoolReq = GetTime();
3118 // Determine transactions to relay
3119 if (fSendTrickle) {
3120 // Produce a vector with all candidates for sending
3121 std::vector<std::set<uint256>::iterator> vInvTx;
3122 vInvTx.reserve(pto->setInventoryTxToSend.size());
3123 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3124 vInvTx.push_back(it);
3126 CAmount filterrate = 0;
3128 LOCK(pto->cs_feeFilter);
3129 filterrate = pto->minFeeFilter;
3131 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3132 // A heap is used so that not all items need sorting if only a few are being sent.
3133 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3134 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3135 // No reason to drain out at many times the network's capacity,
3136 // especially since we have many peers and some will draw much shorter delays.
3137 unsigned int nRelayedTransactions = 0;
3138 LOCK(pto->cs_filter);
3139 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3140 // Fetch the top element from the heap
3141 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3142 std::set<uint256>::iterator it = vInvTx.back();
3143 vInvTx.pop_back();
3144 uint256 hash = *it;
3145 // Remove it from the to-be-sent set
3146 pto->setInventoryTxToSend.erase(it);
3147 // Check if not in the filter already
3148 if (pto->filterInventoryKnown.contains(hash)) {
3149 continue;
3151 // Not in the mempool anymore? don't bother sending it.
3152 auto txinfo = mempool.info(hash);
3153 if (!txinfo.tx) {
3154 continue;
3156 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3157 continue;
3159 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3160 // Send
3161 vInv.push_back(CInv(MSG_TX, hash));
3162 nRelayedTransactions++;
3164 // Expire old relay messages
3165 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3167 mapRelay.erase(vRelayExpiration.front().second);
3168 vRelayExpiration.pop_front();
3171 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3172 if (ret.second) {
3173 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3176 if (vInv.size() == MAX_INV_SZ) {
3177 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3178 vInv.clear();
3180 pto->filterInventoryKnown.insert(hash);
3184 if (!vInv.empty())
3185 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3187 // Detect whether we're stalling
3188 nNow = GetTimeMicros();
3189 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3190 // Stalling only triggers when the block download window cannot move. During normal steady state,
3191 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3192 // should only happen during initial block download.
3193 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3194 pto->fDisconnect = true;
3195 return true;
3197 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3198 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3199 // We compensate for other peers to prevent killing off peers due to our own downstream link
3200 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3201 // to unreasonably increase our timeout.
3202 if (state.vBlocksInFlight.size() > 0) {
3203 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3204 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3205 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3206 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3207 pto->fDisconnect = true;
3208 return true;
3211 // Check for headers sync timeouts
3212 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3213 // Detect whether this is a stalling initial-headers-sync peer
3214 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3215 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3216 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3217 // and we have others we could be using instead.
3218 // Note: If all our peers are inbound, then we won't
3219 // disconnect our sync peer for stalling; we have bigger
3220 // problems if we can't get any outbound peers.
3221 if (!pto->fWhitelisted) {
3222 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3223 pto->fDisconnect = true;
3224 return true;
3225 } else {
3226 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3227 // Reset the headers sync state so that we have a
3228 // chance to try downloading from a different peer.
3229 // Note: this will also result in at least one more
3230 // getheaders message to be sent to
3231 // this peer (eventually).
3232 state.fSyncStarted = false;
3233 nSyncStarted--;
3234 state.nHeadersSyncTimeout = 0;
3237 } else {
3238 // After we've caught up once, reset the timeout so we can't trigger
3239 // disconnect later.
3240 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3246 // Message: getdata (blocks)
3248 std::vector<CInv> vGetData;
3249 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3250 std::vector<const CBlockIndex*> vToDownload;
3251 NodeId staller = -1;
3252 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3253 BOOST_FOREACH(const CBlockIndex *pindex, vToDownload) {
3254 uint32_t nFetchFlags = GetFetchFlags(pto);
3255 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3256 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3257 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3258 pindex->nHeight, pto->GetId());
3260 if (state.nBlocksInFlight == 0 && staller != -1) {
3261 if (State(staller)->nStallingSince == 0) {
3262 State(staller)->nStallingSince = nNow;
3263 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3269 // Message: getdata (non-blocks)
3271 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3273 const CInv& inv = (*pto->mapAskFor.begin()).second;
3274 if (!AlreadyHave(inv))
3276 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3277 vGetData.push_back(inv);
3278 if (vGetData.size() >= 1000)
3280 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3281 vGetData.clear();
3283 } else {
3284 //If we're not going to ask, don't expect a response.
3285 pto->setAskFor.erase(inv.hash);
3287 pto->mapAskFor.erase(pto->mapAskFor.begin());
3289 if (!vGetData.empty())
3290 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3293 // Message: feefilter
3295 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3296 if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3297 !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3298 CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3299 int64_t timeNow = GetTimeMicros();
3300 if (timeNow > pto->nextSendTimeFeeFilter) {
3301 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3302 static FeeFilterRounder filterRounder(default_feerate);
3303 CAmount filterToSend = filterRounder.round(currentFilter);
3304 // We always have a fee filter of at least minRelayTxFee
3305 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3306 if (filterToSend != pto->lastSentFeeFilter) {
3307 connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3308 pto->lastSentFeeFilter = filterToSend;
3310 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3312 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3313 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3314 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3315 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3316 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3320 return true;
3323 class CNetProcessingCleanup
3325 public:
3326 CNetProcessingCleanup() {}
3327 ~CNetProcessingCleanup() {
3328 // orphan transactions
3329 mapOrphanTransactions.clear();
3330 mapOrphanTransactionsByPrev.clear();
3332 } instance_of_cnetprocessingcleanup;