Do not send (potentially) invalid headers in response to getheaders
[bitcoinplatinum.git] / src / net_processing.cpp
blobb26caf377f4fd723f2da84fee1dede44544e527c
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 "reverse_iterator.h"
26 #include "tinyformat.h"
27 #include "txmempool.h"
28 #include "ui_interface.h"
29 #include "util.h"
30 #include "utilmoneystr.h"
31 #include "utilstrencodings.h"
32 #include "validationinterface.h"
34 #if defined(NDEBUG)
35 # error "Bitcoin cannot be compiled without assertions."
36 #endif
38 std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
40 struct IteratorComparator
42 template<typename I>
43 bool operator()(const I& a, const I& b)
45 return &(*a) < &(*b);
49 struct COrphanTx {
50 // When modifying, adapt the copy of this definition in tests/DoS_tests.
51 CTransactionRef tx;
52 NodeId fromPeer;
53 int64_t nTimeExpire;
55 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
56 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
57 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
59 static size_t vExtraTxnForCompactIt = 0;
60 static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
62 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
64 /// Age after which a stale block will no longer be served if requested as
65 /// protection against fingerprinting. Set to one month, denominated in seconds.
66 static const int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
68 /// Age after which a block is considered historical for purposes of rate
69 /// limiting block relay. Set to one week, denominated in seconds.
70 static const int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
72 // Internal stuff
73 namespace {
74 /** Number of nodes with fSyncStarted. */
75 int nSyncStarted = 0;
77 /**
78 * Sources of received blocks, saved to be able to send them reject
79 * messages or ban them when processing happens afterwards. Protected by
80 * cs_main.
81 * Set mapBlockSource[hash].second to false if the node should not be
82 * punished if the block is invalid.
84 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
86 /**
87 * Filter for transactions that were recently rejected by
88 * AcceptToMemoryPool. These are not rerequested until the chain tip
89 * changes, at which point the entire filter is reset. Protected by
90 * cs_main.
92 * Without this filter we'd be re-requesting txs from each of our peers,
93 * increasing bandwidth consumption considerably. For instance, with 100
94 * peers, half of which relay a tx we don't accept, that might be a 50x
95 * bandwidth increase. A flooding attacker attempting to roll-over the
96 * filter using minimum-sized, 60byte, transactions might manage to send
97 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
98 * two minute window to send invs to us.
100 * Decreasing the false positive rate is fairly cheap, so we pick one in a
101 * million to make it highly unlikely for users to have issues with this
102 * filter.
104 * Memory used: 1.3 MB
106 std::unique_ptr<CRollingBloomFilter> recentRejects;
107 uint256 hashRecentRejectsChainTip;
109 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
110 struct QueuedBlock {
111 uint256 hash;
112 const CBlockIndex* pindex; //!< Optional.
113 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
114 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
116 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
118 /** Stack of nodes which we have set to announce using compact blocks */
119 std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
121 /** Number of preferable block download peers. */
122 int nPreferredDownload = 0;
124 /** Number of peers from which we're downloading blocks. */
125 int nPeersWithValidatedDownloads = 0;
127 /** Number of outbound peers with m_chain_sync.m_protect. */
128 int g_outbound_peers_with_protect_from_disconnect = 0;
130 /** Relay map, protected by cs_main. */
131 typedef std::map<uint256, CTransactionRef> MapRelay;
132 MapRelay mapRelay;
133 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
134 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
135 } // namespace
137 namespace {
139 struct CBlockReject {
140 unsigned char chRejectCode;
141 std::string strRejectReason;
142 uint256 hashBlock;
146 * Maintain validation-specific state about nodes, protected by cs_main, instead
147 * by CNode's own locks. This simplifies asynchronous operation, where
148 * processing of incoming data is done after the ProcessMessage call returns,
149 * and we're no longer holding the node's locks.
151 struct CNodeState {
152 //! The peer's address
153 const CService address;
154 //! Whether we have a fully established connection.
155 bool fCurrentlyConnected;
156 //! Accumulated misbehaviour score for this peer.
157 int nMisbehavior;
158 //! Whether this peer should be disconnected and banned (unless whitelisted).
159 bool fShouldBan;
160 //! String name of this peer (debugging/logging purposes).
161 const std::string name;
162 //! List of asynchronously-determined block rejections to notify this peer about.
163 std::vector<CBlockReject> rejects;
164 //! The best known block we know this peer has announced.
165 const CBlockIndex *pindexBestKnownBlock;
166 //! The hash of the last unknown block this peer has announced.
167 uint256 hashLastUnknownBlock;
168 //! The last full block we both have.
169 const CBlockIndex *pindexLastCommonBlock;
170 //! The best header we have sent our peer.
171 const CBlockIndex *pindexBestHeaderSent;
172 //! Length of current-streak of unconnecting headers announcements
173 int nUnconnectingHeaders;
174 //! Whether we've started headers synchronization with this peer.
175 bool fSyncStarted;
176 //! When to potentially disconnect peer for stalling headers download
177 int64_t nHeadersSyncTimeout;
178 //! Since when we're stalling block download progress (in microseconds), or 0.
179 int64_t nStallingSince;
180 std::list<QueuedBlock> vBlocksInFlight;
181 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
182 int64_t nDownloadingSince;
183 int nBlocksInFlight;
184 int nBlocksInFlightValidHeaders;
185 //! Whether we consider this a preferred download peer.
186 bool fPreferredDownload;
187 //! Whether this peer wants invs or headers (when possible) for block announcements.
188 bool fPreferHeaders;
189 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
190 bool fPreferHeaderAndIDs;
192 * Whether this peer will send us cmpctblocks if we request them.
193 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
194 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
196 bool fProvidesHeaderAndIDs;
197 //! Whether this peer can give us witnesses
198 bool fHaveWitness;
199 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
200 bool fWantsCmpctWitness;
202 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
203 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
205 bool fSupportsDesiredCmpctVersion;
207 /** State used to enforce CHAIN_SYNC_TIMEOUT
208 * Only in effect for outbound, non-manual connections, with
209 * m_protect == false
210 * Algorithm: if a peer's best known block has less work than our tip,
211 * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
212 * - If at timeout their best known block now has more work than our tip
213 * when the timeout was set, then either reset the timeout or clear it
214 * (after comparing against our current tip's work)
215 * - If at timeout their best known block still has less work than our
216 * tip did when the timeout was set, then send a getheaders message,
217 * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
218 * If their best known block is still behind when that new timeout is
219 * reached, disconnect.
221 struct ChainSyncTimeoutState {
222 //! A timeout used for checking whether our peer has sufficiently synced
223 int64_t m_timeout;
224 //! A header with the work we require on our peer's chain
225 const CBlockIndex * m_work_header;
226 //! After timeout is reached, set to true after sending getheaders
227 bool m_sent_getheaders;
228 //! Whether this peer is protected from disconnection due to a bad/slow chain
229 bool m_protect;
232 ChainSyncTimeoutState m_chain_sync;
234 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
235 fCurrentlyConnected = false;
236 nMisbehavior = 0;
237 fShouldBan = false;
238 pindexBestKnownBlock = nullptr;
239 hashLastUnknownBlock.SetNull();
240 pindexLastCommonBlock = nullptr;
241 pindexBestHeaderSent = nullptr;
242 nUnconnectingHeaders = 0;
243 fSyncStarted = false;
244 nHeadersSyncTimeout = 0;
245 nStallingSince = 0;
246 nDownloadingSince = 0;
247 nBlocksInFlight = 0;
248 nBlocksInFlightValidHeaders = 0;
249 fPreferredDownload = false;
250 fPreferHeaders = false;
251 fPreferHeaderAndIDs = false;
252 fProvidesHeaderAndIDs = false;
253 fHaveWitness = false;
254 fWantsCmpctWitness = false;
255 fSupportsDesiredCmpctVersion = false;
256 m_chain_sync = { 0, nullptr, false, false };
260 /** Map maintaining per-node state. Requires cs_main. */
261 std::map<NodeId, CNodeState> mapNodeState;
263 // Requires cs_main.
264 CNodeState *State(NodeId pnode) {
265 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
266 if (it == mapNodeState.end())
267 return nullptr;
268 return &it->second;
271 void UpdatePreferredDownload(CNode* node, CNodeState* state)
273 nPreferredDownload -= state->fPreferredDownload;
275 // Whether this node should be marked as a preferred download node.
276 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
278 nPreferredDownload += state->fPreferredDownload;
281 void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
283 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
284 uint64_t nonce = pnode->GetLocalNonce();
285 int nNodeStartingHeight = pnode->GetMyStartingHeight();
286 NodeId nodeid = pnode->GetId();
287 CAddress addr = pnode->addr;
289 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
290 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
292 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
293 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
295 if (fLogIPs) {
296 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
297 } else {
298 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
302 // Requires cs_main.
303 // Returns a bool indicating whether we requested this block.
304 // Also used if a block was /not/ received and timed out or started with another peer
305 bool MarkBlockAsReceived(const uint256& hash) {
306 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
307 if (itInFlight != mapBlocksInFlight.end()) {
308 CNodeState *state = State(itInFlight->second.first);
309 assert(state != nullptr);
310 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
311 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
312 // Last validated block on the queue was received.
313 nPeersWithValidatedDownloads--;
315 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
316 // First block on the queue was received, update the start download time for the next one
317 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
319 state->vBlocksInFlight.erase(itInFlight->second.second);
320 state->nBlocksInFlight--;
321 state->nStallingSince = 0;
322 mapBlocksInFlight.erase(itInFlight);
323 return true;
325 return false;
328 // Requires cs_main.
329 // returns false, still setting pit, if the block was already in flight from the same peer
330 // pit will only be valid as long as the same cs_main lock is being held
331 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
332 CNodeState *state = State(nodeid);
333 assert(state != nullptr);
335 // Short-circuit most stuff in case its from the same node
336 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
337 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
338 if (pit) {
339 *pit = &itInFlight->second.second;
341 return false;
344 // Make sure it's not listed somewhere already.
345 MarkBlockAsReceived(hash);
347 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
348 {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
349 state->nBlocksInFlight++;
350 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
351 if (state->nBlocksInFlight == 1) {
352 // We're starting a block download (batch) from this peer.
353 state->nDownloadingSince = GetTimeMicros();
355 if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
356 nPeersWithValidatedDownloads++;
358 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
359 if (pit)
360 *pit = &itInFlight->second.second;
361 return true;
364 /** Check whether the last unknown block a peer advertised is not yet known. */
365 void ProcessBlockAvailability(NodeId nodeid) {
366 CNodeState *state = State(nodeid);
367 assert(state != nullptr);
369 if (!state->hashLastUnknownBlock.IsNull()) {
370 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
371 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
372 if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
373 state->pindexBestKnownBlock = itOld->second;
374 state->hashLastUnknownBlock.SetNull();
379 /** Update tracking information about which blocks a peer is assumed to have. */
380 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
381 CNodeState *state = State(nodeid);
382 assert(state != nullptr);
384 ProcessBlockAvailability(nodeid);
386 BlockMap::iterator it = mapBlockIndex.find(hash);
387 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
388 // An actually better block was announced.
389 if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
390 state->pindexBestKnownBlock = it->second;
391 } else {
392 // An unknown block was announced; just assume that the latest one is the best one.
393 state->hashLastUnknownBlock = hash;
397 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) {
398 AssertLockHeld(cs_main);
399 CNodeState* nodestate = State(nodeid);
400 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
401 // Never ask from peers who can't provide witnesses.
402 return;
404 if (nodestate->fProvidesHeaderAndIDs) {
405 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
406 if (*it == nodeid) {
407 lNodesAnnouncingHeaderAndIDs.erase(it);
408 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
409 return;
412 connman->ForNode(nodeid, [connman](CNode* pfrom){
413 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
414 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
415 // As per BIP152, we only get 3 of our peers to announce
416 // blocks using compact encodings.
417 connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
418 connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
419 return true;
421 lNodesAnnouncingHeaderAndIDs.pop_front();
423 connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
424 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
425 return true;
430 // Requires cs_main
431 bool CanDirectFetch(const Consensus::Params &consensusParams)
433 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
436 // Requires cs_main
437 bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
439 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
440 return true;
441 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
442 return true;
443 return false;
446 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
447 * at most count entries. */
448 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
449 if (count == 0)
450 return;
452 vBlocks.reserve(vBlocks.size() + count);
453 CNodeState *state = State(nodeid);
454 assert(state != nullptr);
456 // Make sure pindexBestKnownBlock is up to date, we'll need it.
457 ProcessBlockAvailability(nodeid);
459 if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
460 // This peer has nothing interesting.
461 return;
464 if (state->pindexLastCommonBlock == nullptr) {
465 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
466 // Guessing wrong in either direction is not a problem.
467 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
470 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
471 // of its current tip anymore. Go back enough to fix that.
472 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
473 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
474 return;
476 std::vector<const CBlockIndex*> vToFetch;
477 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
478 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
479 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
480 // download that next block if the window were 1 larger.
481 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
482 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
483 NodeId waitingfor = -1;
484 while (pindexWalk->nHeight < nMaxHeight) {
485 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
486 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
487 // as iterating over ~100 CBlockIndex* entries anyway.
488 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
489 vToFetch.resize(nToFetch);
490 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
491 vToFetch[nToFetch - 1] = pindexWalk;
492 for (unsigned int i = nToFetch - 1; i > 0; i--) {
493 vToFetch[i - 1] = vToFetch[i]->pprev;
496 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
497 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
498 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
499 // already part of our chain (and therefore don't need it even if pruned).
500 for (const CBlockIndex* pindex : vToFetch) {
501 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
502 // We consider the chain that this peer is on invalid.
503 return;
505 if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
506 // We wouldn't download this block or its descendants from this peer.
507 return;
509 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
510 if (pindex->nChainTx)
511 state->pindexLastCommonBlock = pindex;
512 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
513 // The block is not already downloaded, and not yet in flight.
514 if (pindex->nHeight > nWindowEnd) {
515 // We reached the end of the window.
516 if (vBlocks.size() == 0 && waitingfor != nodeid) {
517 // We aren't able to fetch anything, but we would be if the download window was one larger.
518 nodeStaller = waitingfor;
520 return;
522 vBlocks.push_back(pindex);
523 if (vBlocks.size() == count) {
524 return;
526 } else if (waitingfor == -1) {
527 // This is the first already-in-flight block.
528 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
534 } // namespace
536 // Returns true for outbound peers, excluding manual connections, feelers, and
537 // one-shots
538 bool IsOutboundDisconnectionCandidate(const CNode *node)
540 return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
543 void PeerLogicValidation::InitializeNode(CNode *pnode) {
544 CAddress addr = pnode->addr;
545 std::string addrName = pnode->GetAddrName();
546 NodeId nodeid = pnode->GetId();
548 LOCK(cs_main);
549 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
551 if(!pnode->fInbound)
552 PushNodeVersion(pnode, connman, GetTime());
555 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
556 fUpdateConnectionTime = false;
557 LOCK(cs_main);
558 CNodeState *state = State(nodeid);
559 assert(state != nullptr);
561 if (state->fSyncStarted)
562 nSyncStarted--;
564 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
565 fUpdateConnectionTime = true;
568 for (const QueuedBlock& entry : state->vBlocksInFlight) {
569 mapBlocksInFlight.erase(entry.hash);
571 EraseOrphansFor(nodeid);
572 nPreferredDownload -= state->fPreferredDownload;
573 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
574 assert(nPeersWithValidatedDownloads >= 0);
575 g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
576 assert(g_outbound_peers_with_protect_from_disconnect >= 0);
578 mapNodeState.erase(nodeid);
580 if (mapNodeState.empty()) {
581 // Do a consistency check after the last peer is removed.
582 assert(mapBlocksInFlight.empty());
583 assert(nPreferredDownload == 0);
584 assert(nPeersWithValidatedDownloads == 0);
585 assert(g_outbound_peers_with_protect_from_disconnect == 0);
587 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
590 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
591 LOCK(cs_main);
592 CNodeState *state = State(nodeid);
593 if (state == nullptr)
594 return false;
595 stats.nMisbehavior = state->nMisbehavior;
596 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
597 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
598 for (const QueuedBlock& queue : state->vBlocksInFlight) {
599 if (queue.pindex)
600 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
602 return true;
605 //////////////////////////////////////////////////////////////////////////////
607 // mapOrphanTransactions
610 void AddToCompactExtraTransactions(const CTransactionRef& tx)
612 size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
613 if (max_extra_txn <= 0)
614 return;
615 if (!vExtraTxnForCompact.size())
616 vExtraTxnForCompact.resize(max_extra_txn);
617 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
618 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
621 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
623 const uint256& hash = tx->GetHash();
624 if (mapOrphanTransactions.count(hash))
625 return false;
627 // Ignore big transactions, to avoid a
628 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
629 // large transaction with a missing parent then we assume
630 // it will rebroadcast it later, after the parent transaction(s)
631 // have been mined or received.
632 // 100 orphans, each of which is at most 99,999 bytes big is
633 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
634 unsigned int sz = GetTransactionWeight(*tx);
635 if (sz >= MAX_STANDARD_TX_WEIGHT)
637 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
638 return false;
641 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
642 assert(ret.second);
643 for (const CTxIn& txin : tx->vin) {
644 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
647 AddToCompactExtraTransactions(tx);
649 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
650 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
651 return true;
654 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
656 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
657 if (it == mapOrphanTransactions.end())
658 return 0;
659 for (const CTxIn& txin : it->second.tx->vin)
661 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
662 if (itPrev == mapOrphanTransactionsByPrev.end())
663 continue;
664 itPrev->second.erase(it);
665 if (itPrev->second.empty())
666 mapOrphanTransactionsByPrev.erase(itPrev);
668 mapOrphanTransactions.erase(it);
669 return 1;
672 void EraseOrphansFor(NodeId peer)
674 int nErased = 0;
675 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
676 while (iter != mapOrphanTransactions.end())
678 std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
679 if (maybeErase->second.fromPeer == peer)
681 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
684 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
688 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
690 unsigned int nEvicted = 0;
691 static int64_t nNextSweep;
692 int64_t nNow = GetTime();
693 if (nNextSweep <= nNow) {
694 // Sweep out expired orphan pool entries:
695 int nErased = 0;
696 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
697 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
698 while (iter != mapOrphanTransactions.end())
700 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
701 if (maybeErase->second.nTimeExpire <= nNow) {
702 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
703 } else {
704 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
707 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
708 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
709 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
711 while (mapOrphanTransactions.size() > nMaxOrphans)
713 // Evict a random orphan:
714 uint256 randomhash = GetRandHash();
715 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
716 if (it == mapOrphanTransactions.end())
717 it = mapOrphanTransactions.begin();
718 EraseOrphanTx(it->first);
719 ++nEvicted;
721 return nEvicted;
724 // Requires cs_main.
725 void Misbehaving(NodeId pnode, int howmuch)
727 if (howmuch == 0)
728 return;
730 CNodeState *state = State(pnode);
731 if (state == nullptr)
732 return;
734 state->nMisbehavior += howmuch;
735 int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
736 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
738 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
739 state->fShouldBan = true;
740 } else
741 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
751 //////////////////////////////////////////////////////////////////////////////
753 // blockchain -> download logic notification
756 // To prevent fingerprinting attacks, only send blocks/headers outside of the
757 // active chain if they are no more than a month older (both in time, and in
758 // best equivalent proof of work) than the best header chain we know about and
759 // we fully-validated them at some point.
760 static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
762 AssertLockHeld(cs_main);
763 if (chainActive.Contains(pindex)) return true;
764 return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
765 (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
766 (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
769 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
770 // Initialize global variables that cannot be constructed at startup.
771 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
774 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
775 LOCK(cs_main);
777 std::vector<uint256> vOrphanErase;
779 for (const CTransactionRef& ptx : pblock->vtx) {
780 const CTransaction& tx = *ptx;
782 // Which orphan pool entries must we evict?
783 for (const auto& txin : tx.vin) {
784 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
785 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
786 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
787 const CTransaction& orphanTx = *(*mi)->second.tx;
788 const uint256& orphanHash = orphanTx.GetHash();
789 vOrphanErase.push_back(orphanHash);
794 // Erase orphan transactions include or precluded by this block
795 if (vOrphanErase.size()) {
796 int nErased = 0;
797 for (uint256 &orphanHash : vOrphanErase) {
798 nErased += EraseOrphanTx(orphanHash);
800 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
804 // All of the following cache a recent block, and are protected by cs_most_recent_block
805 static CCriticalSection cs_most_recent_block;
806 static std::shared_ptr<const CBlock> most_recent_block;
807 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
808 static uint256 most_recent_block_hash;
809 static bool fWitnessesPresentInMostRecentCompactBlock;
811 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
812 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
813 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
815 LOCK(cs_main);
817 static int nHighestFastAnnounce = 0;
818 if (pindex->nHeight <= nHighestFastAnnounce)
819 return;
820 nHighestFastAnnounce = pindex->nHeight;
822 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
823 uint256 hashBlock(pblock->GetHash());
826 LOCK(cs_most_recent_block);
827 most_recent_block_hash = hashBlock;
828 most_recent_block = pblock;
829 most_recent_compact_block = pcmpctblock;
830 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
833 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
834 // TODO: Avoid the repeated-serialization here
835 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
836 return;
837 ProcessBlockAvailability(pnode->GetId());
838 CNodeState &state = *State(pnode->GetId());
839 // If the peer has, or we announced to them the previous block already,
840 // but we don't think they have this one, go ahead and announce it
841 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
842 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
844 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
845 hashBlock.ToString(), pnode->GetId());
846 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
847 state.pindexBestHeaderSent = pindex;
852 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
853 const int nNewHeight = pindexNew->nHeight;
854 connman->SetBestHeight(nNewHeight);
856 if (!fInitialDownload) {
857 // Find the hashes of all blocks that weren't previously in the best chain.
858 std::vector<uint256> vHashes;
859 const CBlockIndex *pindexToAnnounce = pindexNew;
860 while (pindexToAnnounce != pindexFork) {
861 vHashes.push_back(pindexToAnnounce->GetBlockHash());
862 pindexToAnnounce = pindexToAnnounce->pprev;
863 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
864 // Limit announcements in case of a huge reorganization.
865 // Rely on the peer's synchronization mechanism in that case.
866 break;
869 // Relay inventory, but don't relay old inventory during initial block download.
870 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
871 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
872 for (const uint256& hash : reverse_iterate(vHashes)) {
873 pnode->PushBlockHash(hash);
877 connman->WakeMessageHandler();
880 nTimeBestReceived = GetTime();
883 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
884 LOCK(cs_main);
886 const uint256 hash(block.GetHash());
887 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
889 int nDoS = 0;
890 if (state.IsInvalid(nDoS)) {
891 // Don't send reject message with code 0 or an internal reject code.
892 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
893 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
894 State(it->second.first)->rejects.push_back(reject);
895 if (nDoS > 0 && it->second.second)
896 Misbehaving(it->second.first, nDoS);
899 // Check that:
900 // 1. The block is valid
901 // 2. We're not in initial block download
902 // 3. This is currently the best block we're aware of. We haven't updated
903 // the tip yet so we have no way to check this directly here. Instead we
904 // just check that there are currently no other blocks in flight.
905 else if (state.IsValid() &&
906 !IsInitialBlockDownload() &&
907 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
908 if (it != mapBlockSource.end()) {
909 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
912 if (it != mapBlockSource.end())
913 mapBlockSource.erase(it);
916 //////////////////////////////////////////////////////////////////////////////
918 // Messages
922 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
924 switch (inv.type)
926 case MSG_TX:
927 case MSG_WITNESS_TX:
929 assert(recentRejects);
930 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
932 // If the chain tip has changed previously rejected transactions
933 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
934 // or a double-spend. Reset the rejects filter and give those
935 // txs a second chance.
936 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
937 recentRejects->reset();
940 return recentRejects->contains(inv.hash) ||
941 mempool.exists(inv.hash) ||
942 mapOrphanTransactions.count(inv.hash) ||
943 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
944 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
946 case MSG_BLOCK:
947 case MSG_WITNESS_BLOCK:
948 return mapBlockIndex.count(inv.hash);
950 // Don't know what it is, just say we already got one
951 return true;
954 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
956 CInv inv(MSG_TX, tx.GetHash());
957 connman->ForEachNode([&inv](CNode* pnode)
959 pnode->PushInventory(inv);
963 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
965 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
967 // Relay to a limited number of other nodes
968 // Use deterministic randomness to send to the same nodes for 24 hours
969 // at a time so the addrKnowns of the chosen nodes prevent repeats
970 uint64_t hashAddr = addr.GetHash();
971 const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
972 FastRandomContext insecure_rand;
974 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
975 assert(nRelayNodes <= best.size());
977 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
978 if (pnode->nVersion >= CADDR_TIME_VERSION) {
979 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
980 for (unsigned int i = 0; i < nRelayNodes; i++) {
981 if (hashKey > best[i].first) {
982 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
983 best[i] = std::make_pair(hashKey, pnode);
984 break;
990 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
991 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
992 best[i].second->PushAddress(addr, insecure_rand);
996 connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
999 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1001 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1002 std::vector<CInv> vNotFound;
1003 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1004 LOCK(cs_main);
1006 while (it != pfrom->vRecvGetData.end()) {
1007 // Don't bother if send buffer is too full to respond anyway
1008 if (pfrom->fPauseSend)
1009 break;
1011 const CInv &inv = *it;
1013 if (interruptMsgProc)
1014 return;
1016 it++;
1018 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1020 bool send = false;
1021 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1022 std::shared_ptr<const CBlock> a_recent_block;
1023 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1024 bool fWitnessesPresentInARecentCompactBlock;
1026 LOCK(cs_most_recent_block);
1027 a_recent_block = most_recent_block;
1028 a_recent_compact_block = most_recent_compact_block;
1029 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1031 if (mi != mapBlockIndex.end())
1033 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1034 mi->second->IsValid(BLOCK_VALID_TREE)) {
1035 // If we have the block and all of its parents, but have not yet validated it,
1036 // we might be in the middle of connecting it (ie in the unlock of cs_main
1037 // before ActivateBestChain but after AcceptBlock).
1038 // In this case, we need to run ActivateBestChain prior to checking the relay
1039 // conditions below.
1040 CValidationState dummy;
1041 ActivateBestChain(dummy, Params(), a_recent_block);
1043 send = BlockRequestAllowed(mi->second, consensusParams);
1044 if (!send) {
1045 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1048 // disconnect node in case we have reached the outbound limit for serving historical blocks
1049 // never disconnect whitelisted nodes
1050 if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1052 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1054 //disconnect node
1055 pfrom->fDisconnect = true;
1056 send = false;
1058 // Pruned nodes may have deleted the block, so check whether
1059 // it's available before trying to send.
1060 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1062 std::shared_ptr<const CBlock> pblock;
1063 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1064 pblock = a_recent_block;
1065 } else {
1066 // Send block from disk
1067 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1068 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1069 assert(!"cannot load block from disk");
1070 pblock = pblockRead;
1072 if (inv.type == MSG_BLOCK)
1073 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1074 else if (inv.type == MSG_WITNESS_BLOCK)
1075 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1076 else if (inv.type == MSG_FILTERED_BLOCK)
1078 bool sendMerkleBlock = false;
1079 CMerkleBlock merkleBlock;
1081 LOCK(pfrom->cs_filter);
1082 if (pfrom->pfilter) {
1083 sendMerkleBlock = true;
1084 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1087 if (sendMerkleBlock) {
1088 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1089 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1090 // This avoids hurting performance by pointlessly requiring a round-trip
1091 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1092 // they must either disconnect and retry or request the full block.
1093 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1094 // however we MUST always provide at least what the remote peer needs
1095 typedef std::pair<unsigned int, uint256> PairType;
1096 for (PairType& pair : merkleBlock.vMatchedTxn)
1097 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1099 // else
1100 // no response
1102 else if (inv.type == MSG_CMPCT_BLOCK)
1104 // If a peer is asking for old blocks, we're almost guaranteed
1105 // they won't have a useful mempool to match against a compact block,
1106 // and we don't feel like constructing the object for them, so
1107 // instead we respond with the full, non-compact block.
1108 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1109 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1110 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1111 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1112 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1113 } else {
1114 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1115 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1117 } else {
1118 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1122 // Trigger the peer node to send a getblocks request for the next batch of inventory
1123 if (inv.hash == pfrom->hashContinue)
1125 // Bypass PushInventory, this must send even if redundant,
1126 // and we want it right after the last block so they don't
1127 // wait for other stuff first.
1128 std::vector<CInv> vInv;
1129 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1130 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1131 pfrom->hashContinue.SetNull();
1135 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1137 // Send stream from relay memory
1138 bool push = false;
1139 auto mi = mapRelay.find(inv.hash);
1140 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1141 if (mi != mapRelay.end()) {
1142 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1143 push = true;
1144 } else if (pfrom->timeLastMempoolReq) {
1145 auto txinfo = mempool.info(inv.hash);
1146 // To protect privacy, do not answer getdata using the mempool when
1147 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1148 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1149 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1150 push = true;
1153 if (!push) {
1154 vNotFound.push_back(inv);
1158 // Track requests for our stuff.
1159 GetMainSignals().Inventory(inv.hash);
1161 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1162 break;
1166 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1168 if (!vNotFound.empty()) {
1169 // Let the peer know that we didn't find what it asked for, so it doesn't
1170 // have to wait around forever. Currently only SPV clients actually care
1171 // about this message: it's needed when they are recursively walking the
1172 // dependencies of relevant unconfirmed transactions. SPV clients want to
1173 // do that because they want to know about (and store and rebroadcast and
1174 // risk analyze) the dependencies of transactions relevant to them, without
1175 // having to download the entire memory pool.
1176 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1180 uint32_t GetFetchFlags(CNode* pfrom) {
1181 uint32_t nFetchFlags = 0;
1182 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1183 nFetchFlags |= MSG_WITNESS_FLAG;
1185 return nFetchFlags;
1188 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
1189 BlockTransactions resp(req);
1190 for (size_t i = 0; i < req.indexes.size(); i++) {
1191 if (req.indexes[i] >= block.vtx.size()) {
1192 LOCK(cs_main);
1193 Misbehaving(pfrom->GetId(), 100);
1194 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1195 return;
1197 resp.txn[i] = block.vtx[req.indexes[i]];
1199 LOCK(cs_main);
1200 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1201 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1202 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1205 bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
1207 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1208 size_t nCount = headers.size();
1210 if (nCount == 0) {
1211 // Nothing interesting. Stop asking this peers for more headers.
1212 return true;
1215 const CBlockIndex *pindexLast = nullptr;
1217 LOCK(cs_main);
1218 CNodeState *nodestate = State(pfrom->GetId());
1220 // If this looks like it could be a block announcement (nCount <
1221 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1222 // don't connect:
1223 // - Send a getheaders message in response to try to connect the chain.
1224 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1225 // don't connect before giving DoS points
1226 // - Once a headers message is received that is valid and does connect,
1227 // nUnconnectingHeaders gets reset back to 0.
1228 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1229 nodestate->nUnconnectingHeaders++;
1230 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1231 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1232 headers[0].GetHash().ToString(),
1233 headers[0].hashPrevBlock.ToString(),
1234 pindexBestHeader->nHeight,
1235 pfrom->GetId(), nodestate->nUnconnectingHeaders);
1236 // Set hashLastUnknownBlock for this peer, so that if we
1237 // eventually get the headers - even from a different peer -
1238 // we can use this peer to download.
1239 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
1241 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
1242 Misbehaving(pfrom->GetId(), 20);
1244 return true;
1247 uint256 hashLastBlock;
1248 for (const CBlockHeader& header : headers) {
1249 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
1250 Misbehaving(pfrom->GetId(), 20);
1251 return error("non-continuous headers sequence");
1253 hashLastBlock = header.GetHash();
1257 CValidationState state;
1258 CBlockHeader first_invalid_header;
1259 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) {
1260 int nDoS;
1261 if (state.IsInvalid(nDoS)) {
1262 if (nDoS > 0) {
1263 LOCK(cs_main);
1264 Misbehaving(pfrom->GetId(), nDoS);
1266 if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
1267 // Goal: don't allow outbound peers to use up our outbound
1268 // connection slots if they are on incompatible chains.
1270 // We ask the caller to set punish_invalid appropriately based
1271 // on the peer and the method of header delivery (compact
1272 // blocks are allowed to be invalid in some circumstances,
1273 // under BIP 152).
1274 // Here, we try to detect the narrow situation that we have a
1275 // valid block header (ie it was valid at the time the header
1276 // was received, and hence stored in mapBlockIndex) but know the
1277 // block is invalid, and that a peer has announced that same
1278 // block as being on its active chain.
1279 // Disconnect the peer in such a situation.
1281 // Note: if the header that is invalid was not accepted to our
1282 // mapBlockIndex at all, that may also be grounds for
1283 // disconnecting the peer, as the chain they are on is likely
1284 // to be incompatible. However, there is a circumstance where
1285 // that does not hold: if the header's timestamp is more than
1286 // 2 hours ahead of our current time. In that case, the header
1287 // may become valid in the future, and we don't want to
1288 // disconnect a peer merely for serving us one too-far-ahead
1289 // block header, to prevent an attacker from splitting the
1290 // network by mining a block right at the 2 hour boundary.
1292 // TODO: update the DoS logic (or, rather, rewrite the
1293 // DoS-interface between validation and net_processing) so that
1294 // the interface is cleaner, and so that we disconnect on all the
1295 // reasons that a peer's headers chain is incompatible
1296 // with ours (eg block->nVersion softforks, MTP violations,
1297 // etc), and not just the duplicate-invalid case.
1298 pfrom->fDisconnect = true;
1300 return error("invalid header received");
1305 LOCK(cs_main);
1306 CNodeState *nodestate = State(pfrom->GetId());
1307 if (nodestate->nUnconnectingHeaders > 0) {
1308 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
1310 nodestate->nUnconnectingHeaders = 0;
1312 assert(pindexLast);
1313 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1315 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1316 // because it is set in UpdateBlockAvailability. Some nullptr checks
1317 // are still present, however, as belt-and-suspenders.
1319 if (nCount == MAX_HEADERS_RESULTS) {
1320 // Headers message had its maximum size; the peer may have more headers.
1321 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1322 // from there instead.
1323 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1324 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
1327 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
1328 // If this set of headers is valid and ends in a block with at least as
1329 // much work as our tip, download as much as possible.
1330 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
1331 std::vector<const CBlockIndex*> vToFetch;
1332 const CBlockIndex *pindexWalk = pindexLast;
1333 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1334 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1335 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
1336 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
1337 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
1338 // We don't have this block, and it's not yet in flight.
1339 vToFetch.push_back(pindexWalk);
1341 pindexWalk = pindexWalk->pprev;
1343 // If pindexWalk still isn't on our main chain, we're looking at a
1344 // very large reorg at a time we think we're close to caught up to
1345 // the main chain -- this shouldn't really happen. Bail out on the
1346 // direct fetch and rely on parallel download instead.
1347 if (!chainActive.Contains(pindexWalk)) {
1348 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
1349 pindexLast->GetBlockHash().ToString(),
1350 pindexLast->nHeight);
1351 } else {
1352 std::vector<CInv> vGetData;
1353 // Download as much as possible, from earliest to latest.
1354 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
1355 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1356 // Can't download any more from this peer
1357 break;
1359 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1360 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
1361 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
1362 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1363 pindex->GetBlockHash().ToString(), pfrom->GetId());
1365 if (vGetData.size() > 1) {
1366 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1367 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
1369 if (vGetData.size() > 0) {
1370 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1371 // In any case, we want to download using a compact block, not a regular one
1372 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
1374 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
1378 // If we're in IBD, we want outbound peers that will serve us a useful
1379 // chain. Disconnect peers that are on chains with insufficient work.
1380 if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
1381 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1382 // headers to fetch from this peer.
1383 if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1384 // This peer has too little work on their headers chain to help
1385 // us sync -- disconnect if using an outbound slot (unless
1386 // whitelisted or addnode).
1387 // Note: We compare their tip to nMinimumChainWork (rather than
1388 // chainActive.Tip()) because we won't start block download
1389 // until we have a headers chain that has at least
1390 // nMinimumChainWork, even if a peer has a chain past our tip,
1391 // as an anti-DoS measure.
1392 if (IsOutboundDisconnectionCandidate(pfrom)) {
1393 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
1394 pfrom->fDisconnect = true;
1399 if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
1400 // If this is an outbound peer, check to see if we should protect
1401 // it from the bad/lagging chain logic.
1402 if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) {
1403 nodestate->m_chain_sync.m_protect = true;
1404 ++g_outbound_peers_with_protect_from_disconnect;
1409 return true;
1412 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1414 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1415 if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
1417 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1418 return true;
1422 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1423 (strCommand == NetMsgType::FILTERLOAD ||
1424 strCommand == NetMsgType::FILTERADD))
1426 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1427 LOCK(cs_main);
1428 Misbehaving(pfrom->GetId(), 100);
1429 return false;
1430 } else {
1431 pfrom->fDisconnect = true;
1432 return false;
1436 if (strCommand == NetMsgType::REJECT)
1438 if (LogAcceptCategory(BCLog::NET)) {
1439 try {
1440 std::string strMsg; unsigned char ccode; std::string strReason;
1441 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1443 std::ostringstream ss;
1444 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1446 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1448 uint256 hash;
1449 vRecv >> hash;
1450 ss << ": hash " << hash.ToString();
1452 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1453 } catch (const std::ios_base::failure&) {
1454 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1455 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1460 else if (strCommand == NetMsgType::VERSION)
1462 // Each connection can only send one version message
1463 if (pfrom->nVersion != 0)
1465 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1466 LOCK(cs_main);
1467 Misbehaving(pfrom->GetId(), 1);
1468 return false;
1471 int64_t nTime;
1472 CAddress addrMe;
1473 CAddress addrFrom;
1474 uint64_t nNonce = 1;
1475 uint64_t nServiceInt;
1476 ServiceFlags nServices;
1477 int nVersion;
1478 int nSendVersion;
1479 std::string strSubVer;
1480 std::string cleanSubVer;
1481 int nStartingHeight = -1;
1482 bool fRelay = true;
1484 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1485 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1486 nServices = ServiceFlags(nServiceInt);
1487 if (!pfrom->fInbound)
1489 connman->SetServices(pfrom->addr, nServices);
1491 if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
1493 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
1494 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1495 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
1496 pfrom->fDisconnect = true;
1497 return false;
1500 if (nServices & ((1 << 7) | (1 << 5))) {
1501 if (GetTime() < 1533096000) {
1502 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1503 // These bits have been used as a flag to indicate that a node is running incompatible
1504 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1505 // based on these service bits, at least for a while.
1506 pfrom->fDisconnect = true;
1507 return false;
1511 if (nVersion < MIN_PEER_PROTO_VERSION)
1513 // disconnect from peers older than this proto version
1514 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1515 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1516 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1517 pfrom->fDisconnect = true;
1518 return false;
1521 if (nVersion == 10300)
1522 nVersion = 300;
1523 if (!vRecv.empty())
1524 vRecv >> addrFrom >> nNonce;
1525 if (!vRecv.empty()) {
1526 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1527 cleanSubVer = SanitizeString(strSubVer);
1529 if (!vRecv.empty()) {
1530 vRecv >> nStartingHeight;
1532 if (!vRecv.empty())
1533 vRecv >> fRelay;
1534 // Disconnect if we connected to ourself
1535 if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
1537 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1538 pfrom->fDisconnect = true;
1539 return true;
1542 if (pfrom->fInbound && addrMe.IsRoutable())
1544 SeenLocal(addrMe);
1547 // Be shy and don't send version until we hear
1548 if (pfrom->fInbound)
1549 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1551 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1553 pfrom->nServices = nServices;
1554 pfrom->SetAddrLocal(addrMe);
1556 LOCK(pfrom->cs_SubVer);
1557 pfrom->strSubVer = strSubVer;
1558 pfrom->cleanSubVer = cleanSubVer;
1560 pfrom->nStartingHeight = nStartingHeight;
1561 pfrom->fClient = !(nServices & NODE_NETWORK);
1563 LOCK(pfrom->cs_filter);
1564 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1567 // Change version
1568 pfrom->SetSendVersion(nSendVersion);
1569 pfrom->nVersion = nVersion;
1571 if((nServices & NODE_WITNESS))
1573 LOCK(cs_main);
1574 State(pfrom->GetId())->fHaveWitness = true;
1577 // Potentially mark this peer as a preferred download peer.
1579 LOCK(cs_main);
1580 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1583 if (!pfrom->fInbound)
1585 // Advertise our address
1586 if (fListen && !IsInitialBlockDownload())
1588 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1589 FastRandomContext insecure_rand;
1590 if (addr.IsRoutable())
1592 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1593 pfrom->PushAddress(addr, insecure_rand);
1594 } else if (IsPeerAddrLocalGood(pfrom)) {
1595 addr.SetIP(addrMe);
1596 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1597 pfrom->PushAddress(addr, insecure_rand);
1601 // Get recent addresses
1602 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
1604 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1605 pfrom->fGetAddr = true;
1607 connman->MarkAddressGood(pfrom->addr);
1610 std::string remoteAddr;
1611 if (fLogIPs)
1612 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1614 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1615 cleanSubVer, pfrom->nVersion,
1616 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1617 remoteAddr);
1619 int64_t nTimeOffset = nTime - GetTime();
1620 pfrom->nTimeOffset = nTimeOffset;
1621 AddTimeData(pfrom->addr, nTimeOffset);
1623 // If the peer is old enough to have the old alert system, send it the final alert.
1624 if (pfrom->nVersion <= 70012) {
1625 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1626 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1629 // Feeler connections exist only to verify if address is online.
1630 if (pfrom->fFeeler) {
1631 assert(pfrom->fInbound == false);
1632 pfrom->fDisconnect = true;
1634 return true;
1638 else if (pfrom->nVersion == 0)
1640 // Must have a version message before anything else
1641 LOCK(cs_main);
1642 Misbehaving(pfrom->GetId(), 1);
1643 return false;
1646 // At this point, the outgoing message serialization version can't change.
1647 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1649 if (strCommand == NetMsgType::VERACK)
1651 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1653 if (!pfrom->fInbound) {
1654 // Mark this node as currently connected, so we update its timestamp later.
1655 LOCK(cs_main);
1656 State(pfrom->GetId())->fCurrentlyConnected = true;
1659 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1660 // Tell our peer we prefer to receive headers rather than inv's
1661 // We send this to non-NODE NETWORK peers as well, because even
1662 // non-NODE NETWORK peers can announce blocks (such as pruning
1663 // nodes)
1664 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1666 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1667 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1668 // However, we do not request new block announcements using
1669 // cmpctblock messages.
1670 // We send this to non-NODE NETWORK peers as well, because
1671 // they may wish to request compact blocks from us
1672 bool fAnnounceUsingCMPCTBLOCK = false;
1673 uint64_t nCMPCTBLOCKVersion = 2;
1674 if (pfrom->GetLocalServices() & NODE_WITNESS)
1675 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1676 nCMPCTBLOCKVersion = 1;
1677 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1679 pfrom->fSuccessfullyConnected = true;
1682 else if (!pfrom->fSuccessfullyConnected)
1684 // Must have a verack message before anything else
1685 LOCK(cs_main);
1686 Misbehaving(pfrom->GetId(), 1);
1687 return false;
1690 else if (strCommand == NetMsgType::ADDR)
1692 std::vector<CAddress> vAddr;
1693 vRecv >> vAddr;
1695 // Don't want addr from older versions unless seeding
1696 if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
1697 return true;
1698 if (vAddr.size() > 1000)
1700 LOCK(cs_main);
1701 Misbehaving(pfrom->GetId(), 20);
1702 return error("message addr size() = %u", vAddr.size());
1705 // Store the new addresses
1706 std::vector<CAddress> vAddrOk;
1707 int64_t nNow = GetAdjustedTime();
1708 int64_t nSince = nNow - 10 * 60;
1709 for (CAddress& addr : vAddr)
1711 if (interruptMsgProc)
1712 return true;
1714 // We only bother storing full nodes, though this may include
1715 // things which we would not make an outbound connection to, in
1716 // part because we may make feeler connections to them.
1717 if (!MayHaveUsefulAddressDB(addr.nServices))
1718 continue;
1720 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1721 addr.nTime = nNow - 5 * 24 * 60 * 60;
1722 pfrom->AddAddressKnown(addr);
1723 bool fReachable = IsReachable(addr);
1724 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1726 // Relay to a limited number of other nodes
1727 RelayAddress(addr, fReachable, connman);
1729 // Do not store addresses outside our network
1730 if (fReachable)
1731 vAddrOk.push_back(addr);
1733 connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1734 if (vAddr.size() < 1000)
1735 pfrom->fGetAddr = false;
1736 if (pfrom->fOneShot)
1737 pfrom->fDisconnect = true;
1740 else if (strCommand == NetMsgType::SENDHEADERS)
1742 LOCK(cs_main);
1743 State(pfrom->GetId())->fPreferHeaders = true;
1746 else if (strCommand == NetMsgType::SENDCMPCT)
1748 bool fAnnounceUsingCMPCTBLOCK = false;
1749 uint64_t nCMPCTBLOCKVersion = 0;
1750 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1751 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1752 LOCK(cs_main);
1753 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1754 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1755 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1756 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1758 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1759 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1760 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1761 if (pfrom->GetLocalServices() & NODE_WITNESS)
1762 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1763 else
1764 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1770 else if (strCommand == NetMsgType::INV)
1772 std::vector<CInv> vInv;
1773 vRecv >> vInv;
1774 if (vInv.size() > MAX_INV_SZ)
1776 LOCK(cs_main);
1777 Misbehaving(pfrom->GetId(), 20);
1778 return error("message inv size() = %u", vInv.size());
1781 bool fBlocksOnly = !fRelayTxes;
1783 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1784 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1785 fBlocksOnly = false;
1787 LOCK(cs_main);
1789 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1791 for (CInv &inv : vInv)
1793 if (interruptMsgProc)
1794 return true;
1796 bool fAlreadyHave = AlreadyHave(inv);
1797 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1799 if (inv.type == MSG_TX) {
1800 inv.type |= nFetchFlags;
1803 if (inv.type == MSG_BLOCK) {
1804 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1805 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1806 // We used to request the full block here, but since headers-announcements are now the
1807 // primary method of announcement on the network, and since, in the case that a node
1808 // fell back to inv we probably have a reorg which we should get the headers for first,
1809 // we now only provide a getheaders response here. When we receive the headers, we will
1810 // then ask for the blocks we need.
1811 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1812 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1815 else
1817 pfrom->AddInventoryKnown(inv);
1818 if (fBlocksOnly) {
1819 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1820 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1821 pfrom->AskFor(inv);
1825 // Track requests for our stuff
1826 GetMainSignals().Inventory(inv.hash);
1831 else if (strCommand == NetMsgType::GETDATA)
1833 std::vector<CInv> vInv;
1834 vRecv >> vInv;
1835 if (vInv.size() > MAX_INV_SZ)
1837 LOCK(cs_main);
1838 Misbehaving(pfrom->GetId(), 20);
1839 return error("message getdata size() = %u", vInv.size());
1842 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1844 if (vInv.size() > 0) {
1845 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1848 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1849 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1853 else if (strCommand == NetMsgType::GETBLOCKS)
1855 CBlockLocator locator;
1856 uint256 hashStop;
1857 vRecv >> locator >> hashStop;
1859 // We might have announced the currently-being-connected tip using a
1860 // compact block, which resulted in the peer sending a getblocks
1861 // request, which we would otherwise respond to without the new block.
1862 // To avoid this situation we simply verify that we are on our best
1863 // known chain now. This is super overkill, but we handle it better
1864 // for getheaders requests, and there are no known nodes which support
1865 // compact blocks but still use getblocks to request blocks.
1867 std::shared_ptr<const CBlock> a_recent_block;
1869 LOCK(cs_most_recent_block);
1870 a_recent_block = most_recent_block;
1872 CValidationState dummy;
1873 ActivateBestChain(dummy, Params(), a_recent_block);
1876 LOCK(cs_main);
1878 // Find the last block the caller has in the main chain
1879 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1881 // Send the rest of the chain
1882 if (pindex)
1883 pindex = chainActive.Next(pindex);
1884 int nLimit = 500;
1885 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());
1886 for (; pindex; pindex = chainActive.Next(pindex))
1888 if (pindex->GetBlockHash() == hashStop)
1890 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1891 break;
1893 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1894 // for some reasonable time window (1 hour) that block relay might require.
1895 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1896 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1898 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1899 break;
1901 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1902 if (--nLimit <= 0)
1904 // When this block is requested, we'll send an inv that'll
1905 // trigger the peer to getblocks the next batch of inventory.
1906 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1907 pfrom->hashContinue = pindex->GetBlockHash();
1908 break;
1914 else if (strCommand == NetMsgType::GETBLOCKTXN)
1916 BlockTransactionsRequest req;
1917 vRecv >> req;
1919 std::shared_ptr<const CBlock> recent_block;
1921 LOCK(cs_most_recent_block);
1922 if (most_recent_block_hash == req.blockhash)
1923 recent_block = most_recent_block;
1924 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1926 if (recent_block) {
1927 SendBlockTransactions(*recent_block, req, pfrom, connman);
1928 return true;
1931 LOCK(cs_main);
1933 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1934 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1935 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
1936 return true;
1939 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1940 // If an older block is requested (should never happen in practice,
1941 // but can happen in tests) send a block response instead of a
1942 // blocktxn response. Sending a full block response instead of a
1943 // small blocktxn response is preferable in the case where a peer
1944 // might maliciously send lots of getblocktxn requests to trigger
1945 // expensive disk reads, because it will require the peer to
1946 // actually receive all the data read from disk over the network.
1947 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
1948 CInv inv;
1949 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
1950 inv.hash = req.blockhash;
1951 pfrom->vRecvGetData.push_back(inv);
1952 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1953 return true;
1956 CBlock block;
1957 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
1958 assert(ret);
1960 SendBlockTransactions(block, req, pfrom, connman);
1964 else if (strCommand == NetMsgType::GETHEADERS)
1966 CBlockLocator locator;
1967 uint256 hashStop;
1968 vRecv >> locator >> hashStop;
1970 LOCK(cs_main);
1971 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
1972 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
1973 return true;
1976 CNodeState *nodestate = State(pfrom->GetId());
1977 const CBlockIndex* pindex = nullptr;
1978 if (locator.IsNull())
1980 // If locator is null, return the hashStop block
1981 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
1982 if (mi == mapBlockIndex.end())
1983 return true;
1984 pindex = (*mi).second;
1986 if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
1987 LogPrintf("%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
1988 return true;
1991 else
1993 // Find the last block the caller has in the main chain
1994 pindex = FindForkInGlobalIndex(chainActive, locator);
1995 if (pindex)
1996 pindex = chainActive.Next(pindex);
1999 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2000 std::vector<CBlock> vHeaders;
2001 int nLimit = MAX_HEADERS_RESULTS;
2002 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
2003 for (; pindex; pindex = chainActive.Next(pindex))
2005 vHeaders.push_back(pindex->GetBlockHeader());
2006 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2007 break;
2009 // pindex can be nullptr either if we sent chainActive.Tip() OR
2010 // if our peer has chainActive.Tip() (and thus we are sending an empty
2011 // headers message). In both cases it's safe to update
2012 // pindexBestHeaderSent to be our tip.
2014 // It is important that we simply reset the BestHeaderSent value here,
2015 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2016 // the currently-being-connected tip using a compact block, which
2017 // resulted in the peer sending a headers request, which we respond to
2018 // without the new block. By resetting the BestHeaderSent, we ensure we
2019 // will re-announce the new block via headers (or compact blocks again)
2020 // in the SendMessages logic.
2021 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
2022 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2026 else if (strCommand == NetMsgType::TX)
2028 // Stop processing the transaction early if
2029 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2030 if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
2032 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
2033 return true;
2036 std::deque<COutPoint> vWorkQueue;
2037 std::vector<uint256> vEraseQueue;
2038 CTransactionRef ptx;
2039 vRecv >> ptx;
2040 const CTransaction& tx = *ptx;
2042 CInv inv(MSG_TX, tx.GetHash());
2043 pfrom->AddInventoryKnown(inv);
2045 LOCK(cs_main);
2047 bool fMissingInputs = false;
2048 CValidationState state;
2050 pfrom->setAskFor.erase(inv.hash);
2051 mapAlreadyAskedFor.erase(inv.hash);
2053 std::list<CTransactionRef> lRemovedTxn;
2055 if (!AlreadyHave(inv) &&
2056 AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2057 mempool.check(pcoinsTip);
2058 RelayTransaction(tx, connman);
2059 for (unsigned int i = 0; i < tx.vout.size(); i++) {
2060 vWorkQueue.emplace_back(inv.hash, i);
2063 pfrom->nLastTXTime = GetTime();
2065 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2066 pfrom->GetId(),
2067 tx.GetHash().ToString(),
2068 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
2070 // Recursively process any orphan transactions that depended on this one
2071 std::set<NodeId> setMisbehaving;
2072 while (!vWorkQueue.empty()) {
2073 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
2074 vWorkQueue.pop_front();
2075 if (itByPrev == mapOrphanTransactionsByPrev.end())
2076 continue;
2077 for (auto mi = itByPrev->second.begin();
2078 mi != itByPrev->second.end();
2079 ++mi)
2081 const CTransactionRef& porphanTx = (*mi)->second.tx;
2082 const CTransaction& orphanTx = *porphanTx;
2083 const uint256& orphanHash = orphanTx.GetHash();
2084 NodeId fromPeer = (*mi)->second.fromPeer;
2085 bool fMissingInputs2 = false;
2086 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2087 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2088 // anyone relaying LegitTxX banned)
2089 CValidationState stateDummy;
2092 if (setMisbehaving.count(fromPeer))
2093 continue;
2094 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2095 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2096 RelayTransaction(orphanTx, connman);
2097 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
2098 vWorkQueue.emplace_back(orphanHash, i);
2100 vEraseQueue.push_back(orphanHash);
2102 else if (!fMissingInputs2)
2104 int nDos = 0;
2105 if (stateDummy.IsInvalid(nDos) && nDos > 0)
2107 // Punish peer that gave us an invalid orphan tx
2108 Misbehaving(fromPeer, nDos);
2109 setMisbehaving.insert(fromPeer);
2110 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
2112 // Has inputs but not accepted to mempool
2113 // Probably non-standard or insufficient fee
2114 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2115 vEraseQueue.push_back(orphanHash);
2116 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
2117 // Do not use rejection cache for witness transactions or
2118 // witness-stripped transactions, as they can have been malleated.
2119 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2120 assert(recentRejects);
2121 recentRejects->insert(orphanHash);
2124 mempool.check(pcoinsTip);
2128 for (uint256 hash : vEraseQueue)
2129 EraseOrphanTx(hash);
2131 else if (fMissingInputs)
2133 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
2134 for (const CTxIn& txin : tx.vin) {
2135 if (recentRejects->contains(txin.prevout.hash)) {
2136 fRejectedParents = true;
2137 break;
2140 if (!fRejectedParents) {
2141 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2142 for (const CTxIn& txin : tx.vin) {
2143 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
2144 pfrom->AddInventoryKnown(_inv);
2145 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
2147 AddOrphanTx(ptx, pfrom->GetId());
2149 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2150 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
2151 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
2152 if (nEvicted > 0) {
2153 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
2155 } else {
2156 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
2157 // We will continue to reject this tx since it has rejected
2158 // parents so avoid re-requesting it from other peers.
2159 recentRejects->insert(tx.GetHash());
2161 } else {
2162 if (!tx.HasWitness() && !state.CorruptionPossible()) {
2163 // Do not use rejection cache for witness transactions or
2164 // witness-stripped transactions, as they can have been malleated.
2165 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2166 assert(recentRejects);
2167 recentRejects->insert(tx.GetHash());
2168 if (RecursiveDynamicUsage(*ptx) < 100000) {
2169 AddToCompactExtraTransactions(ptx);
2171 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
2172 AddToCompactExtraTransactions(ptx);
2175 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
2176 // Always relay transactions received from whitelisted peers, even
2177 // if they were already in the mempool or rejected from it due
2178 // to policy, allowing the node to function as a gateway for
2179 // nodes hidden behind it.
2181 // Never relay transactions that we would assign a non-zero DoS
2182 // score for, as we expect peers to do the same with us in that
2183 // case.
2184 int nDoS = 0;
2185 if (!state.IsInvalid(nDoS) || nDoS == 0) {
2186 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
2187 RelayTransaction(tx, connman);
2188 } else {
2189 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
2194 for (const CTransactionRef& removedTx : lRemovedTxn)
2195 AddToCompactExtraTransactions(removedTx);
2197 int nDoS = 0;
2198 if (state.IsInvalid(nDoS))
2200 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
2201 pfrom->GetId(),
2202 FormatStateMessage(state));
2203 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
2204 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
2205 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
2206 if (nDoS > 0) {
2207 Misbehaving(pfrom->GetId(), nDoS);
2213 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2215 CBlockHeaderAndShortTxIDs cmpctblock;
2216 vRecv >> cmpctblock;
2219 LOCK(cs_main);
2221 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
2222 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2223 if (!IsInitialBlockDownload())
2224 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2225 return true;
2229 const CBlockIndex *pindex = nullptr;
2230 CValidationState state;
2231 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
2232 int nDoS;
2233 if (state.IsInvalid(nDoS)) {
2234 if (nDoS > 0) {
2235 LOCK(cs_main);
2236 Misbehaving(pfrom->GetId(), nDoS);
2238 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2239 return true;
2243 // When we succeed in decoding a block's txids from a cmpctblock
2244 // message we typically jump to the BLOCKTXN handling code, with a
2245 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2246 // completing processing of the putative block (without cs_main).
2247 bool fProcessBLOCKTXN = false;
2248 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2250 // If we end up treating this as a plain headers message, call that as well
2251 // without cs_main.
2252 bool fRevertToHeaderProcessing = false;
2254 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2255 // below)
2256 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2257 bool fBlockReconstructed = false;
2260 LOCK(cs_main);
2261 // If AcceptBlockHeader returned true, it set pindex
2262 assert(pindex);
2263 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2265 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2266 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2268 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2269 return true;
2271 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2272 pindex->nTx != 0) { // We had this block at some point, but pruned it
2273 if (fAlreadyInFlight) {
2274 // We requested this block for some reason, but our mempool will probably be useless
2275 // so we just grab the block via normal getdata
2276 std::vector<CInv> vInv(1);
2277 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2278 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2280 return true;
2283 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2284 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2285 return true;
2287 CNodeState *nodestate = State(pfrom->GetId());
2289 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2290 // Don't bother trying to process compact blocks from v1 peers
2291 // after segwit activates.
2292 return true;
2295 // We want to be a bit conservative just to be extra careful about DoS
2296 // possibilities in compact block processing...
2297 if (pindex->nHeight <= chainActive.Height() + 2) {
2298 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2299 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2300 std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
2301 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2302 if (!(*queuedBlockIt)->partialBlock)
2303 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2304 else {
2305 // The block was already in flight using compact blocks from the same peer
2306 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2307 return true;
2311 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2312 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2313 if (status == READ_STATUS_INVALID) {
2314 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2315 Misbehaving(pfrom->GetId(), 100);
2316 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2317 return true;
2318 } else if (status == READ_STATUS_FAILED) {
2319 // Duplicate txindexes, the block is now in-flight, so just request it
2320 std::vector<CInv> vInv(1);
2321 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2322 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2323 return true;
2326 BlockTransactionsRequest req;
2327 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2328 if (!partialBlock.IsTxAvailable(i))
2329 req.indexes.push_back(i);
2331 if (req.indexes.empty()) {
2332 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2333 BlockTransactions txn;
2334 txn.blockhash = cmpctblock.header.GetHash();
2335 blockTxnMsg << txn;
2336 fProcessBLOCKTXN = true;
2337 } else {
2338 req.blockhash = pindex->GetBlockHash();
2339 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2341 } else {
2342 // This block is either already in flight from a different
2343 // peer, or this peer has too many blocks outstanding to
2344 // download from.
2345 // Optimistically try to reconstruct anyway since we might be
2346 // able to without any round trips.
2347 PartiallyDownloadedBlock tempBlock(&mempool);
2348 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2349 if (status != READ_STATUS_OK) {
2350 // TODO: don't ignore failures
2351 return true;
2353 std::vector<CTransactionRef> dummy;
2354 status = tempBlock.FillBlock(*pblock, dummy);
2355 if (status == READ_STATUS_OK) {
2356 fBlockReconstructed = true;
2359 } else {
2360 if (fAlreadyInFlight) {
2361 // We requested this block, but its far into the future, so our
2362 // mempool will probably be useless - request the block normally
2363 std::vector<CInv> vInv(1);
2364 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2365 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2366 return true;
2367 } else {
2368 // If this was an announce-cmpctblock, we want the same treatment as a header message
2369 fRevertToHeaderProcessing = true;
2372 } // cs_main
2374 if (fProcessBLOCKTXN)
2375 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2377 if (fRevertToHeaderProcessing) {
2378 // Headers received from HB compact block peers are permitted to be
2379 // relayed before full validation (see BIP 152), so we don't want to disconnect
2380 // the peer if the header turns out to be for an invalid block.
2381 // Note that if a peer tries to build on an invalid chain, that
2382 // will be detected and the peer will be banned.
2383 return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
2386 if (fBlockReconstructed) {
2387 // If we got here, we were able to optimistically reconstruct a
2388 // block that is in flight from some other peer.
2390 LOCK(cs_main);
2391 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2393 bool fNewBlock = false;
2394 // Setting fForceProcessing to true means that we bypass some of
2395 // our anti-DoS protections in AcceptBlock, which filters
2396 // unrequested blocks that might be trying to waste our resources
2397 // (eg disk space). Because we only try to reconstruct blocks when
2398 // we're close to caught up (via the CanDirectFetch() requirement
2399 // above, combined with the behavior of not requesting blocks until
2400 // we have a chain with at least nMinimumChainWork), and we ignore
2401 // compact blocks with less work than our tip, it is safe to treat
2402 // reconstructed compact blocks as having been requested.
2403 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2404 if (fNewBlock) {
2405 pfrom->nLastBlockTime = GetTime();
2406 } else {
2407 LOCK(cs_main);
2408 mapBlockSource.erase(pblock->GetHash());
2410 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2411 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2412 // Clear download state for this block, which is in
2413 // process from some other peer. We do this after calling
2414 // ProcessNewBlock so that a malleated cmpctblock announcement
2415 // can't be used to interfere with block relay.
2416 MarkBlockAsReceived(pblock->GetHash());
2422 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2424 BlockTransactions resp;
2425 vRecv >> resp;
2427 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2428 bool fBlockRead = false;
2430 LOCK(cs_main);
2432 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2433 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2434 it->second.first != pfrom->GetId()) {
2435 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2436 return true;
2439 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2440 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2441 if (status == READ_STATUS_INVALID) {
2442 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2443 Misbehaving(pfrom->GetId(), 100);
2444 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2445 return true;
2446 } else if (status == READ_STATUS_FAILED) {
2447 // Might have collided, fall back to getdata now :(
2448 std::vector<CInv> invs;
2449 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2450 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2451 } else {
2452 // Block is either okay, or possibly we received
2453 // READ_STATUS_CHECKBLOCK_FAILED.
2454 // Note that CheckBlock can only fail for one of a few reasons:
2455 // 1. bad-proof-of-work (impossible here, because we've already
2456 // accepted the header)
2457 // 2. merkleroot doesn't match the transactions given (already
2458 // caught in FillBlock with READ_STATUS_FAILED, so
2459 // impossible here)
2460 // 3. the block is otherwise invalid (eg invalid coinbase,
2461 // block is too big, too many legacy sigops, etc).
2462 // So if CheckBlock failed, #3 is the only possibility.
2463 // Under BIP 152, we don't DoS-ban unless proof of work is
2464 // invalid (we don't require all the stateless checks to have
2465 // been run). This is handled below, so just treat this as
2466 // though the block was successfully read, and rely on the
2467 // handling in ProcessNewBlock to ensure the block index is
2468 // updated, reject messages go out, etc.
2469 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2470 fBlockRead = true;
2471 // mapBlockSource is only used for sending reject messages and DoS scores,
2472 // so the race between here and cs_main in ProcessNewBlock is fine.
2473 // BIP 152 permits peers to relay compact blocks after validating
2474 // the header only; we should not punish peers if the block turns
2475 // out to be invalid.
2476 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2478 } // Don't hold cs_main when we call into ProcessNewBlock
2479 if (fBlockRead) {
2480 bool fNewBlock = false;
2481 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2482 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2483 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2484 // disk-space attacks), but this should be safe due to the
2485 // protections in the compact block handler -- see related comment
2486 // in compact block optimistic reconstruction handling.
2487 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2488 if (fNewBlock) {
2489 pfrom->nLastBlockTime = GetTime();
2490 } else {
2491 LOCK(cs_main);
2492 mapBlockSource.erase(pblock->GetHash());
2498 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2500 std::vector<CBlockHeader> headers;
2502 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2503 unsigned int nCount = ReadCompactSize(vRecv);
2504 if (nCount > MAX_HEADERS_RESULTS) {
2505 LOCK(cs_main);
2506 Misbehaving(pfrom->GetId(), 20);
2507 return error("headers message size = %u", nCount);
2509 headers.resize(nCount);
2510 for (unsigned int n = 0; n < nCount; n++) {
2511 vRecv >> headers[n];
2512 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2515 // Headers received via a HEADERS message should be valid, and reflect
2516 // the chain the peer is on. If we receive a known-invalid header,
2517 // disconnect the peer if it is using one of our outbound connection
2518 // slots.
2519 bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
2520 return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
2523 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2525 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2526 vRecv >> *pblock;
2528 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2530 // Process all blocks from whitelisted peers, even if not requested,
2531 // unless we're still syncing with the network.
2532 // Such an unrequested block may still be processed, subject to the
2533 // conditions in AcceptBlock().
2534 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
2535 const uint256 hash(pblock->GetHash());
2537 LOCK(cs_main);
2538 // Also always process if we requested the block explicitly, as we may
2539 // need it even though it is not a candidate for a new best tip.
2540 forceProcessing |= MarkBlockAsReceived(hash);
2541 // mapBlockSource is only used for sending reject messages and DoS scores,
2542 // so the race between here and cs_main in ProcessNewBlock is fine.
2543 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2545 bool fNewBlock = false;
2546 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2547 if (fNewBlock) {
2548 pfrom->nLastBlockTime = GetTime();
2549 } else {
2550 LOCK(cs_main);
2551 mapBlockSource.erase(pblock->GetHash());
2556 else if (strCommand == NetMsgType::GETADDR)
2558 // This asymmetric behavior for inbound and outbound connections was introduced
2559 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2560 // to users' AddrMan and later request them by sending getaddr messages.
2561 // Making nodes which are behind NAT and can only make outgoing connections ignore
2562 // the getaddr message mitigates the attack.
2563 if (!pfrom->fInbound) {
2564 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2565 return true;
2568 // Only send one GetAddr response per connection to reduce resource waste
2569 // and discourage addr stamping of INV announcements.
2570 if (pfrom->fSentAddr) {
2571 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2572 return true;
2574 pfrom->fSentAddr = true;
2576 pfrom->vAddrToSend.clear();
2577 std::vector<CAddress> vAddr = connman->GetAddresses();
2578 FastRandomContext insecure_rand;
2579 for (const CAddress &addr : vAddr)
2580 pfrom->PushAddress(addr, insecure_rand);
2584 else if (strCommand == NetMsgType::MEMPOOL)
2586 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2588 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2589 pfrom->fDisconnect = true;
2590 return true;
2593 if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
2595 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2596 pfrom->fDisconnect = true;
2597 return true;
2600 LOCK(pfrom->cs_inventory);
2601 pfrom->fSendMempool = true;
2605 else if (strCommand == NetMsgType::PING)
2607 if (pfrom->nVersion > BIP0031_VERSION)
2609 uint64_t nonce = 0;
2610 vRecv >> nonce;
2611 // Echo the message back with the nonce. This allows for two useful features:
2613 // 1) A remote node can quickly check if the connection is operational
2614 // 2) Remote nodes can measure the latency of the network thread. If this node
2615 // is overloaded it won't respond to pings quickly and the remote node can
2616 // avoid sending us more work, like chain download requests.
2618 // The nonce stops the remote getting confused between different pings: without
2619 // it, if the remote node sends a ping once per second and this node takes 5
2620 // seconds to respond to each, the 5th ping the remote sends would appear to
2621 // return very quickly.
2622 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2627 else if (strCommand == NetMsgType::PONG)
2629 int64_t pingUsecEnd = nTimeReceived;
2630 uint64_t nonce = 0;
2631 size_t nAvail = vRecv.in_avail();
2632 bool bPingFinished = false;
2633 std::string sProblem;
2635 if (nAvail >= sizeof(nonce)) {
2636 vRecv >> nonce;
2638 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2639 if (pfrom->nPingNonceSent != 0) {
2640 if (nonce == pfrom->nPingNonceSent) {
2641 // Matching pong received, this ping is no longer outstanding
2642 bPingFinished = true;
2643 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2644 if (pingUsecTime > 0) {
2645 // Successful ping time measurement, replace previous
2646 pfrom->nPingUsecTime = pingUsecTime;
2647 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2648 } else {
2649 // This should never happen
2650 sProblem = "Timing mishap";
2652 } else {
2653 // Nonce mismatches are normal when pings are overlapping
2654 sProblem = "Nonce mismatch";
2655 if (nonce == 0) {
2656 // This is most likely a bug in another implementation somewhere; cancel this ping
2657 bPingFinished = true;
2658 sProblem = "Nonce zero";
2661 } else {
2662 sProblem = "Unsolicited pong without ping";
2664 } else {
2665 // This is most likely a bug in another implementation somewhere; cancel this ping
2666 bPingFinished = true;
2667 sProblem = "Short payload";
2670 if (!(sProblem.empty())) {
2671 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2672 pfrom->GetId(),
2673 sProblem,
2674 pfrom->nPingNonceSent,
2675 nonce,
2676 nAvail);
2678 if (bPingFinished) {
2679 pfrom->nPingNonceSent = 0;
2684 else if (strCommand == NetMsgType::FILTERLOAD)
2686 CBloomFilter filter;
2687 vRecv >> filter;
2689 if (!filter.IsWithinSizeConstraints())
2691 // There is no excuse for sending a too-large filter
2692 LOCK(cs_main);
2693 Misbehaving(pfrom->GetId(), 100);
2695 else
2697 LOCK(pfrom->cs_filter);
2698 delete pfrom->pfilter;
2699 pfrom->pfilter = new CBloomFilter(filter);
2700 pfrom->pfilter->UpdateEmptyFull();
2701 pfrom->fRelayTxes = true;
2706 else if (strCommand == NetMsgType::FILTERADD)
2708 std::vector<unsigned char> vData;
2709 vRecv >> vData;
2711 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2712 // and thus, the maximum size any matched object can have) in a filteradd message
2713 bool bad = false;
2714 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2715 bad = true;
2716 } else {
2717 LOCK(pfrom->cs_filter);
2718 if (pfrom->pfilter) {
2719 pfrom->pfilter->insert(vData);
2720 } else {
2721 bad = true;
2724 if (bad) {
2725 LOCK(cs_main);
2726 Misbehaving(pfrom->GetId(), 100);
2731 else if (strCommand == NetMsgType::FILTERCLEAR)
2733 LOCK(pfrom->cs_filter);
2734 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2735 delete pfrom->pfilter;
2736 pfrom->pfilter = new CBloomFilter();
2738 pfrom->fRelayTxes = true;
2741 else if (strCommand == NetMsgType::FEEFILTER) {
2742 CAmount newFeeFilter = 0;
2743 vRecv >> newFeeFilter;
2744 if (MoneyRange(newFeeFilter)) {
2746 LOCK(pfrom->cs_feeFilter);
2747 pfrom->minFeeFilter = newFeeFilter;
2749 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2753 else if (strCommand == NetMsgType::NOTFOUND) {
2754 // We do not care about the NOTFOUND message, but logging an Unknown Command
2755 // message would be undesirable as we transmit it ourselves.
2758 else {
2759 // Ignore unknown commands for extensibility
2760 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2765 return true;
2768 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
2770 AssertLockHeld(cs_main);
2771 CNodeState &state = *State(pnode->GetId());
2773 for (const CBlockReject& reject : state.rejects) {
2774 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2776 state.rejects.clear();
2778 if (state.fShouldBan) {
2779 state.fShouldBan = false;
2780 if (pnode->fWhitelisted)
2781 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2782 else if (pnode->m_manual_connection)
2783 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
2784 else {
2785 pnode->fDisconnect = true;
2786 if (pnode->addr.IsLocal())
2787 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2788 else
2790 connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2793 return true;
2795 return false;
2798 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2800 const CChainParams& chainparams = Params();
2802 // Message format
2803 // (4) message start
2804 // (12) command
2805 // (4) size
2806 // (4) checksum
2807 // (x) data
2809 bool fMoreWork = false;
2811 if (!pfrom->vRecvGetData.empty())
2812 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2814 if (pfrom->fDisconnect)
2815 return false;
2817 // this maintains the order of responses
2818 if (!pfrom->vRecvGetData.empty()) return true;
2820 // Don't bother if send buffer is too full to respond anyway
2821 if (pfrom->fPauseSend)
2822 return false;
2824 std::list<CNetMessage> msgs;
2826 LOCK(pfrom->cs_vProcessMsg);
2827 if (pfrom->vProcessMsg.empty())
2828 return false;
2829 // Just take one message
2830 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2831 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2832 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize();
2833 fMoreWork = !pfrom->vProcessMsg.empty();
2835 CNetMessage& msg(msgs.front());
2837 msg.SetVersion(pfrom->GetRecvVersion());
2838 // Scan for message start
2839 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2840 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2841 pfrom->fDisconnect = true;
2842 return false;
2845 // Read header
2846 CMessageHeader& hdr = msg.hdr;
2847 if (!hdr.IsValid(chainparams.MessageStart()))
2849 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2850 return fMoreWork;
2852 std::string strCommand = hdr.GetCommand();
2854 // Message size
2855 unsigned int nMessageSize = hdr.nMessageSize;
2857 // Checksum
2858 CDataStream& vRecv = msg.vRecv;
2859 const uint256& hash = msg.GetMessageHash();
2860 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2862 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2863 SanitizeString(strCommand), nMessageSize,
2864 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2865 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2866 return fMoreWork;
2869 // Process message
2870 bool fRet = false;
2873 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2874 if (interruptMsgProc)
2875 return false;
2876 if (!pfrom->vRecvGetData.empty())
2877 fMoreWork = true;
2879 catch (const std::ios_base::failure& e)
2881 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2882 if (strstr(e.what(), "end of data"))
2884 // Allow exceptions from under-length message on vRecv
2885 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());
2887 else if (strstr(e.what(), "size too large"))
2889 // Allow exceptions from over-long size
2890 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2892 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2894 // Allow exceptions from non-canonical encoding
2895 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2897 else
2899 PrintExceptionContinue(&e, "ProcessMessages()");
2902 catch (const std::exception& e) {
2903 PrintExceptionContinue(&e, "ProcessMessages()");
2904 } catch (...) {
2905 PrintExceptionContinue(nullptr, "ProcessMessages()");
2908 if (!fRet) {
2909 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
2912 LOCK(cs_main);
2913 SendRejectsAndCheckIfBanned(pfrom, connman);
2915 return fMoreWork;
2918 void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
2920 AssertLockHeld(cs_main);
2922 CNodeState &state = *State(pto->GetId());
2923 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2925 if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
2926 // This is an outbound peer subject to disconnection if they don't
2927 // announce a block with as much work as the current tip within
2928 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
2929 // their chain has more work than ours, we should sync to it,
2930 // unless it's invalid, in which case we should find that out and
2931 // disconnect from them elsewhere).
2932 if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
2933 if (state.m_chain_sync.m_timeout != 0) {
2934 state.m_chain_sync.m_timeout = 0;
2935 state.m_chain_sync.m_work_header = nullptr;
2936 state.m_chain_sync.m_sent_getheaders = false;
2938 } else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
2939 // Our best block known by this peer is behind our tip, and we're either noticing
2940 // that for the first time, OR this peer was able to catch up to some earlier point
2941 // where we checked against our tip.
2942 // Either way, set a new timeout based on current tip.
2943 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
2944 state.m_chain_sync.m_work_header = chainActive.Tip();
2945 state.m_chain_sync.m_sent_getheaders = false;
2946 } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
2947 // No evidence yet that our peer has synced to a chain with work equal to that
2948 // of our tip, when we first detected it was behind. Send a single getheaders
2949 // message to give the peer a chance to update us.
2950 if (state.m_chain_sync.m_sent_getheaders) {
2951 // They've run out of time to catch up!
2952 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
2953 pto->fDisconnect = true;
2954 } else {
2955 LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
2956 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
2957 state.m_chain_sync.m_sent_getheaders = true;
2958 constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
2959 // Bump the timeout to allow a response, which could clear the timeout
2960 // (if the response shows the peer has synced), reset the timeout (if
2961 // the peer syncs to the required work but not to our tip), or result
2962 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
2963 // has not sufficiently progressed)
2964 state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
2970 class CompareInvMempoolOrder
2972 CTxMemPool *mp;
2973 public:
2974 explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
2976 mp = _mempool;
2979 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
2981 /* As std::make_heap produces a max-heap, we want the entries with the
2982 * fewest ancestors/highest fee to sort later. */
2983 return mp->CompareDepthAndScore(*b, *a);
2987 bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
2989 const Consensus::Params& consensusParams = Params().GetConsensus();
2991 // Don't send anything until the version handshake is complete
2992 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
2993 return true;
2995 // If we get here, the outgoing message serialization version is set and can't change.
2996 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2999 // Message: ping
3001 bool pingSend = false;
3002 if (pto->fPingQueued) {
3003 // RPC ping request by user
3004 pingSend = true;
3006 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
3007 // Ping automatically sent as a latency probe & keepalive.
3008 pingSend = true;
3010 if (pingSend) {
3011 uint64_t nonce = 0;
3012 while (nonce == 0) {
3013 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
3015 pto->fPingQueued = false;
3016 pto->nPingUsecStart = GetTimeMicros();
3017 if (pto->nVersion > BIP0031_VERSION) {
3018 pto->nPingNonceSent = nonce;
3019 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
3020 } else {
3021 // Peer is too old to support ping command with nonce, pong will never arrive.
3022 pto->nPingNonceSent = 0;
3023 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
3027 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3028 if (!lockMain)
3029 return true;
3031 if (SendRejectsAndCheckIfBanned(pto, connman))
3032 return true;
3033 CNodeState &state = *State(pto->GetId());
3035 // Address refresh broadcast
3036 int64_t nNow = GetTimeMicros();
3037 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3038 AdvertiseLocal(pto);
3039 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
3043 // Message: addr
3045 if (pto->nNextAddrSend < nNow) {
3046 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
3047 std::vector<CAddress> vAddr;
3048 vAddr.reserve(pto->vAddrToSend.size());
3049 for (const CAddress& addr : pto->vAddrToSend)
3051 if (!pto->addrKnown.contains(addr.GetKey()))
3053 pto->addrKnown.insert(addr.GetKey());
3054 vAddr.push_back(addr);
3055 // receiver rejects addr messages larger than 1000
3056 if (vAddr.size() >= 1000)
3058 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3059 vAddr.clear();
3063 pto->vAddrToSend.clear();
3064 if (!vAddr.empty())
3065 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3066 // we only send the big addr message once
3067 if (pto->vAddrToSend.capacity() > 40)
3068 pto->vAddrToSend.shrink_to_fit();
3071 // Start block sync
3072 if (pindexBestHeader == nullptr)
3073 pindexBestHeader = chainActive.Tip();
3074 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.
3075 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
3076 // Only actively request headers from a single peer, unless we're close to today.
3077 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3078 state.fSyncStarted = true;
3079 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
3080 nSyncStarted++;
3081 const CBlockIndex *pindexStart = pindexBestHeader;
3082 /* If possible, start at the block preceding the currently
3083 best known header. This ensures that we always get a
3084 non-empty list of headers back as long as the peer
3085 is up-to-date. With a non-empty response, we can initialise
3086 the peer's known best block. This wouldn't be possible
3087 if we requested starting at pindexBestHeader and
3088 got back an empty response. */
3089 if (pindexStart->pprev)
3090 pindexStart = pindexStart->pprev;
3091 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
3092 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
3096 // Resend wallet transactions that haven't gotten in a block yet
3097 // Except during reindex, importing and IBD, when old wallet
3098 // transactions become unconfirmed and spams other nodes.
3099 if (!fReindex && !fImporting && !IsInitialBlockDownload())
3101 GetMainSignals().Broadcast(nTimeBestReceived, connman);
3105 // Try sending block announcements via headers
3108 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3109 // list of block hashes we're relaying, and our peer wants
3110 // headers announcements, then find the first header
3111 // not yet known to our peer but would connect, and send.
3112 // If no header would connect, or if we have too many
3113 // blocks, or if the peer doesn't want headers, just
3114 // add all to the inv queue.
3115 LOCK(pto->cs_inventory);
3116 std::vector<CBlock> vHeaders;
3117 bool fRevertToInv = ((!state.fPreferHeaders &&
3118 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
3119 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
3120 const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
3121 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
3123 if (!fRevertToInv) {
3124 bool fFoundStartingHeader = false;
3125 // Try to find first header that our peer doesn't have, and
3126 // then send all headers past that one. If we come across any
3127 // headers that aren't on chainActive, give up.
3128 for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3129 BlockMap::iterator mi = mapBlockIndex.find(hash);
3130 assert(mi != mapBlockIndex.end());
3131 const CBlockIndex *pindex = mi->second;
3132 if (chainActive[pindex->nHeight] != pindex) {
3133 // Bail out if we reorged away from this block
3134 fRevertToInv = true;
3135 break;
3137 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
3138 // This means that the list of blocks to announce don't
3139 // connect to each other.
3140 // This shouldn't really be possible to hit during
3141 // regular operation (because reorgs should take us to
3142 // a chain that has some block not on the prior chain,
3143 // which should be caught by the prior check), but one
3144 // way this could happen is by using invalidateblock /
3145 // reconsiderblock repeatedly on the tip, causing it to
3146 // be added multiple times to vBlockHashesToAnnounce.
3147 // Robustly deal with this rare situation by reverting
3148 // to an inv.
3149 fRevertToInv = true;
3150 break;
3152 pBestIndex = pindex;
3153 if (fFoundStartingHeader) {
3154 // add this to the headers message
3155 vHeaders.push_back(pindex->GetBlockHeader());
3156 } else if (PeerHasHeader(&state, pindex)) {
3157 continue; // keep looking for the first new block
3158 } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
3159 // Peer doesn't have this header but they do have the prior one.
3160 // Start sending headers.
3161 fFoundStartingHeader = true;
3162 vHeaders.push_back(pindex->GetBlockHeader());
3163 } else {
3164 // Peer doesn't have this header or the prior one -- nothing will
3165 // connect, so bail out.
3166 fRevertToInv = true;
3167 break;
3171 if (!fRevertToInv && !vHeaders.empty()) {
3172 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
3173 // We only send up to 1 block as header-and-ids, as otherwise
3174 // probably means we're doing an initial-ish-sync or they're slow
3175 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
3176 vHeaders.front().GetHash().ToString(), pto->GetId());
3178 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
3180 bool fGotBlockFromCache = false;
3182 LOCK(cs_most_recent_block);
3183 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
3184 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
3185 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
3186 else {
3187 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
3188 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3190 fGotBlockFromCache = true;
3193 if (!fGotBlockFromCache) {
3194 CBlock block;
3195 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3196 assert(ret);
3197 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3198 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3200 state.pindexBestHeaderSent = pBestIndex;
3201 } else if (state.fPreferHeaders) {
3202 if (vHeaders.size() > 1) {
3203 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3204 vHeaders.size(),
3205 vHeaders.front().GetHash().ToString(),
3206 vHeaders.back().GetHash().ToString(), pto->GetId());
3207 } else {
3208 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3209 vHeaders.front().GetHash().ToString(), pto->GetId());
3211 connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3212 state.pindexBestHeaderSent = pBestIndex;
3213 } else
3214 fRevertToInv = true;
3216 if (fRevertToInv) {
3217 // If falling back to using an inv, just try to inv the tip.
3218 // The last entry in vBlockHashesToAnnounce was our tip at some point
3219 // in the past.
3220 if (!pto->vBlockHashesToAnnounce.empty()) {
3221 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3222 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3223 assert(mi != mapBlockIndex.end());
3224 const CBlockIndex *pindex = mi->second;
3226 // Warn if we're announcing a block that is not on the main chain.
3227 // This should be very rare and could be optimized out.
3228 // Just log for now.
3229 if (chainActive[pindex->nHeight] != pindex) {
3230 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3231 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3234 // If the peer's chain has this block, don't inv it back.
3235 if (!PeerHasHeader(&state, pindex)) {
3236 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3237 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3238 pto->GetId(), hashToAnnounce.ToString());
3242 pto->vBlockHashesToAnnounce.clear();
3246 // Message: inventory
3248 std::vector<CInv> vInv;
3250 LOCK(pto->cs_inventory);
3251 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3253 // Add blocks
3254 for (const uint256& hash : pto->vInventoryBlockToSend) {
3255 vInv.push_back(CInv(MSG_BLOCK, hash));
3256 if (vInv.size() == MAX_INV_SZ) {
3257 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3258 vInv.clear();
3261 pto->vInventoryBlockToSend.clear();
3263 // Check whether periodic sends should happen
3264 bool fSendTrickle = pto->fWhitelisted;
3265 if (pto->nNextInvSend < nNow) {
3266 fSendTrickle = true;
3267 // Use half the delay for outbound peers, as there is less privacy concern for them.
3268 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3271 // Time to send but the peer has requested we not relay transactions.
3272 if (fSendTrickle) {
3273 LOCK(pto->cs_filter);
3274 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3277 // Respond to BIP35 mempool requests
3278 if (fSendTrickle && pto->fSendMempool) {
3279 auto vtxinfo = mempool.infoAll();
3280 pto->fSendMempool = false;
3281 CAmount filterrate = 0;
3283 LOCK(pto->cs_feeFilter);
3284 filterrate = pto->minFeeFilter;
3287 LOCK(pto->cs_filter);
3289 for (const auto& txinfo : vtxinfo) {
3290 const uint256& hash = txinfo.tx->GetHash();
3291 CInv inv(MSG_TX, hash);
3292 pto->setInventoryTxToSend.erase(hash);
3293 if (filterrate) {
3294 if (txinfo.feeRate.GetFeePerK() < filterrate)
3295 continue;
3297 if (pto->pfilter) {
3298 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3300 pto->filterInventoryKnown.insert(hash);
3301 vInv.push_back(inv);
3302 if (vInv.size() == MAX_INV_SZ) {
3303 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3304 vInv.clear();
3307 pto->timeLastMempoolReq = GetTime();
3310 // Determine transactions to relay
3311 if (fSendTrickle) {
3312 // Produce a vector with all candidates for sending
3313 std::vector<std::set<uint256>::iterator> vInvTx;
3314 vInvTx.reserve(pto->setInventoryTxToSend.size());
3315 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3316 vInvTx.push_back(it);
3318 CAmount filterrate = 0;
3320 LOCK(pto->cs_feeFilter);
3321 filterrate = pto->minFeeFilter;
3323 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3324 // A heap is used so that not all items need sorting if only a few are being sent.
3325 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3326 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3327 // No reason to drain out at many times the network's capacity,
3328 // especially since we have many peers and some will draw much shorter delays.
3329 unsigned int nRelayedTransactions = 0;
3330 LOCK(pto->cs_filter);
3331 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3332 // Fetch the top element from the heap
3333 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3334 std::set<uint256>::iterator it = vInvTx.back();
3335 vInvTx.pop_back();
3336 uint256 hash = *it;
3337 // Remove it from the to-be-sent set
3338 pto->setInventoryTxToSend.erase(it);
3339 // Check if not in the filter already
3340 if (pto->filterInventoryKnown.contains(hash)) {
3341 continue;
3343 // Not in the mempool anymore? don't bother sending it.
3344 auto txinfo = mempool.info(hash);
3345 if (!txinfo.tx) {
3346 continue;
3348 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3349 continue;
3351 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3352 // Send
3353 vInv.push_back(CInv(MSG_TX, hash));
3354 nRelayedTransactions++;
3356 // Expire old relay messages
3357 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3359 mapRelay.erase(vRelayExpiration.front().second);
3360 vRelayExpiration.pop_front();
3363 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3364 if (ret.second) {
3365 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3368 if (vInv.size() == MAX_INV_SZ) {
3369 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3370 vInv.clear();
3372 pto->filterInventoryKnown.insert(hash);
3376 if (!vInv.empty())
3377 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3379 // Detect whether we're stalling
3380 nNow = GetTimeMicros();
3381 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3382 // Stalling only triggers when the block download window cannot move. During normal steady state,
3383 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3384 // should only happen during initial block download.
3385 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3386 pto->fDisconnect = true;
3387 return true;
3389 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3390 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3391 // We compensate for other peers to prevent killing off peers due to our own downstream link
3392 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3393 // to unreasonably increase our timeout.
3394 if (state.vBlocksInFlight.size() > 0) {
3395 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3396 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3397 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3398 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3399 pto->fDisconnect = true;
3400 return true;
3403 // Check for headers sync timeouts
3404 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3405 // Detect whether this is a stalling initial-headers-sync peer
3406 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3407 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3408 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3409 // and we have others we could be using instead.
3410 // Note: If all our peers are inbound, then we won't
3411 // disconnect our sync peer for stalling; we have bigger
3412 // problems if we can't get any outbound peers.
3413 if (!pto->fWhitelisted) {
3414 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3415 pto->fDisconnect = true;
3416 return true;
3417 } else {
3418 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3419 // Reset the headers sync state so that we have a
3420 // chance to try downloading from a different peer.
3421 // Note: this will also result in at least one more
3422 // getheaders message to be sent to
3423 // this peer (eventually).
3424 state.fSyncStarted = false;
3425 nSyncStarted--;
3426 state.nHeadersSyncTimeout = 0;
3429 } else {
3430 // After we've caught up once, reset the timeout so we can't trigger
3431 // disconnect later.
3432 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3436 // Check that outbound peers have reasonable chains
3437 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3438 ConsiderEviction(pto, GetTime());
3441 // Message: getdata (blocks)
3443 std::vector<CInv> vGetData;
3444 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3445 std::vector<const CBlockIndex*> vToDownload;
3446 NodeId staller = -1;
3447 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3448 for (const CBlockIndex *pindex : vToDownload) {
3449 uint32_t nFetchFlags = GetFetchFlags(pto);
3450 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3451 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3452 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3453 pindex->nHeight, pto->GetId());
3455 if (state.nBlocksInFlight == 0 && staller != -1) {
3456 if (State(staller)->nStallingSince == 0) {
3457 State(staller)->nStallingSince = nNow;
3458 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3464 // Message: getdata (non-blocks)
3466 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3468 const CInv& inv = (*pto->mapAskFor.begin()).second;
3469 if (!AlreadyHave(inv))
3471 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3472 vGetData.push_back(inv);
3473 if (vGetData.size() >= 1000)
3475 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3476 vGetData.clear();
3478 } else {
3479 //If we're not going to ask, don't expect a response.
3480 pto->setAskFor.erase(inv.hash);
3482 pto->mapAskFor.erase(pto->mapAskFor.begin());
3484 if (!vGetData.empty())
3485 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3488 // Message: feefilter
3490 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3491 if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3492 !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3493 CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3494 int64_t timeNow = GetTimeMicros();
3495 if (timeNow > pto->nextSendTimeFeeFilter) {
3496 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3497 static FeeFilterRounder filterRounder(default_feerate);
3498 CAmount filterToSend = filterRounder.round(currentFilter);
3499 // We always have a fee filter of at least minRelayTxFee
3500 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3501 if (filterToSend != pto->lastSentFeeFilter) {
3502 connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3503 pto->lastSentFeeFilter = filterToSend;
3505 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3507 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3508 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3509 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3510 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3511 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3515 return true;
3518 class CNetProcessingCleanup
3520 public:
3521 CNetProcessingCleanup() {}
3522 ~CNetProcessingCleanup() {
3523 // orphan transactions
3524 mapOrphanTransactions.clear();
3525 mapOrphanTransactionsByPrev.clear();
3527 } instance_of_cnetprocessingcleanup;