Merge #10502: scripted-diff: Remove BOOST_FOREACH, Q_FOREACH and PAIRTYPE
[bitcoinplatinum.git] / src / net_processing.cpp
blobb9357440e951ad5eee674dea156db2bdf1eb348e
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 #if defined(NDEBUG)
34 # error "Bitcoin cannot be compiled without assertions."
35 #endif
37 std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
39 struct IteratorComparator
41 template<typename I>
42 bool operator()(const I& a, const I& b)
44 return &(*a) < &(*b);
48 struct COrphanTx {
49 // When modifying, adapt the copy of this definition in tests/DoS_tests.
50 CTransactionRef tx;
51 NodeId fromPeer;
52 int64_t nTimeExpire;
54 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
55 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
56 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
58 static size_t vExtraTxnForCompactIt = 0;
59 static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
61 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
63 // Internal stuff
64 namespace {
65 /** Number of nodes with fSyncStarted. */
66 int nSyncStarted = 0;
68 /**
69 * Sources of received blocks, saved to be able to send them reject
70 * messages or ban them when processing happens afterwards. Protected by
71 * cs_main.
72 * Set mapBlockSource[hash].second to false if the node should not be
73 * punished if the block is invalid.
75 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
77 /**
78 * Filter for transactions that were recently rejected by
79 * AcceptToMemoryPool. These are not rerequested until the chain tip
80 * changes, at which point the entire filter is reset. Protected by
81 * cs_main.
83 * Without this filter we'd be re-requesting txs from each of our peers,
84 * increasing bandwidth consumption considerably. For instance, with 100
85 * peers, half of which relay a tx we don't accept, that might be a 50x
86 * bandwidth increase. A flooding attacker attempting to roll-over the
87 * filter using minimum-sized, 60byte, transactions might manage to send
88 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
89 * two minute window to send invs to us.
91 * Decreasing the false positive rate is fairly cheap, so we pick one in a
92 * million to make it highly unlikely for users to have issues with this
93 * filter.
95 * Memory used: 1.3 MB
97 std::unique_ptr<CRollingBloomFilter> recentRejects;
98 uint256 hashRecentRejectsChainTip;
100 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
101 struct QueuedBlock {
102 uint256 hash;
103 const CBlockIndex* pindex; //!< Optional.
104 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
105 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
107 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
109 /** Stack of nodes which we have set to announce using compact blocks */
110 std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
112 /** Number of preferable block download peers. */
113 int nPreferredDownload = 0;
115 /** Number of peers from which we're downloading blocks. */
116 int nPeersWithValidatedDownloads = 0;
118 /** Relay map, protected by cs_main. */
119 typedef std::map<uint256, CTransactionRef> MapRelay;
120 MapRelay mapRelay;
121 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
122 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
123 } // anon namespace
125 //////////////////////////////////////////////////////////////////////////////
127 // Registration of network node signals.
130 namespace {
132 struct CBlockReject {
133 unsigned char chRejectCode;
134 std::string strRejectReason;
135 uint256 hashBlock;
139 * Maintain validation-specific state about nodes, protected by cs_main, instead
140 * by CNode's own locks. This simplifies asynchronous operation, where
141 * processing of incoming data is done after the ProcessMessage call returns,
142 * and we're no longer holding the node's locks.
144 struct CNodeState {
145 //! The peer's address
146 const CService address;
147 //! Whether we have a fully established connection.
148 bool fCurrentlyConnected;
149 //! Accumulated misbehaviour score for this peer.
150 int nMisbehavior;
151 //! Whether this peer should be disconnected and banned (unless whitelisted).
152 bool fShouldBan;
153 //! String name of this peer (debugging/logging purposes).
154 const std::string name;
155 //! List of asynchronously-determined block rejections to notify this peer about.
156 std::vector<CBlockReject> rejects;
157 //! The best known block we know this peer has announced.
158 const CBlockIndex *pindexBestKnownBlock;
159 //! The hash of the last unknown block this peer has announced.
160 uint256 hashLastUnknownBlock;
161 //! The last full block we both have.
162 const CBlockIndex *pindexLastCommonBlock;
163 //! The best header we have sent our peer.
164 const CBlockIndex *pindexBestHeaderSent;
165 //! Length of current-streak of unconnecting headers announcements
166 int nUnconnectingHeaders;
167 //! Whether we've started headers synchronization with this peer.
168 bool fSyncStarted;
169 //! When to potentially disconnect peer for stalling headers download
170 int64_t nHeadersSyncTimeout;
171 //! Since when we're stalling block download progress (in microseconds), or 0.
172 int64_t nStallingSince;
173 std::list<QueuedBlock> vBlocksInFlight;
174 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
175 int64_t nDownloadingSince;
176 int nBlocksInFlight;
177 int nBlocksInFlightValidHeaders;
178 //! Whether we consider this a preferred download peer.
179 bool fPreferredDownload;
180 //! Whether this peer wants invs or headers (when possible) for block announcements.
181 bool fPreferHeaders;
182 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
183 bool fPreferHeaderAndIDs;
185 * Whether this peer will send us cmpctblocks if we request them.
186 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
187 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
189 bool fProvidesHeaderAndIDs;
190 //! Whether this peer can give us witnesses
191 bool fHaveWitness;
192 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
193 bool fWantsCmpctWitness;
195 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
196 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
198 bool fSupportsDesiredCmpctVersion;
200 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
201 fCurrentlyConnected = false;
202 nMisbehavior = 0;
203 fShouldBan = false;
204 pindexBestKnownBlock = NULL;
205 hashLastUnknownBlock.SetNull();
206 pindexLastCommonBlock = NULL;
207 pindexBestHeaderSent = NULL;
208 nUnconnectingHeaders = 0;
209 fSyncStarted = false;
210 nHeadersSyncTimeout = 0;
211 nStallingSince = 0;
212 nDownloadingSince = 0;
213 nBlocksInFlight = 0;
214 nBlocksInFlightValidHeaders = 0;
215 fPreferredDownload = false;
216 fPreferHeaders = false;
217 fPreferHeaderAndIDs = false;
218 fProvidesHeaderAndIDs = false;
219 fHaveWitness = false;
220 fWantsCmpctWitness = false;
221 fSupportsDesiredCmpctVersion = false;
225 /** Map maintaining per-node state. Requires cs_main. */
226 std::map<NodeId, CNodeState> mapNodeState;
228 // Requires cs_main.
229 CNodeState *State(NodeId pnode) {
230 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
231 if (it == mapNodeState.end())
232 return NULL;
233 return &it->second;
236 void UpdatePreferredDownload(CNode* node, CNodeState* state)
238 nPreferredDownload -= state->fPreferredDownload;
240 // Whether this node should be marked as a preferred download node.
241 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
243 nPreferredDownload += state->fPreferredDownload;
246 void PushNodeVersion(CNode *pnode, CConnman& connman, int64_t nTime)
248 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
249 uint64_t nonce = pnode->GetLocalNonce();
250 int nNodeStartingHeight = pnode->GetMyStartingHeight();
251 NodeId nodeid = pnode->GetId();
252 CAddress addr = pnode->addr;
254 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
255 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
257 connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
258 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
260 if (fLogIPs) {
261 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);
262 } else {
263 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
267 void InitializeNode(CNode *pnode, CConnman& connman) {
268 CAddress addr = pnode->addr;
269 std::string addrName = pnode->GetAddrName();
270 NodeId nodeid = pnode->GetId();
272 LOCK(cs_main);
273 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
275 if(!pnode->fInbound)
276 PushNodeVersion(pnode, connman, GetTime());
279 void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
280 fUpdateConnectionTime = false;
281 LOCK(cs_main);
282 CNodeState *state = State(nodeid);
284 if (state->fSyncStarted)
285 nSyncStarted--;
287 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
288 fUpdateConnectionTime = true;
291 for (const QueuedBlock& entry : state->vBlocksInFlight) {
292 mapBlocksInFlight.erase(entry.hash);
294 EraseOrphansFor(nodeid);
295 nPreferredDownload -= state->fPreferredDownload;
296 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
297 assert(nPeersWithValidatedDownloads >= 0);
299 mapNodeState.erase(nodeid);
301 if (mapNodeState.empty()) {
302 // Do a consistency check after the last peer is removed.
303 assert(mapBlocksInFlight.empty());
304 assert(nPreferredDownload == 0);
305 assert(nPeersWithValidatedDownloads == 0);
307 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
310 // Requires cs_main.
311 // Returns a bool indicating whether we requested this block.
312 // Also used if a block was /not/ received and timed out or started with another peer
313 bool MarkBlockAsReceived(const uint256& hash) {
314 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
315 if (itInFlight != mapBlocksInFlight.end()) {
316 CNodeState *state = State(itInFlight->second.first);
317 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
318 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
319 // Last validated block on the queue was received.
320 nPeersWithValidatedDownloads--;
322 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
323 // First block on the queue was received, update the start download time for the next one
324 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
326 state->vBlocksInFlight.erase(itInFlight->second.second);
327 state->nBlocksInFlight--;
328 state->nStallingSince = 0;
329 mapBlocksInFlight.erase(itInFlight);
330 return true;
332 return false;
335 // Requires cs_main.
336 // returns false, still setting pit, if the block was already in flight from the same peer
337 // pit will only be valid as long as the same cs_main lock is being held
338 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = NULL, std::list<QueuedBlock>::iterator** pit = NULL) {
339 CNodeState *state = State(nodeid);
340 assert(state != NULL);
342 // Short-circuit most stuff in case its from the same node
343 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
344 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
345 *pit = &itInFlight->second.second;
346 return false;
349 // Make sure it's not listed somewhere already.
350 MarkBlockAsReceived(hash);
352 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
353 {hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)});
354 state->nBlocksInFlight++;
355 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
356 if (state->nBlocksInFlight == 1) {
357 // We're starting a block download (batch) from this peer.
358 state->nDownloadingSince = GetTimeMicros();
360 if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
361 nPeersWithValidatedDownloads++;
363 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
364 if (pit)
365 *pit = &itInFlight->second.second;
366 return true;
369 /** Check whether the last unknown block a peer advertised is not yet known. */
370 void ProcessBlockAvailability(NodeId nodeid) {
371 CNodeState *state = State(nodeid);
372 assert(state != NULL);
374 if (!state->hashLastUnknownBlock.IsNull()) {
375 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
376 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
377 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
378 state->pindexBestKnownBlock = itOld->second;
379 state->hashLastUnknownBlock.SetNull();
384 /** Update tracking information about which blocks a peer is assumed to have. */
385 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
386 CNodeState *state = State(nodeid);
387 assert(state != NULL);
389 ProcessBlockAvailability(nodeid);
391 BlockMap::iterator it = mapBlockIndex.find(hash);
392 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
393 // An actually better block was announced.
394 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
395 state->pindexBestKnownBlock = it->second;
396 } else {
397 // An unknown block was announced; just assume that the latest one is the best one.
398 state->hashLastUnknownBlock = hash;
402 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman& connman) {
403 AssertLockHeld(cs_main);
404 CNodeState* nodestate = State(nodeid);
405 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
406 // Never ask from peers who can't provide witnesses.
407 return;
409 if (nodestate->fProvidesHeaderAndIDs) {
410 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
411 if (*it == nodeid) {
412 lNodesAnnouncingHeaderAndIDs.erase(it);
413 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
414 return;
417 connman.ForNode(nodeid, [&connman](CNode* pfrom){
418 bool fAnnounceUsingCMPCTBLOCK = false;
419 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
420 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
421 // As per BIP152, we only get 3 of our peers to announce
422 // blocks using compact encodings.
423 connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [&connman, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion](CNode* pnodeStop){
424 connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
425 return true;
427 lNodesAnnouncingHeaderAndIDs.pop_front();
429 fAnnounceUsingCMPCTBLOCK = true;
430 connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
431 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
432 return true;
437 // Requires cs_main
438 bool CanDirectFetch(const Consensus::Params &consensusParams)
440 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
443 // Requires cs_main
444 bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
446 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
447 return true;
448 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
449 return true;
450 return false;
453 /** Find the last common ancestor two blocks have.
454 * Both pa and pb must be non-NULL. */
455 const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
456 if (pa->nHeight > pb->nHeight) {
457 pa = pa->GetAncestor(pb->nHeight);
458 } else if (pb->nHeight > pa->nHeight) {
459 pb = pb->GetAncestor(pa->nHeight);
462 while (pa != pb && pa && pb) {
463 pa = pa->pprev;
464 pb = pb->pprev;
467 // Eventually all chain branches meet at the genesis block.
468 assert(pa == pb);
469 return pa;
472 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
473 * at most count entries. */
474 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
475 if (count == 0)
476 return;
478 vBlocks.reserve(vBlocks.size() + count);
479 CNodeState *state = State(nodeid);
480 assert(state != NULL);
482 // Make sure pindexBestKnownBlock is up to date, we'll need it.
483 ProcessBlockAvailability(nodeid);
485 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < UintToArith256(consensusParams.nMinimumChainWork)) {
486 // This peer has nothing interesting.
487 return;
490 if (state->pindexLastCommonBlock == NULL) {
491 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
492 // Guessing wrong in either direction is not a problem.
493 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
496 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
497 // of its current tip anymore. Go back enough to fix that.
498 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
499 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
500 return;
502 std::vector<const CBlockIndex*> vToFetch;
503 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
504 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
505 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
506 // download that next block if the window were 1 larger.
507 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
508 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
509 NodeId waitingfor = -1;
510 while (pindexWalk->nHeight < nMaxHeight) {
511 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
512 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
513 // as iterating over ~100 CBlockIndex* entries anyway.
514 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
515 vToFetch.resize(nToFetch);
516 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
517 vToFetch[nToFetch - 1] = pindexWalk;
518 for (unsigned int i = nToFetch - 1; i > 0; i--) {
519 vToFetch[i - 1] = vToFetch[i]->pprev;
522 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
523 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
524 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
525 // already part of our chain (and therefore don't need it even if pruned).
526 for (const CBlockIndex* pindex : vToFetch) {
527 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
528 // We consider the chain that this peer is on invalid.
529 return;
531 if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
532 // We wouldn't download this block or its descendants from this peer.
533 return;
535 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
536 if (pindex->nChainTx)
537 state->pindexLastCommonBlock = pindex;
538 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
539 // The block is not already downloaded, and not yet in flight.
540 if (pindex->nHeight > nWindowEnd) {
541 // We reached the end of the window.
542 if (vBlocks.size() == 0 && waitingfor != nodeid) {
543 // We aren't able to fetch anything, but we would be if the download window was one larger.
544 nodeStaller = waitingfor;
546 return;
548 vBlocks.push_back(pindex);
549 if (vBlocks.size() == count) {
550 return;
552 } else if (waitingfor == -1) {
553 // This is the first already-in-flight block.
554 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
560 } // anon namespace
562 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
563 LOCK(cs_main);
564 CNodeState *state = State(nodeid);
565 if (state == NULL)
566 return false;
567 stats.nMisbehavior = state->nMisbehavior;
568 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
569 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
570 for (const QueuedBlock& queue : state->vBlocksInFlight) {
571 if (queue.pindex)
572 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
574 return true;
577 void RegisterNodeSignals(CNodeSignals& nodeSignals)
579 nodeSignals.ProcessMessages.connect(&ProcessMessages);
580 nodeSignals.SendMessages.connect(&SendMessages);
581 nodeSignals.InitializeNode.connect(&InitializeNode);
582 nodeSignals.FinalizeNode.connect(&FinalizeNode);
585 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
587 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
588 nodeSignals.SendMessages.disconnect(&SendMessages);
589 nodeSignals.InitializeNode.disconnect(&InitializeNode);
590 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
593 //////////////////////////////////////////////////////////////////////////////
595 // mapOrphanTransactions
598 void AddToCompactExtraTransactions(const CTransactionRef& tx)
600 size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
601 if (max_extra_txn <= 0)
602 return;
603 if (!vExtraTxnForCompact.size())
604 vExtraTxnForCompact.resize(max_extra_txn);
605 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
606 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
609 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
611 const uint256& hash = tx->GetHash();
612 if (mapOrphanTransactions.count(hash))
613 return false;
615 // Ignore big transactions, to avoid a
616 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
617 // large transaction with a missing parent then we assume
618 // it will rebroadcast it later, after the parent transaction(s)
619 // have been mined or received.
620 // 100 orphans, each of which is at most 99,999 bytes big is
621 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
622 unsigned int sz = GetTransactionWeight(*tx);
623 if (sz >= MAX_STANDARD_TX_WEIGHT)
625 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
626 return false;
629 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
630 assert(ret.second);
631 for (const CTxIn& txin : tx->vin) {
632 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
635 AddToCompactExtraTransactions(tx);
637 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
638 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
639 return true;
642 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
644 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
645 if (it == mapOrphanTransactions.end())
646 return 0;
647 for (const CTxIn& txin : it->second.tx->vin)
649 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
650 if (itPrev == mapOrphanTransactionsByPrev.end())
651 continue;
652 itPrev->second.erase(it);
653 if (itPrev->second.empty())
654 mapOrphanTransactionsByPrev.erase(itPrev);
656 mapOrphanTransactions.erase(it);
657 return 1;
660 void EraseOrphansFor(NodeId peer)
662 int nErased = 0;
663 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
664 while (iter != mapOrphanTransactions.end())
666 std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
667 if (maybeErase->second.fromPeer == peer)
669 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
672 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
676 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
678 unsigned int nEvicted = 0;
679 static int64_t nNextSweep;
680 int64_t nNow = GetTime();
681 if (nNextSweep <= nNow) {
682 // Sweep out expired orphan pool entries:
683 int nErased = 0;
684 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
685 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
686 while (iter != mapOrphanTransactions.end())
688 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
689 if (maybeErase->second.nTimeExpire <= nNow) {
690 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
691 } else {
692 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
695 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
696 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
697 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
699 while (mapOrphanTransactions.size() > nMaxOrphans)
701 // Evict a random orphan:
702 uint256 randomhash = GetRandHash();
703 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
704 if (it == mapOrphanTransactions.end())
705 it = mapOrphanTransactions.begin();
706 EraseOrphanTx(it->first);
707 ++nEvicted;
709 return nEvicted;
712 // Requires cs_main.
713 void Misbehaving(NodeId pnode, int howmuch)
715 if (howmuch == 0)
716 return;
718 CNodeState *state = State(pnode);
719 if (state == NULL)
720 return;
722 state->nMisbehavior += howmuch;
723 int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
724 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
726 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
727 state->fShouldBan = true;
728 } else
729 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
739 //////////////////////////////////////////////////////////////////////////////
741 // blockchain -> download logic notification
744 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
745 // Initialize global variables that cannot be constructed at startup.
746 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
749 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
750 LOCK(cs_main);
752 std::vector<uint256> vOrphanErase;
754 for (const CTransactionRef& ptx : pblock->vtx) {
755 const CTransaction& tx = *ptx;
757 // Which orphan pool entries must we evict?
758 for (const auto& txin : tx.vin) {
759 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
760 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
761 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
762 const CTransaction& orphanTx = *(*mi)->second.tx;
763 const uint256& orphanHash = orphanTx.GetHash();
764 vOrphanErase.push_back(orphanHash);
769 // Erase orphan transactions include or precluded by this block
770 if (vOrphanErase.size()) {
771 int nErased = 0;
772 for (uint256 &orphanHash : vOrphanErase) {
773 nErased += EraseOrphanTx(orphanHash);
775 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
779 // All of the following cache a recent block, and are protected by cs_most_recent_block
780 static CCriticalSection cs_most_recent_block;
781 static std::shared_ptr<const CBlock> most_recent_block;
782 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
783 static uint256 most_recent_block_hash;
784 static bool fWitnessesPresentInMostRecentCompactBlock;
786 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
787 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
788 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
790 LOCK(cs_main);
792 static int nHighestFastAnnounce = 0;
793 if (pindex->nHeight <= nHighestFastAnnounce)
794 return;
795 nHighestFastAnnounce = pindex->nHeight;
797 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
798 uint256 hashBlock(pblock->GetHash());
801 LOCK(cs_most_recent_block);
802 most_recent_block_hash = hashBlock;
803 most_recent_block = pblock;
804 most_recent_compact_block = pcmpctblock;
805 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
808 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
809 // TODO: Avoid the repeated-serialization here
810 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
811 return;
812 ProcessBlockAvailability(pnode->GetId());
813 CNodeState &state = *State(pnode->GetId());
814 // If the peer has, or we announced to them the previous block already,
815 // but we don't think they have this one, go ahead and announce it
816 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
817 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
819 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
820 hashBlock.ToString(), pnode->GetId());
821 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
822 state.pindexBestHeaderSent = pindex;
827 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
828 const int nNewHeight = pindexNew->nHeight;
829 connman->SetBestHeight(nNewHeight);
831 if (!fInitialDownload) {
832 // Find the hashes of all blocks that weren't previously in the best chain.
833 std::vector<uint256> vHashes;
834 const CBlockIndex *pindexToAnnounce = pindexNew;
835 while (pindexToAnnounce != pindexFork) {
836 vHashes.push_back(pindexToAnnounce->GetBlockHash());
837 pindexToAnnounce = pindexToAnnounce->pprev;
838 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
839 // Limit announcements in case of a huge reorganization.
840 // Rely on the peer's synchronization mechanism in that case.
841 break;
844 // Relay inventory, but don't relay old inventory during initial block download.
845 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
846 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
847 BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
848 pnode->PushBlockHash(hash);
852 connman->WakeMessageHandler();
855 nTimeBestReceived = GetTime();
858 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
859 LOCK(cs_main);
861 const uint256 hash(block.GetHash());
862 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
864 int nDoS = 0;
865 if (state.IsInvalid(nDoS)) {
866 // Don't send reject message with code 0 or an internal reject code.
867 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
868 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
869 State(it->second.first)->rejects.push_back(reject);
870 if (nDoS > 0 && it->second.second)
871 Misbehaving(it->second.first, nDoS);
874 // Check that:
875 // 1. The block is valid
876 // 2. We're not in initial block download
877 // 3. This is currently the best block we're aware of. We haven't updated
878 // the tip yet so we have no way to check this directly here. Instead we
879 // just check that there are currently no other blocks in flight.
880 else if (state.IsValid() &&
881 !IsInitialBlockDownload() &&
882 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
883 if (it != mapBlockSource.end()) {
884 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, *connman);
887 if (it != mapBlockSource.end())
888 mapBlockSource.erase(it);
891 //////////////////////////////////////////////////////////////////////////////
893 // Messages
897 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
899 switch (inv.type)
901 case MSG_TX:
902 case MSG_WITNESS_TX:
904 assert(recentRejects);
905 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
907 // If the chain tip has changed previously rejected transactions
908 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
909 // or a double-spend. Reset the rejects filter and give those
910 // txs a second chance.
911 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
912 recentRejects->reset();
915 return recentRejects->contains(inv.hash) ||
916 mempool.exists(inv.hash) ||
917 mapOrphanTransactions.count(inv.hash) ||
918 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
919 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
921 case MSG_BLOCK:
922 case MSG_WITNESS_BLOCK:
923 return mapBlockIndex.count(inv.hash);
925 // Don't know what it is, just say we already got one
926 return true;
929 static void RelayTransaction(const CTransaction& tx, CConnman& connman)
931 CInv inv(MSG_TX, tx.GetHash());
932 connman.ForEachNode([&inv](CNode* pnode)
934 pnode->PushInventory(inv);
938 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman& connman)
940 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
942 // Relay to a limited number of other nodes
943 // Use deterministic randomness to send to the same nodes for 24 hours
944 // at a time so the addrKnowns of the chosen nodes prevent repeats
945 uint64_t hashAddr = addr.GetHash();
946 const CSipHasher hasher = connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
947 FastRandomContext insecure_rand;
949 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
950 assert(nRelayNodes <= best.size());
952 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
953 if (pnode->nVersion >= CADDR_TIME_VERSION) {
954 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
955 for (unsigned int i = 0; i < nRelayNodes; i++) {
956 if (hashKey > best[i].first) {
957 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
958 best[i] = std::make_pair(hashKey, pnode);
959 break;
965 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
966 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
967 best[i].second->PushAddress(addr, insecure_rand);
971 connman.ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
974 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
976 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
977 std::vector<CInv> vNotFound;
978 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
979 LOCK(cs_main);
981 while (it != pfrom->vRecvGetData.end()) {
982 // Don't bother if send buffer is too full to respond anyway
983 if (pfrom->fPauseSend)
984 break;
986 const CInv &inv = *it;
988 if (interruptMsgProc)
989 return;
991 it++;
993 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
995 bool send = false;
996 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
997 std::shared_ptr<const CBlock> a_recent_block;
998 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
999 bool fWitnessesPresentInARecentCompactBlock;
1001 LOCK(cs_most_recent_block);
1002 a_recent_block = most_recent_block;
1003 a_recent_compact_block = most_recent_compact_block;
1004 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1006 if (mi != mapBlockIndex.end())
1008 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1009 mi->second->IsValid(BLOCK_VALID_TREE)) {
1010 // If we have the block and all of its parents, but have not yet validated it,
1011 // we might be in the middle of connecting it (ie in the unlock of cs_main
1012 // before ActivateBestChain but after AcceptBlock).
1013 // In this case, we need to run ActivateBestChain prior to checking the relay
1014 // conditions below.
1015 CValidationState dummy;
1016 ActivateBestChain(dummy, Params(), a_recent_block);
1018 if (chainActive.Contains(mi->second)) {
1019 send = true;
1020 } else {
1021 static const int nOneMonth = 30 * 24 * 60 * 60;
1022 // To prevent fingerprinting attacks, only send blocks outside of the active
1023 // chain if they are valid, and no more than a month older (both in time, and in
1024 // best equivalent proof of work) than the best header chain we know about.
1025 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
1026 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
1027 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
1028 if (!send) {
1029 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1033 // disconnect node in case we have reached the outbound limit for serving historical blocks
1034 // never disconnect whitelisted nodes
1035 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
1036 if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1038 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1040 //disconnect node
1041 pfrom->fDisconnect = true;
1042 send = false;
1044 // Pruned nodes may have deleted the block, so check whether
1045 // it's available before trying to send.
1046 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1048 std::shared_ptr<const CBlock> pblock;
1049 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1050 pblock = a_recent_block;
1051 } else {
1052 // Send block from disk
1053 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1054 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1055 assert(!"cannot load block from disk");
1056 pblock = pblockRead;
1058 if (inv.type == MSG_BLOCK)
1059 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1060 else if (inv.type == MSG_WITNESS_BLOCK)
1061 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1062 else if (inv.type == MSG_FILTERED_BLOCK)
1064 bool sendMerkleBlock = false;
1065 CMerkleBlock merkleBlock;
1067 LOCK(pfrom->cs_filter);
1068 if (pfrom->pfilter) {
1069 sendMerkleBlock = true;
1070 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1073 if (sendMerkleBlock) {
1074 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1075 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1076 // This avoids hurting performance by pointlessly requiring a round-trip
1077 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1078 // they must either disconnect and retry or request the full block.
1079 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1080 // however we MUST always provide at least what the remote peer needs
1081 typedef std::pair<unsigned int, uint256> PairType;
1082 for (PairType& pair : merkleBlock.vMatchedTxn)
1083 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1085 // else
1086 // no response
1088 else if (inv.type == MSG_CMPCT_BLOCK)
1090 // If a peer is asking for old blocks, we're almost guaranteed
1091 // they won't have a useful mempool to match against a compact block,
1092 // and we don't feel like constructing the object for them, so
1093 // instead we respond with the full, non-compact block.
1094 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1095 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1096 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1097 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1098 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1099 } else {
1100 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1101 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1103 } else {
1104 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1108 // Trigger the peer node to send a getblocks request for the next batch of inventory
1109 if (inv.hash == pfrom->hashContinue)
1111 // Bypass PushInventory, this must send even if redundant,
1112 // and we want it right after the last block so they don't
1113 // wait for other stuff first.
1114 std::vector<CInv> vInv;
1115 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1116 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1117 pfrom->hashContinue.SetNull();
1121 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1123 // Send stream from relay memory
1124 bool push = false;
1125 auto mi = mapRelay.find(inv.hash);
1126 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1127 if (mi != mapRelay.end()) {
1128 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1129 push = true;
1130 } else if (pfrom->timeLastMempoolReq) {
1131 auto txinfo = mempool.info(inv.hash);
1132 // To protect privacy, do not answer getdata using the mempool when
1133 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1134 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1135 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1136 push = true;
1139 if (!push) {
1140 vNotFound.push_back(inv);
1144 // Track requests for our stuff.
1145 GetMainSignals().Inventory(inv.hash);
1147 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1148 break;
1152 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1154 if (!vNotFound.empty()) {
1155 // Let the peer know that we didn't find what it asked for, so it doesn't
1156 // have to wait around forever. Currently only SPV clients actually care
1157 // about this message: it's needed when they are recursively walking the
1158 // dependencies of relevant unconfirmed transactions. SPV clients want to
1159 // do that because they want to know about (and store and rebroadcast and
1160 // risk analyze) the dependencies of transactions relevant to them, without
1161 // having to download the entire memory pool.
1162 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1166 uint32_t GetFetchFlags(CNode* pfrom) {
1167 uint32_t nFetchFlags = 0;
1168 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1169 nFetchFlags |= MSG_WITNESS_FLAG;
1171 return nFetchFlags;
1174 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman& connman) {
1175 BlockTransactions resp(req);
1176 for (size_t i = 0; i < req.indexes.size(); i++) {
1177 if (req.indexes[i] >= block.vtx.size()) {
1178 LOCK(cs_main);
1179 Misbehaving(pfrom->GetId(), 100);
1180 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1181 return;
1183 resp.txn[i] = block.vtx[req.indexes[i]];
1185 LOCK(cs_main);
1186 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1187 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1188 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1191 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
1193 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1194 if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
1196 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1197 return true;
1201 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1202 (strCommand == NetMsgType::FILTERLOAD ||
1203 strCommand == NetMsgType::FILTERADD))
1205 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1206 LOCK(cs_main);
1207 Misbehaving(pfrom->GetId(), 100);
1208 return false;
1209 } else {
1210 pfrom->fDisconnect = true;
1211 return false;
1215 if (strCommand == NetMsgType::REJECT)
1217 if (LogAcceptCategory(BCLog::NET)) {
1218 try {
1219 std::string strMsg; unsigned char ccode; std::string strReason;
1220 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1222 std::ostringstream ss;
1223 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1225 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1227 uint256 hash;
1228 vRecv >> hash;
1229 ss << ": hash " << hash.ToString();
1231 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1232 } catch (const std::ios_base::failure&) {
1233 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1234 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1239 else if (strCommand == NetMsgType::VERSION)
1241 // Each connection can only send one version message
1242 if (pfrom->nVersion != 0)
1244 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1245 LOCK(cs_main);
1246 Misbehaving(pfrom->GetId(), 1);
1247 return false;
1250 int64_t nTime;
1251 CAddress addrMe;
1252 CAddress addrFrom;
1253 uint64_t nNonce = 1;
1254 uint64_t nServiceInt;
1255 ServiceFlags nServices;
1256 int nVersion;
1257 int nSendVersion;
1258 std::string strSubVer;
1259 std::string cleanSubVer;
1260 int nStartingHeight = -1;
1261 bool fRelay = true;
1263 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1264 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1265 nServices = ServiceFlags(nServiceInt);
1266 if (!pfrom->fInbound)
1268 connman.SetServices(pfrom->addr, nServices);
1270 if (pfrom->nServicesExpected & ~nServices)
1272 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, pfrom->nServicesExpected);
1273 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1274 strprintf("Expected to offer services %08x", pfrom->nServicesExpected)));
1275 pfrom->fDisconnect = true;
1276 return false;
1279 if (nVersion < MIN_PEER_PROTO_VERSION)
1281 // disconnect from peers older than this proto version
1282 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1283 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1284 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1285 pfrom->fDisconnect = true;
1286 return false;
1289 if (nVersion == 10300)
1290 nVersion = 300;
1291 if (!vRecv.empty())
1292 vRecv >> addrFrom >> nNonce;
1293 if (!vRecv.empty()) {
1294 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1295 cleanSubVer = SanitizeString(strSubVer);
1297 if (!vRecv.empty()) {
1298 vRecv >> nStartingHeight;
1300 if (!vRecv.empty())
1301 vRecv >> fRelay;
1302 // Disconnect if we connected to ourself
1303 if (pfrom->fInbound && !connman.CheckIncomingNonce(nNonce))
1305 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1306 pfrom->fDisconnect = true;
1307 return true;
1310 if (pfrom->fInbound && addrMe.IsRoutable())
1312 SeenLocal(addrMe);
1315 // Be shy and don't send version until we hear
1316 if (pfrom->fInbound)
1317 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1319 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1321 pfrom->nServices = nServices;
1322 pfrom->SetAddrLocal(addrMe);
1324 LOCK(pfrom->cs_SubVer);
1325 pfrom->strSubVer = strSubVer;
1326 pfrom->cleanSubVer = cleanSubVer;
1328 pfrom->nStartingHeight = nStartingHeight;
1329 pfrom->fClient = !(nServices & NODE_NETWORK);
1331 LOCK(pfrom->cs_filter);
1332 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1335 // Change version
1336 pfrom->SetSendVersion(nSendVersion);
1337 pfrom->nVersion = nVersion;
1339 if((nServices & NODE_WITNESS))
1341 LOCK(cs_main);
1342 State(pfrom->GetId())->fHaveWitness = true;
1345 // Potentially mark this peer as a preferred download peer.
1347 LOCK(cs_main);
1348 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1351 if (!pfrom->fInbound)
1353 // Advertise our address
1354 if (fListen && !IsInitialBlockDownload())
1356 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1357 FastRandomContext insecure_rand;
1358 if (addr.IsRoutable())
1360 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1361 pfrom->PushAddress(addr, insecure_rand);
1362 } else if (IsPeerAddrLocalGood(pfrom)) {
1363 addr.SetIP(addrMe);
1364 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1365 pfrom->PushAddress(addr, insecure_rand);
1369 // Get recent addresses
1370 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman.GetAddressCount() < 1000)
1372 connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1373 pfrom->fGetAddr = true;
1375 connman.MarkAddressGood(pfrom->addr);
1378 std::string remoteAddr;
1379 if (fLogIPs)
1380 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1382 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1383 cleanSubVer, pfrom->nVersion,
1384 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1385 remoteAddr);
1387 int64_t nTimeOffset = nTime - GetTime();
1388 pfrom->nTimeOffset = nTimeOffset;
1389 AddTimeData(pfrom->addr, nTimeOffset);
1391 // If the peer is old enough to have the old alert system, send it the final alert.
1392 if (pfrom->nVersion <= 70012) {
1393 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1394 connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1397 // Feeler connections exist only to verify if address is online.
1398 if (pfrom->fFeeler) {
1399 assert(pfrom->fInbound == false);
1400 pfrom->fDisconnect = true;
1402 return true;
1406 else if (pfrom->nVersion == 0)
1408 // Must have a version message before anything else
1409 LOCK(cs_main);
1410 Misbehaving(pfrom->GetId(), 1);
1411 return false;
1414 // At this point, the outgoing message serialization version can't change.
1415 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1417 if (strCommand == NetMsgType::VERACK)
1419 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1421 if (!pfrom->fInbound) {
1422 // Mark this node as currently connected, so we update its timestamp later.
1423 LOCK(cs_main);
1424 State(pfrom->GetId())->fCurrentlyConnected = true;
1427 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1428 // Tell our peer we prefer to receive headers rather than inv's
1429 // We send this to non-NODE NETWORK peers as well, because even
1430 // non-NODE NETWORK peers can announce blocks (such as pruning
1431 // nodes)
1432 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1434 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1435 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1436 // However, we do not request new block announcements using
1437 // cmpctblock messages.
1438 // We send this to non-NODE NETWORK peers as well, because
1439 // they may wish to request compact blocks from us
1440 bool fAnnounceUsingCMPCTBLOCK = false;
1441 uint64_t nCMPCTBLOCKVersion = 2;
1442 if (pfrom->GetLocalServices() & NODE_WITNESS)
1443 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1444 nCMPCTBLOCKVersion = 1;
1445 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1447 pfrom->fSuccessfullyConnected = true;
1450 else if (!pfrom->fSuccessfullyConnected)
1452 // Must have a verack message before anything else
1453 LOCK(cs_main);
1454 Misbehaving(pfrom->GetId(), 1);
1455 return false;
1458 else if (strCommand == NetMsgType::ADDR)
1460 std::vector<CAddress> vAddr;
1461 vRecv >> vAddr;
1463 // Don't want addr from older versions unless seeding
1464 if (pfrom->nVersion < CADDR_TIME_VERSION && connman.GetAddressCount() > 1000)
1465 return true;
1466 if (vAddr.size() > 1000)
1468 LOCK(cs_main);
1469 Misbehaving(pfrom->GetId(), 20);
1470 return error("message addr size() = %u", vAddr.size());
1473 // Store the new addresses
1474 std::vector<CAddress> vAddrOk;
1475 int64_t nNow = GetAdjustedTime();
1476 int64_t nSince = nNow - 10 * 60;
1477 for (CAddress& addr : vAddr)
1479 if (interruptMsgProc)
1480 return true;
1482 if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1483 continue;
1485 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1486 addr.nTime = nNow - 5 * 24 * 60 * 60;
1487 pfrom->AddAddressKnown(addr);
1488 bool fReachable = IsReachable(addr);
1489 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1491 // Relay to a limited number of other nodes
1492 RelayAddress(addr, fReachable, connman);
1494 // Do not store addresses outside our network
1495 if (fReachable)
1496 vAddrOk.push_back(addr);
1498 connman.AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1499 if (vAddr.size() < 1000)
1500 pfrom->fGetAddr = false;
1501 if (pfrom->fOneShot)
1502 pfrom->fDisconnect = true;
1505 else if (strCommand == NetMsgType::SENDHEADERS)
1507 LOCK(cs_main);
1508 State(pfrom->GetId())->fPreferHeaders = true;
1511 else if (strCommand == NetMsgType::SENDCMPCT)
1513 bool fAnnounceUsingCMPCTBLOCK = false;
1514 uint64_t nCMPCTBLOCKVersion = 0;
1515 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1516 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1517 LOCK(cs_main);
1518 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1519 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1520 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1521 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1523 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1524 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1525 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1526 if (pfrom->GetLocalServices() & NODE_WITNESS)
1527 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1528 else
1529 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1535 else if (strCommand == NetMsgType::INV)
1537 std::vector<CInv> vInv;
1538 vRecv >> vInv;
1539 if (vInv.size() > MAX_INV_SZ)
1541 LOCK(cs_main);
1542 Misbehaving(pfrom->GetId(), 20);
1543 return error("message inv size() = %u", vInv.size());
1546 bool fBlocksOnly = !fRelayTxes;
1548 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1549 if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1550 fBlocksOnly = false;
1552 LOCK(cs_main);
1554 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1556 for (CInv &inv : vInv)
1558 if (interruptMsgProc)
1559 return true;
1561 bool fAlreadyHave = AlreadyHave(inv);
1562 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1564 if (inv.type == MSG_TX) {
1565 inv.type |= nFetchFlags;
1568 if (inv.type == MSG_BLOCK) {
1569 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1570 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1571 // We used to request the full block here, but since headers-announcements are now the
1572 // primary method of announcement on the network, and since, in the case that a node
1573 // fell back to inv we probably have a reorg which we should get the headers for first,
1574 // we now only provide a getheaders response here. When we receive the headers, we will
1575 // then ask for the blocks we need.
1576 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1577 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1580 else
1582 pfrom->AddInventoryKnown(inv);
1583 if (fBlocksOnly) {
1584 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1585 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1586 pfrom->AskFor(inv);
1590 // Track requests for our stuff
1591 GetMainSignals().Inventory(inv.hash);
1596 else if (strCommand == NetMsgType::GETDATA)
1598 std::vector<CInv> vInv;
1599 vRecv >> vInv;
1600 if (vInv.size() > MAX_INV_SZ)
1602 LOCK(cs_main);
1603 Misbehaving(pfrom->GetId(), 20);
1604 return error("message getdata size() = %u", vInv.size());
1607 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1609 if (vInv.size() > 0) {
1610 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1613 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1614 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1618 else if (strCommand == NetMsgType::GETBLOCKS)
1620 CBlockLocator locator;
1621 uint256 hashStop;
1622 vRecv >> locator >> hashStop;
1624 // We might have announced the currently-being-connected tip using a
1625 // compact block, which resulted in the peer sending a getblocks
1626 // request, which we would otherwise respond to without the new block.
1627 // To avoid this situation we simply verify that we are on our best
1628 // known chain now. This is super overkill, but we handle it better
1629 // for getheaders requests, and there are no known nodes which support
1630 // compact blocks but still use getblocks to request blocks.
1632 std::shared_ptr<const CBlock> a_recent_block;
1634 LOCK(cs_most_recent_block);
1635 a_recent_block = most_recent_block;
1637 CValidationState dummy;
1638 ActivateBestChain(dummy, Params(), a_recent_block);
1641 LOCK(cs_main);
1643 // Find the last block the caller has in the main chain
1644 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1646 // Send the rest of the chain
1647 if (pindex)
1648 pindex = chainActive.Next(pindex);
1649 int nLimit = 500;
1650 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());
1651 for (; pindex; pindex = chainActive.Next(pindex))
1653 if (pindex->GetBlockHash() == hashStop)
1655 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1656 break;
1658 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1659 // for some reasonable time window (1 hour) that block relay might require.
1660 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1661 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1663 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1664 break;
1666 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1667 if (--nLimit <= 0)
1669 // When this block is requested, we'll send an inv that'll
1670 // trigger the peer to getblocks the next batch of inventory.
1671 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1672 pfrom->hashContinue = pindex->GetBlockHash();
1673 break;
1679 else if (strCommand == NetMsgType::GETBLOCKTXN)
1681 BlockTransactionsRequest req;
1682 vRecv >> req;
1684 std::shared_ptr<const CBlock> recent_block;
1686 LOCK(cs_most_recent_block);
1687 if (most_recent_block_hash == req.blockhash)
1688 recent_block = most_recent_block;
1689 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1691 if (recent_block) {
1692 SendBlockTransactions(*recent_block, req, pfrom, connman);
1693 return true;
1696 LOCK(cs_main);
1698 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1699 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1700 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
1701 return true;
1704 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1705 // If an older block is requested (should never happen in practice,
1706 // but can happen in tests) send a block response instead of a
1707 // blocktxn response. Sending a full block response instead of a
1708 // small blocktxn response is preferable in the case where a peer
1709 // might maliciously send lots of getblocktxn requests to trigger
1710 // expensive disk reads, because it will require the peer to
1711 // actually receive all the data read from disk over the network.
1712 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
1713 CInv inv;
1714 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
1715 inv.hash = req.blockhash;
1716 pfrom->vRecvGetData.push_back(inv);
1717 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1718 return true;
1721 CBlock block;
1722 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
1723 assert(ret);
1725 SendBlockTransactions(block, req, pfrom, connman);
1729 else if (strCommand == NetMsgType::GETHEADERS)
1731 CBlockLocator locator;
1732 uint256 hashStop;
1733 vRecv >> locator >> hashStop;
1735 LOCK(cs_main);
1736 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
1737 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
1738 return true;
1741 CNodeState *nodestate = State(pfrom->GetId());
1742 const CBlockIndex* pindex = NULL;
1743 if (locator.IsNull())
1745 // If locator is null, return the hashStop block
1746 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
1747 if (mi == mapBlockIndex.end())
1748 return true;
1749 pindex = (*mi).second;
1751 else
1753 // Find the last block the caller has in the main chain
1754 pindex = FindForkInGlobalIndex(chainActive, locator);
1755 if (pindex)
1756 pindex = chainActive.Next(pindex);
1759 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1760 std::vector<CBlock> vHeaders;
1761 int nLimit = MAX_HEADERS_RESULTS;
1762 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
1763 for (; pindex; pindex = chainActive.Next(pindex))
1765 vHeaders.push_back(pindex->GetBlockHeader());
1766 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
1767 break;
1769 // pindex can be NULL either if we sent chainActive.Tip() OR
1770 // if our peer has chainActive.Tip() (and thus we are sending an empty
1771 // headers message). In both cases it's safe to update
1772 // pindexBestHeaderSent to be our tip.
1774 // It is important that we simply reset the BestHeaderSent value here,
1775 // and not max(BestHeaderSent, newHeaderSent). We might have announced
1776 // the currently-being-connected tip using a compact block, which
1777 // resulted in the peer sending a headers request, which we respond to
1778 // without the new block. By resetting the BestHeaderSent, we ensure we
1779 // will re-announce the new block via headers (or compact blocks again)
1780 // in the SendMessages logic.
1781 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
1782 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
1786 else if (strCommand == NetMsgType::TX)
1788 // Stop processing the transaction early if
1789 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1790 if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
1792 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
1793 return true;
1796 std::deque<COutPoint> vWorkQueue;
1797 std::vector<uint256> vEraseQueue;
1798 CTransactionRef ptx;
1799 vRecv >> ptx;
1800 const CTransaction& tx = *ptx;
1802 CInv inv(MSG_TX, tx.GetHash());
1803 pfrom->AddInventoryKnown(inv);
1805 LOCK(cs_main);
1807 bool fMissingInputs = false;
1808 CValidationState state;
1810 pfrom->setAskFor.erase(inv.hash);
1811 mapAlreadyAskedFor.erase(inv.hash);
1813 std::list<CTransactionRef> lRemovedTxn;
1815 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, ptx, true, &fMissingInputs, &lRemovedTxn)) {
1816 mempool.check(pcoinsTip);
1817 RelayTransaction(tx, connman);
1818 for (unsigned int i = 0; i < tx.vout.size(); i++) {
1819 vWorkQueue.emplace_back(inv.hash, i);
1822 pfrom->nLastTXTime = GetTime();
1824 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1825 pfrom->GetId(),
1826 tx.GetHash().ToString(),
1827 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
1829 // Recursively process any orphan transactions that depended on this one
1830 std::set<NodeId> setMisbehaving;
1831 while (!vWorkQueue.empty()) {
1832 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
1833 vWorkQueue.pop_front();
1834 if (itByPrev == mapOrphanTransactionsByPrev.end())
1835 continue;
1836 for (auto mi = itByPrev->second.begin();
1837 mi != itByPrev->second.end();
1838 ++mi)
1840 const CTransactionRef& porphanTx = (*mi)->second.tx;
1841 const CTransaction& orphanTx = *porphanTx;
1842 const uint256& orphanHash = orphanTx.GetHash();
1843 NodeId fromPeer = (*mi)->second.fromPeer;
1844 bool fMissingInputs2 = false;
1845 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1846 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1847 // anyone relaying LegitTxX banned)
1848 CValidationState stateDummy;
1851 if (setMisbehaving.count(fromPeer))
1852 continue;
1853 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, true, &fMissingInputs2, &lRemovedTxn)) {
1854 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
1855 RelayTransaction(orphanTx, connman);
1856 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
1857 vWorkQueue.emplace_back(orphanHash, i);
1859 vEraseQueue.push_back(orphanHash);
1861 else if (!fMissingInputs2)
1863 int nDos = 0;
1864 if (stateDummy.IsInvalid(nDos) && nDos > 0)
1866 // Punish peer that gave us an invalid orphan tx
1867 Misbehaving(fromPeer, nDos);
1868 setMisbehaving.insert(fromPeer);
1869 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
1871 // Has inputs but not accepted to mempool
1872 // Probably non-standard or insufficient fee
1873 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
1874 vEraseQueue.push_back(orphanHash);
1875 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
1876 // Do not use rejection cache for witness transactions or
1877 // witness-stripped transactions, as they can have been malleated.
1878 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1879 assert(recentRejects);
1880 recentRejects->insert(orphanHash);
1883 mempool.check(pcoinsTip);
1887 for (uint256 hash : vEraseQueue)
1888 EraseOrphanTx(hash);
1890 else if (fMissingInputs)
1892 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
1893 for (const CTxIn& txin : tx.vin) {
1894 if (recentRejects->contains(txin.prevout.hash)) {
1895 fRejectedParents = true;
1896 break;
1899 if (!fRejectedParents) {
1900 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1901 for (const CTxIn& txin : tx.vin) {
1902 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
1903 pfrom->AddInventoryKnown(_inv);
1904 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
1906 AddOrphanTx(ptx, pfrom->GetId());
1908 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1909 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
1910 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
1911 if (nEvicted > 0) {
1912 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
1914 } else {
1915 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
1916 // We will continue to reject this tx since it has rejected
1917 // parents so avoid re-requesting it from other peers.
1918 recentRejects->insert(tx.GetHash());
1920 } else {
1921 if (!tx.HasWitness() && !state.CorruptionPossible()) {
1922 // Do not use rejection cache for witness transactions or
1923 // witness-stripped transactions, as they can have been malleated.
1924 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1925 assert(recentRejects);
1926 recentRejects->insert(tx.GetHash());
1927 if (RecursiveDynamicUsage(*ptx) < 100000) {
1928 AddToCompactExtraTransactions(ptx);
1930 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
1931 AddToCompactExtraTransactions(ptx);
1934 if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1935 // Always relay transactions received from whitelisted peers, even
1936 // if they were already in the mempool or rejected from it due
1937 // to policy, allowing the node to function as a gateway for
1938 // nodes hidden behind it.
1940 // Never relay transactions that we would assign a non-zero DoS
1941 // score for, as we expect peers to do the same with us in that
1942 // case.
1943 int nDoS = 0;
1944 if (!state.IsInvalid(nDoS) || nDoS == 0) {
1945 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
1946 RelayTransaction(tx, connman);
1947 } else {
1948 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
1953 for (const CTransactionRef& removedTx : lRemovedTxn)
1954 AddToCompactExtraTransactions(removedTx);
1956 int nDoS = 0;
1957 if (state.IsInvalid(nDoS))
1959 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
1960 pfrom->GetId(),
1961 FormatStateMessage(state));
1962 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
1963 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
1964 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
1965 if (nDoS > 0) {
1966 Misbehaving(pfrom->GetId(), nDoS);
1972 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
1974 CBlockHeaderAndShortTxIDs cmpctblock;
1975 vRecv >> cmpctblock;
1978 LOCK(cs_main);
1980 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
1981 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1982 if (!IsInitialBlockDownload())
1983 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1984 return true;
1988 const CBlockIndex *pindex = NULL;
1989 CValidationState state;
1990 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
1991 int nDoS;
1992 if (state.IsInvalid(nDoS)) {
1993 if (nDoS > 0) {
1994 LOCK(cs_main);
1995 Misbehaving(pfrom->GetId(), nDoS);
1997 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
1998 return true;
2002 // When we succeed in decoding a block's txids from a cmpctblock
2003 // message we typically jump to the BLOCKTXN handling code, with a
2004 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2005 // completing processing of the putative block (without cs_main).
2006 bool fProcessBLOCKTXN = false;
2007 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2009 // If we end up treating this as a plain headers message, call that as well
2010 // without cs_main.
2011 bool fRevertToHeaderProcessing = false;
2012 CDataStream vHeadersMsg(SER_NETWORK, PROTOCOL_VERSION);
2014 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2015 // below)
2016 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2017 bool fBlockReconstructed = false;
2020 LOCK(cs_main);
2021 // If AcceptBlockHeader returned true, it set pindex
2022 assert(pindex);
2023 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2025 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2026 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2028 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2029 return true;
2031 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2032 pindex->nTx != 0) { // We had this block at some point, but pruned it
2033 if (fAlreadyInFlight) {
2034 // We requested this block for some reason, but our mempool will probably be useless
2035 // so we just grab the block via normal getdata
2036 std::vector<CInv> vInv(1);
2037 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2038 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2040 return true;
2043 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2044 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2045 return true;
2047 CNodeState *nodestate = State(pfrom->GetId());
2049 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2050 // Don't bother trying to process compact blocks from v1 peers
2051 // after segwit activates.
2052 return true;
2055 // We want to be a bit conservative just to be extra careful about DoS
2056 // possibilities in compact block processing...
2057 if (pindex->nHeight <= chainActive.Height() + 2) {
2058 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2059 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2060 std::list<QueuedBlock>::iterator* queuedBlockIt = NULL;
2061 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2062 if (!(*queuedBlockIt)->partialBlock)
2063 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2064 else {
2065 // The block was already in flight using compact blocks from the same peer
2066 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2067 return true;
2071 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2072 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2073 if (status == READ_STATUS_INVALID) {
2074 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2075 Misbehaving(pfrom->GetId(), 100);
2076 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2077 return true;
2078 } else if (status == READ_STATUS_FAILED) {
2079 // Duplicate txindexes, the block is now in-flight, so just request it
2080 std::vector<CInv> vInv(1);
2081 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2082 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2083 return true;
2086 BlockTransactionsRequest req;
2087 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2088 if (!partialBlock.IsTxAvailable(i))
2089 req.indexes.push_back(i);
2091 if (req.indexes.empty()) {
2092 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2093 BlockTransactions txn;
2094 txn.blockhash = cmpctblock.header.GetHash();
2095 blockTxnMsg << txn;
2096 fProcessBLOCKTXN = true;
2097 } else {
2098 req.blockhash = pindex->GetBlockHash();
2099 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2101 } else {
2102 // This block is either already in flight from a different
2103 // peer, or this peer has too many blocks outstanding to
2104 // download from.
2105 // Optimistically try to reconstruct anyway since we might be
2106 // able to without any round trips.
2107 PartiallyDownloadedBlock tempBlock(&mempool);
2108 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2109 if (status != READ_STATUS_OK) {
2110 // TODO: don't ignore failures
2111 return true;
2113 std::vector<CTransactionRef> dummy;
2114 status = tempBlock.FillBlock(*pblock, dummy);
2115 if (status == READ_STATUS_OK) {
2116 fBlockReconstructed = true;
2119 } else {
2120 if (fAlreadyInFlight) {
2121 // We requested this block, but its far into the future, so our
2122 // mempool will probably be useless - request the block normally
2123 std::vector<CInv> vInv(1);
2124 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2125 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2126 return true;
2127 } else {
2128 // If this was an announce-cmpctblock, we want the same treatment as a header message
2129 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
2130 std::vector<CBlock> headers;
2131 headers.push_back(cmpctblock.header);
2132 vHeadersMsg << headers;
2133 fRevertToHeaderProcessing = true;
2136 } // cs_main
2138 if (fProcessBLOCKTXN)
2139 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2141 if (fRevertToHeaderProcessing)
2142 return ProcessMessage(pfrom, NetMsgType::HEADERS, vHeadersMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2144 if (fBlockReconstructed) {
2145 // If we got here, we were able to optimistically reconstruct a
2146 // block that is in flight from some other peer.
2148 LOCK(cs_main);
2149 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2151 bool fNewBlock = false;
2152 ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
2153 if (fNewBlock)
2154 pfrom->nLastBlockTime = GetTime();
2156 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2157 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2158 // Clear download state for this block, which is in
2159 // process from some other peer. We do this after calling
2160 // ProcessNewBlock so that a malleated cmpctblock announcement
2161 // can't be used to interfere with block relay.
2162 MarkBlockAsReceived(pblock->GetHash());
2168 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2170 BlockTransactions resp;
2171 vRecv >> resp;
2173 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2174 bool fBlockRead = false;
2176 LOCK(cs_main);
2178 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2179 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2180 it->second.first != pfrom->GetId()) {
2181 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2182 return true;
2185 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2186 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2187 if (status == READ_STATUS_INVALID) {
2188 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2189 Misbehaving(pfrom->GetId(), 100);
2190 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2191 return true;
2192 } else if (status == READ_STATUS_FAILED) {
2193 // Might have collided, fall back to getdata now :(
2194 std::vector<CInv> invs;
2195 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2196 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2197 } else {
2198 // Block is either okay, or possibly we received
2199 // READ_STATUS_CHECKBLOCK_FAILED.
2200 // Note that CheckBlock can only fail for one of a few reasons:
2201 // 1. bad-proof-of-work (impossible here, because we've already
2202 // accepted the header)
2203 // 2. merkleroot doesn't match the transactions given (already
2204 // caught in FillBlock with READ_STATUS_FAILED, so
2205 // impossible here)
2206 // 3. the block is otherwise invalid (eg invalid coinbase,
2207 // block is too big, too many legacy sigops, etc).
2208 // So if CheckBlock failed, #3 is the only possibility.
2209 // Under BIP 152, we don't DoS-ban unless proof of work is
2210 // invalid (we don't require all the stateless checks to have
2211 // been run). This is handled below, so just treat this as
2212 // though the block was successfully read, and rely on the
2213 // handling in ProcessNewBlock to ensure the block index is
2214 // updated, reject messages go out, etc.
2215 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2216 fBlockRead = true;
2217 // mapBlockSource is only used for sending reject messages and DoS scores,
2218 // so the race between here and cs_main in ProcessNewBlock is fine.
2219 // BIP 152 permits peers to relay compact blocks after validating
2220 // the header only; we should not punish peers if the block turns
2221 // out to be invalid.
2222 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2224 } // Don't hold cs_main when we call into ProcessNewBlock
2225 if (fBlockRead) {
2226 bool fNewBlock = false;
2227 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2228 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2229 ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
2230 if (fNewBlock)
2231 pfrom->nLastBlockTime = GetTime();
2236 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2238 std::vector<CBlockHeader> headers;
2240 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2241 unsigned int nCount = ReadCompactSize(vRecv);
2242 if (nCount > MAX_HEADERS_RESULTS) {
2243 LOCK(cs_main);
2244 Misbehaving(pfrom->GetId(), 20);
2245 return error("headers message size = %u", nCount);
2247 headers.resize(nCount);
2248 for (unsigned int n = 0; n < nCount; n++) {
2249 vRecv >> headers[n];
2250 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2253 if (nCount == 0) {
2254 // Nothing interesting. Stop asking this peers for more headers.
2255 return true;
2258 const CBlockIndex *pindexLast = NULL;
2260 LOCK(cs_main);
2261 CNodeState *nodestate = State(pfrom->GetId());
2263 // If this looks like it could be a block announcement (nCount <
2264 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2265 // don't connect:
2266 // - Send a getheaders message in response to try to connect the chain.
2267 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2268 // don't connect before giving DoS points
2269 // - Once a headers message is received that is valid and does connect,
2270 // nUnconnectingHeaders gets reset back to 0.
2271 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
2272 nodestate->nUnconnectingHeaders++;
2273 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2274 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2275 headers[0].GetHash().ToString(),
2276 headers[0].hashPrevBlock.ToString(),
2277 pindexBestHeader->nHeight,
2278 pfrom->GetId(), nodestate->nUnconnectingHeaders);
2279 // Set hashLastUnknownBlock for this peer, so that if we
2280 // eventually get the headers - even from a different peer -
2281 // we can use this peer to download.
2282 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
2284 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
2285 Misbehaving(pfrom->GetId(), 20);
2287 return true;
2290 uint256 hashLastBlock;
2291 for (const CBlockHeader& header : headers) {
2292 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2293 Misbehaving(pfrom->GetId(), 20);
2294 return error("non-continuous headers sequence");
2296 hashLastBlock = header.GetHash();
2300 CValidationState state;
2301 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast)) {
2302 int nDoS;
2303 if (state.IsInvalid(nDoS)) {
2304 if (nDoS > 0) {
2305 LOCK(cs_main);
2306 Misbehaving(pfrom->GetId(), nDoS);
2308 return error("invalid header received");
2313 LOCK(cs_main);
2314 CNodeState *nodestate = State(pfrom->GetId());
2315 if (nodestate->nUnconnectingHeaders > 0) {
2316 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
2318 nodestate->nUnconnectingHeaders = 0;
2320 assert(pindexLast);
2321 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
2323 if (nCount == MAX_HEADERS_RESULTS) {
2324 // Headers message had its maximum size; the peer may have more headers.
2325 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2326 // from there instead.
2327 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
2328 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
2331 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
2332 // If this set of headers is valid and ends in a block with at least as
2333 // much work as our tip, download as much as possible.
2334 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
2335 std::vector<const CBlockIndex*> vToFetch;
2336 const CBlockIndex *pindexWalk = pindexLast;
2337 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2338 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2339 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2340 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
2341 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
2342 // We don't have this block, and it's not yet in flight.
2343 vToFetch.push_back(pindexWalk);
2345 pindexWalk = pindexWalk->pprev;
2347 // If pindexWalk still isn't on our main chain, we're looking at a
2348 // very large reorg at a time we think we're close to caught up to
2349 // the main chain -- this shouldn't really happen. Bail out on the
2350 // direct fetch and rely on parallel download instead.
2351 if (!chainActive.Contains(pindexWalk)) {
2352 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
2353 pindexLast->GetBlockHash().ToString(),
2354 pindexLast->nHeight);
2355 } else {
2356 std::vector<CInv> vGetData;
2357 // Download as much as possible, from earliest to latest.
2358 BOOST_REVERSE_FOREACH(const CBlockIndex *pindex, vToFetch) {
2359 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2360 // Can't download any more from this peer
2361 break;
2363 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2364 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2365 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
2366 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
2367 pindex->GetBlockHash().ToString(), pfrom->GetId());
2369 if (vGetData.size() > 1) {
2370 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2371 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
2373 if (vGetData.size() > 0) {
2374 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
2375 // In any case, we want to download using a compact block, not a regular one
2376 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2378 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2385 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2387 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2388 vRecv >> *pblock;
2390 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2392 // Process all blocks from whitelisted peers, even if not requested,
2393 // unless we're still syncing with the network.
2394 // Such an unrequested block may still be processed, subject to the
2395 // conditions in AcceptBlock().
2396 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
2397 const uint256 hash(pblock->GetHash());
2399 LOCK(cs_main);
2400 // Also always process if we requested the block explicitly, as we may
2401 // need it even though it is not a candidate for a new best tip.
2402 forceProcessing |= MarkBlockAsReceived(hash);
2403 // mapBlockSource is only used for sending reject messages and DoS scores,
2404 // so the race between here and cs_main in ProcessNewBlock is fine.
2405 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2407 bool fNewBlock = false;
2408 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2409 if (fNewBlock)
2410 pfrom->nLastBlockTime = GetTime();
2414 else if (strCommand == NetMsgType::GETADDR)
2416 // This asymmetric behavior for inbound and outbound connections was introduced
2417 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2418 // to users' AddrMan and later request them by sending getaddr messages.
2419 // Making nodes which are behind NAT and can only make outgoing connections ignore
2420 // the getaddr message mitigates the attack.
2421 if (!pfrom->fInbound) {
2422 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2423 return true;
2426 // Only send one GetAddr response per connection to reduce resource waste
2427 // and discourage addr stamping of INV announcements.
2428 if (pfrom->fSentAddr) {
2429 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2430 return true;
2432 pfrom->fSentAddr = true;
2434 pfrom->vAddrToSend.clear();
2435 std::vector<CAddress> vAddr = connman.GetAddresses();
2436 FastRandomContext insecure_rand;
2437 for (const CAddress &addr : vAddr)
2438 pfrom->PushAddress(addr, insecure_rand);
2442 else if (strCommand == NetMsgType::MEMPOOL)
2444 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2446 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2447 pfrom->fDisconnect = true;
2448 return true;
2451 if (connman.OutboundTargetReached(false) && !pfrom->fWhitelisted)
2453 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2454 pfrom->fDisconnect = true;
2455 return true;
2458 LOCK(pfrom->cs_inventory);
2459 pfrom->fSendMempool = true;
2463 else if (strCommand == NetMsgType::PING)
2465 if (pfrom->nVersion > BIP0031_VERSION)
2467 uint64_t nonce = 0;
2468 vRecv >> nonce;
2469 // Echo the message back with the nonce. This allows for two useful features:
2471 // 1) A remote node can quickly check if the connection is operational
2472 // 2) Remote nodes can measure the latency of the network thread. If this node
2473 // is overloaded it won't respond to pings quickly and the remote node can
2474 // avoid sending us more work, like chain download requests.
2476 // The nonce stops the remote getting confused between different pings: without
2477 // it, if the remote node sends a ping once per second and this node takes 5
2478 // seconds to respond to each, the 5th ping the remote sends would appear to
2479 // return very quickly.
2480 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2485 else if (strCommand == NetMsgType::PONG)
2487 int64_t pingUsecEnd = nTimeReceived;
2488 uint64_t nonce = 0;
2489 size_t nAvail = vRecv.in_avail();
2490 bool bPingFinished = false;
2491 std::string sProblem;
2493 if (nAvail >= sizeof(nonce)) {
2494 vRecv >> nonce;
2496 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2497 if (pfrom->nPingNonceSent != 0) {
2498 if (nonce == pfrom->nPingNonceSent) {
2499 // Matching pong received, this ping is no longer outstanding
2500 bPingFinished = true;
2501 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2502 if (pingUsecTime > 0) {
2503 // Successful ping time measurement, replace previous
2504 pfrom->nPingUsecTime = pingUsecTime;
2505 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2506 } else {
2507 // This should never happen
2508 sProblem = "Timing mishap";
2510 } else {
2511 // Nonce mismatches are normal when pings are overlapping
2512 sProblem = "Nonce mismatch";
2513 if (nonce == 0) {
2514 // This is most likely a bug in another implementation somewhere; cancel this ping
2515 bPingFinished = true;
2516 sProblem = "Nonce zero";
2519 } else {
2520 sProblem = "Unsolicited pong without ping";
2522 } else {
2523 // This is most likely a bug in another implementation somewhere; cancel this ping
2524 bPingFinished = true;
2525 sProblem = "Short payload";
2528 if (!(sProblem.empty())) {
2529 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2530 pfrom->GetId(),
2531 sProblem,
2532 pfrom->nPingNonceSent,
2533 nonce,
2534 nAvail);
2536 if (bPingFinished) {
2537 pfrom->nPingNonceSent = 0;
2542 else if (strCommand == NetMsgType::FILTERLOAD)
2544 CBloomFilter filter;
2545 vRecv >> filter;
2547 if (!filter.IsWithinSizeConstraints())
2549 // There is no excuse for sending a too-large filter
2550 LOCK(cs_main);
2551 Misbehaving(pfrom->GetId(), 100);
2553 else
2555 LOCK(pfrom->cs_filter);
2556 delete pfrom->pfilter;
2557 pfrom->pfilter = new CBloomFilter(filter);
2558 pfrom->pfilter->UpdateEmptyFull();
2559 pfrom->fRelayTxes = true;
2564 else if (strCommand == NetMsgType::FILTERADD)
2566 std::vector<unsigned char> vData;
2567 vRecv >> vData;
2569 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2570 // and thus, the maximum size any matched object can have) in a filteradd message
2571 bool bad = false;
2572 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2573 bad = true;
2574 } else {
2575 LOCK(pfrom->cs_filter);
2576 if (pfrom->pfilter) {
2577 pfrom->pfilter->insert(vData);
2578 } else {
2579 bad = true;
2582 if (bad) {
2583 LOCK(cs_main);
2584 Misbehaving(pfrom->GetId(), 100);
2589 else if (strCommand == NetMsgType::FILTERCLEAR)
2591 LOCK(pfrom->cs_filter);
2592 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2593 delete pfrom->pfilter;
2594 pfrom->pfilter = new CBloomFilter();
2596 pfrom->fRelayTxes = true;
2599 else if (strCommand == NetMsgType::FEEFILTER) {
2600 CAmount newFeeFilter = 0;
2601 vRecv >> newFeeFilter;
2602 if (MoneyRange(newFeeFilter)) {
2604 LOCK(pfrom->cs_feeFilter);
2605 pfrom->minFeeFilter = newFeeFilter;
2607 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2611 else if (strCommand == NetMsgType::NOTFOUND) {
2612 // We do not care about the NOTFOUND message, but logging an Unknown Command
2613 // message would be undesirable as we transmit it ourselves.
2616 else {
2617 // Ignore unknown commands for extensibility
2618 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2623 return true;
2626 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman& connman)
2628 AssertLockHeld(cs_main);
2629 CNodeState &state = *State(pnode->GetId());
2631 for (const CBlockReject& reject : state.rejects) {
2632 connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2634 state.rejects.clear();
2636 if (state.fShouldBan) {
2637 state.fShouldBan = false;
2638 if (pnode->fWhitelisted)
2639 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2640 else if (pnode->fAddnode)
2641 LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode->addr.ToString());
2642 else {
2643 pnode->fDisconnect = true;
2644 if (pnode->addr.IsLocal())
2645 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2646 else
2648 connman.Ban(pnode->addr, BanReasonNodeMisbehaving);
2651 return true;
2653 return false;
2656 bool ProcessMessages(CNode* pfrom, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
2658 const CChainParams& chainparams = Params();
2660 // Message format
2661 // (4) message start
2662 // (12) command
2663 // (4) size
2664 // (4) checksum
2665 // (x) data
2667 bool fMoreWork = false;
2669 if (!pfrom->vRecvGetData.empty())
2670 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2672 if (pfrom->fDisconnect)
2673 return false;
2675 // this maintains the order of responses
2676 if (!pfrom->vRecvGetData.empty()) return true;
2678 // Don't bother if send buffer is too full to respond anyway
2679 if (pfrom->fPauseSend)
2680 return false;
2682 std::list<CNetMessage> msgs;
2684 LOCK(pfrom->cs_vProcessMsg);
2685 if (pfrom->vProcessMsg.empty())
2686 return false;
2687 // Just take one message
2688 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2689 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2690 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman.GetReceiveFloodSize();
2691 fMoreWork = !pfrom->vProcessMsg.empty();
2693 CNetMessage& msg(msgs.front());
2695 msg.SetVersion(pfrom->GetRecvVersion());
2696 // Scan for message start
2697 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2698 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2699 pfrom->fDisconnect = true;
2700 return false;
2703 // Read header
2704 CMessageHeader& hdr = msg.hdr;
2705 if (!hdr.IsValid(chainparams.MessageStart()))
2707 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2708 return fMoreWork;
2710 std::string strCommand = hdr.GetCommand();
2712 // Message size
2713 unsigned int nMessageSize = hdr.nMessageSize;
2715 // Checksum
2716 CDataStream& vRecv = msg.vRecv;
2717 const uint256& hash = msg.GetMessageHash();
2718 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2720 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2721 SanitizeString(strCommand), nMessageSize,
2722 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2723 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2724 return fMoreWork;
2727 // Process message
2728 bool fRet = false;
2731 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2732 if (interruptMsgProc)
2733 return false;
2734 if (!pfrom->vRecvGetData.empty())
2735 fMoreWork = true;
2737 catch (const std::ios_base::failure& e)
2739 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2740 if (strstr(e.what(), "end of data"))
2742 // Allow exceptions from under-length message on vRecv
2743 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());
2745 else if (strstr(e.what(), "size too large"))
2747 // Allow exceptions from over-long size
2748 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2750 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2752 // Allow exceptions from non-canonical encoding
2753 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2755 else
2757 PrintExceptionContinue(&e, "ProcessMessages()");
2760 catch (const std::exception& e) {
2761 PrintExceptionContinue(&e, "ProcessMessages()");
2762 } catch (...) {
2763 PrintExceptionContinue(NULL, "ProcessMessages()");
2766 if (!fRet) {
2767 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
2770 LOCK(cs_main);
2771 SendRejectsAndCheckIfBanned(pfrom, connman);
2773 return fMoreWork;
2776 class CompareInvMempoolOrder
2778 CTxMemPool *mp;
2779 public:
2780 CompareInvMempoolOrder(CTxMemPool *_mempool)
2782 mp = _mempool;
2785 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
2787 /* As std::make_heap produces a max-heap, we want the entries with the
2788 * fewest ancestors/highest fee to sort later. */
2789 return mp->CompareDepthAndScore(*b, *a);
2793 bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
2795 const Consensus::Params& consensusParams = Params().GetConsensus();
2797 // Don't send anything until the version handshake is complete
2798 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
2799 return true;
2801 // If we get here, the outgoing message serialization version is set and can't change.
2802 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2805 // Message: ping
2807 bool pingSend = false;
2808 if (pto->fPingQueued) {
2809 // RPC ping request by user
2810 pingSend = true;
2812 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
2813 // Ping automatically sent as a latency probe & keepalive.
2814 pingSend = true;
2816 if (pingSend) {
2817 uint64_t nonce = 0;
2818 while (nonce == 0) {
2819 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
2821 pto->fPingQueued = false;
2822 pto->nPingUsecStart = GetTimeMicros();
2823 if (pto->nVersion > BIP0031_VERSION) {
2824 pto->nPingNonceSent = nonce;
2825 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
2826 } else {
2827 // Peer is too old to support ping command with nonce, pong will never arrive.
2828 pto->nPingNonceSent = 0;
2829 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING));
2833 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2834 if (!lockMain)
2835 return true;
2837 if (SendRejectsAndCheckIfBanned(pto, connman))
2838 return true;
2839 CNodeState &state = *State(pto->GetId());
2841 // Address refresh broadcast
2842 int64_t nNow = GetTimeMicros();
2843 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
2844 AdvertiseLocal(pto);
2845 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
2849 // Message: addr
2851 if (pto->nNextAddrSend < nNow) {
2852 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
2853 std::vector<CAddress> vAddr;
2854 vAddr.reserve(pto->vAddrToSend.size());
2855 for (const CAddress& addr : pto->vAddrToSend)
2857 if (!pto->addrKnown.contains(addr.GetKey()))
2859 pto->addrKnown.insert(addr.GetKey());
2860 vAddr.push_back(addr);
2861 // receiver rejects addr messages larger than 1000
2862 if (vAddr.size() >= 1000)
2864 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2865 vAddr.clear();
2869 pto->vAddrToSend.clear();
2870 if (!vAddr.empty())
2871 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2872 // we only send the big addr message once
2873 if (pto->vAddrToSend.capacity() > 40)
2874 pto->vAddrToSend.shrink_to_fit();
2877 // Start block sync
2878 if (pindexBestHeader == NULL)
2879 pindexBestHeader = chainActive.Tip();
2880 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.
2881 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
2882 // Only actively request headers from a single peer, unless we're close to today.
2883 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2884 state.fSyncStarted = true;
2885 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
2886 nSyncStarted++;
2887 const CBlockIndex *pindexStart = pindexBestHeader;
2888 /* If possible, start at the block preceding the currently
2889 best known header. This ensures that we always get a
2890 non-empty list of headers back as long as the peer
2891 is up-to-date. With a non-empty response, we can initialise
2892 the peer's known best block. This wouldn't be possible
2893 if we requested starting at pindexBestHeader and
2894 got back an empty response. */
2895 if (pindexStart->pprev)
2896 pindexStart = pindexStart->pprev;
2897 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
2898 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
2902 // Resend wallet transactions that haven't gotten in a block yet
2903 // Except during reindex, importing and IBD, when old wallet
2904 // transactions become unconfirmed and spams other nodes.
2905 if (!fReindex && !fImporting && !IsInitialBlockDownload())
2907 GetMainSignals().Broadcast(nTimeBestReceived, &connman);
2911 // Try sending block announcements via headers
2914 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2915 // list of block hashes we're relaying, and our peer wants
2916 // headers announcements, then find the first header
2917 // not yet known to our peer but would connect, and send.
2918 // If no header would connect, or if we have too many
2919 // blocks, or if the peer doesn't want headers, just
2920 // add all to the inv queue.
2921 LOCK(pto->cs_inventory);
2922 std::vector<CBlock> vHeaders;
2923 bool fRevertToInv = ((!state.fPreferHeaders &&
2924 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
2925 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
2926 const CBlockIndex *pBestIndex = NULL; // last header queued for delivery
2927 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
2929 if (!fRevertToInv) {
2930 bool fFoundStartingHeader = false;
2931 // Try to find first header that our peer doesn't have, and
2932 // then send all headers past that one. If we come across any
2933 // headers that aren't on chainActive, give up.
2934 for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
2935 BlockMap::iterator mi = mapBlockIndex.find(hash);
2936 assert(mi != mapBlockIndex.end());
2937 const CBlockIndex *pindex = mi->second;
2938 if (chainActive[pindex->nHeight] != pindex) {
2939 // Bail out if we reorged away from this block
2940 fRevertToInv = true;
2941 break;
2943 if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
2944 // This means that the list of blocks to announce don't
2945 // connect to each other.
2946 // This shouldn't really be possible to hit during
2947 // regular operation (because reorgs should take us to
2948 // a chain that has some block not on the prior chain,
2949 // which should be caught by the prior check), but one
2950 // way this could happen is by using invalidateblock /
2951 // reconsiderblock repeatedly on the tip, causing it to
2952 // be added multiple times to vBlockHashesToAnnounce.
2953 // Robustly deal with this rare situation by reverting
2954 // to an inv.
2955 fRevertToInv = true;
2956 break;
2958 pBestIndex = pindex;
2959 if (fFoundStartingHeader) {
2960 // add this to the headers message
2961 vHeaders.push_back(pindex->GetBlockHeader());
2962 } else if (PeerHasHeader(&state, pindex)) {
2963 continue; // keep looking for the first new block
2964 } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
2965 // Peer doesn't have this header but they do have the prior one.
2966 // Start sending headers.
2967 fFoundStartingHeader = true;
2968 vHeaders.push_back(pindex->GetBlockHeader());
2969 } else {
2970 // Peer doesn't have this header or the prior one -- nothing will
2971 // connect, so bail out.
2972 fRevertToInv = true;
2973 break;
2977 if (!fRevertToInv && !vHeaders.empty()) {
2978 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
2979 // We only send up to 1 block as header-and-ids, as otherwise
2980 // probably means we're doing an initial-ish-sync or they're slow
2981 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
2982 vHeaders.front().GetHash().ToString(), pto->GetId());
2984 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
2986 bool fGotBlockFromCache = false;
2988 LOCK(cs_most_recent_block);
2989 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
2990 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
2991 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
2992 else {
2993 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
2994 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
2996 fGotBlockFromCache = true;
2999 if (!fGotBlockFromCache) {
3000 CBlock block;
3001 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3002 assert(ret);
3003 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3004 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3006 state.pindexBestHeaderSent = pBestIndex;
3007 } else if (state.fPreferHeaders) {
3008 if (vHeaders.size() > 1) {
3009 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3010 vHeaders.size(),
3011 vHeaders.front().GetHash().ToString(),
3012 vHeaders.back().GetHash().ToString(), pto->GetId());
3013 } else {
3014 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3015 vHeaders.front().GetHash().ToString(), pto->GetId());
3017 connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3018 state.pindexBestHeaderSent = pBestIndex;
3019 } else
3020 fRevertToInv = true;
3022 if (fRevertToInv) {
3023 // If falling back to using an inv, just try to inv the tip.
3024 // The last entry in vBlockHashesToAnnounce was our tip at some point
3025 // in the past.
3026 if (!pto->vBlockHashesToAnnounce.empty()) {
3027 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3028 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3029 assert(mi != mapBlockIndex.end());
3030 const CBlockIndex *pindex = mi->second;
3032 // Warn if we're announcing a block that is not on the main chain.
3033 // This should be very rare and could be optimized out.
3034 // Just log for now.
3035 if (chainActive[pindex->nHeight] != pindex) {
3036 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3037 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3040 // If the peer's chain has this block, don't inv it back.
3041 if (!PeerHasHeader(&state, pindex)) {
3042 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3043 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3044 pto->GetId(), hashToAnnounce.ToString());
3048 pto->vBlockHashesToAnnounce.clear();
3052 // Message: inventory
3054 std::vector<CInv> vInv;
3056 LOCK(pto->cs_inventory);
3057 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3059 // Add blocks
3060 for (const uint256& hash : pto->vInventoryBlockToSend) {
3061 vInv.push_back(CInv(MSG_BLOCK, hash));
3062 if (vInv.size() == MAX_INV_SZ) {
3063 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3064 vInv.clear();
3067 pto->vInventoryBlockToSend.clear();
3069 // Check whether periodic sends should happen
3070 bool fSendTrickle = pto->fWhitelisted;
3071 if (pto->nNextInvSend < nNow) {
3072 fSendTrickle = true;
3073 // Use half the delay for outbound peers, as there is less privacy concern for them.
3074 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3077 // Time to send but the peer has requested we not relay transactions.
3078 if (fSendTrickle) {
3079 LOCK(pto->cs_filter);
3080 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3083 // Respond to BIP35 mempool requests
3084 if (fSendTrickle && pto->fSendMempool) {
3085 auto vtxinfo = mempool.infoAll();
3086 pto->fSendMempool = false;
3087 CAmount filterrate = 0;
3089 LOCK(pto->cs_feeFilter);
3090 filterrate = pto->minFeeFilter;
3093 LOCK(pto->cs_filter);
3095 for (const auto& txinfo : vtxinfo) {
3096 const uint256& hash = txinfo.tx->GetHash();
3097 CInv inv(MSG_TX, hash);
3098 pto->setInventoryTxToSend.erase(hash);
3099 if (filterrate) {
3100 if (txinfo.feeRate.GetFeePerK() < filterrate)
3101 continue;
3103 if (pto->pfilter) {
3104 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3106 pto->filterInventoryKnown.insert(hash);
3107 vInv.push_back(inv);
3108 if (vInv.size() == MAX_INV_SZ) {
3109 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3110 vInv.clear();
3113 pto->timeLastMempoolReq = GetTime();
3116 // Determine transactions to relay
3117 if (fSendTrickle) {
3118 // Produce a vector with all candidates for sending
3119 std::vector<std::set<uint256>::iterator> vInvTx;
3120 vInvTx.reserve(pto->setInventoryTxToSend.size());
3121 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3122 vInvTx.push_back(it);
3124 CAmount filterrate = 0;
3126 LOCK(pto->cs_feeFilter);
3127 filterrate = pto->minFeeFilter;
3129 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3130 // A heap is used so that not all items need sorting if only a few are being sent.
3131 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3132 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3133 // No reason to drain out at many times the network's capacity,
3134 // especially since we have many peers and some will draw much shorter delays.
3135 unsigned int nRelayedTransactions = 0;
3136 LOCK(pto->cs_filter);
3137 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3138 // Fetch the top element from the heap
3139 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3140 std::set<uint256>::iterator it = vInvTx.back();
3141 vInvTx.pop_back();
3142 uint256 hash = *it;
3143 // Remove it from the to-be-sent set
3144 pto->setInventoryTxToSend.erase(it);
3145 // Check if not in the filter already
3146 if (pto->filterInventoryKnown.contains(hash)) {
3147 continue;
3149 // Not in the mempool anymore? don't bother sending it.
3150 auto txinfo = mempool.info(hash);
3151 if (!txinfo.tx) {
3152 continue;
3154 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3155 continue;
3157 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3158 // Send
3159 vInv.push_back(CInv(MSG_TX, hash));
3160 nRelayedTransactions++;
3162 // Expire old relay messages
3163 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3165 mapRelay.erase(vRelayExpiration.front().second);
3166 vRelayExpiration.pop_front();
3169 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3170 if (ret.second) {
3171 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3174 if (vInv.size() == MAX_INV_SZ) {
3175 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3176 vInv.clear();
3178 pto->filterInventoryKnown.insert(hash);
3182 if (!vInv.empty())
3183 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3185 // Detect whether we're stalling
3186 nNow = GetTimeMicros();
3187 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3188 // Stalling only triggers when the block download window cannot move. During normal steady state,
3189 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3190 // should only happen during initial block download.
3191 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3192 pto->fDisconnect = true;
3193 return true;
3195 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3196 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3197 // We compensate for other peers to prevent killing off peers due to our own downstream link
3198 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3199 // to unreasonably increase our timeout.
3200 if (state.vBlocksInFlight.size() > 0) {
3201 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3202 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3203 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3204 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3205 pto->fDisconnect = true;
3206 return true;
3209 // Check for headers sync timeouts
3210 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3211 // Detect whether this is a stalling initial-headers-sync peer
3212 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3213 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3214 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3215 // and we have others we could be using instead.
3216 // Note: If all our peers are inbound, then we won't
3217 // disconnect our sync peer for stalling; we have bigger
3218 // problems if we can't get any outbound peers.
3219 if (!pto->fWhitelisted) {
3220 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3221 pto->fDisconnect = true;
3222 return true;
3223 } else {
3224 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3225 // Reset the headers sync state so that we have a
3226 // chance to try downloading from a different peer.
3227 // Note: this will also result in at least one more
3228 // getheaders message to be sent to
3229 // this peer (eventually).
3230 state.fSyncStarted = false;
3231 nSyncStarted--;
3232 state.nHeadersSyncTimeout = 0;
3235 } else {
3236 // After we've caught up once, reset the timeout so we can't trigger
3237 // disconnect later.
3238 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3244 // Message: getdata (blocks)
3246 std::vector<CInv> vGetData;
3247 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3248 std::vector<const CBlockIndex*> vToDownload;
3249 NodeId staller = -1;
3250 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3251 for (const CBlockIndex *pindex : vToDownload) {
3252 uint32_t nFetchFlags = GetFetchFlags(pto);
3253 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3254 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3255 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3256 pindex->nHeight, pto->GetId());
3258 if (state.nBlocksInFlight == 0 && staller != -1) {
3259 if (State(staller)->nStallingSince == 0) {
3260 State(staller)->nStallingSince = nNow;
3261 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3267 // Message: getdata (non-blocks)
3269 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3271 const CInv& inv = (*pto->mapAskFor.begin()).second;
3272 if (!AlreadyHave(inv))
3274 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3275 vGetData.push_back(inv);
3276 if (vGetData.size() >= 1000)
3278 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3279 vGetData.clear();
3281 } else {
3282 //If we're not going to ask, don't expect a response.
3283 pto->setAskFor.erase(inv.hash);
3285 pto->mapAskFor.erase(pto->mapAskFor.begin());
3287 if (!vGetData.empty())
3288 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3291 // Message: feefilter
3293 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3294 if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3295 !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3296 CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3297 int64_t timeNow = GetTimeMicros();
3298 if (timeNow > pto->nextSendTimeFeeFilter) {
3299 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3300 static FeeFilterRounder filterRounder(default_feerate);
3301 CAmount filterToSend = filterRounder.round(currentFilter);
3302 // We always have a fee filter of at least minRelayTxFee
3303 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3304 if (filterToSend != pto->lastSentFeeFilter) {
3305 connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3306 pto->lastSentFeeFilter = filterToSend;
3308 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3310 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3311 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3312 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3313 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3314 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3318 return true;
3321 class CNetProcessingCleanup
3323 public:
3324 CNetProcessingCleanup() {}
3325 ~CNetProcessingCleanup() {
3326 // orphan transactions
3327 mapOrphanTransactions.clear();
3328 mapOrphanTransactionsByPrev.clear();
3330 } instance_of_cnetprocessingcleanup;