Add CConnmanTest to mutate g_connman in tests
[bitcoinplatinum.git] / src / net_processing.cpp
blob3aa13fff435f306c8d6270f3f4a266c8603e3b8d
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 "scheduler.h"
27 #include "tinyformat.h"
28 #include "txmempool.h"
29 #include "ui_interface.h"
30 #include "util.h"
31 #include "utilmoneystr.h"
32 #include "utilstrencodings.h"
33 #include "validationinterface.h"
35 #if defined(NDEBUG)
36 # error "Bitcoin cannot be compiled without assertions."
37 #endif
39 std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
41 struct IteratorComparator
43 template<typename I>
44 bool operator()(const I& a, const I& b)
46 return &(*a) < &(*b);
50 struct COrphanTx {
51 // When modifying, adapt the copy of this definition in tests/DoS_tests.
52 CTransactionRef tx;
53 NodeId fromPeer;
54 int64_t nTimeExpire;
56 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
57 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
58 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
60 static size_t vExtraTxnForCompactIt = 0;
61 static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
63 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
65 /// Age after which a stale block will no longer be served if requested as
66 /// protection against fingerprinting. Set to one month, denominated in seconds.
67 static const int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
69 /// Age after which a block is considered historical for purposes of rate
70 /// limiting block relay. Set to one week, denominated in seconds.
71 static const int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
73 // Internal stuff
74 namespace {
75 /** Number of nodes with fSyncStarted. */
76 int nSyncStarted = 0;
78 /**
79 * Sources of received blocks, saved to be able to send them reject
80 * messages or ban them when processing happens afterwards. Protected by
81 * cs_main.
82 * Set mapBlockSource[hash].second to false if the node should not be
83 * punished if the block is invalid.
85 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
87 /**
88 * Filter for transactions that were recently rejected by
89 * AcceptToMemoryPool. These are not rerequested until the chain tip
90 * changes, at which point the entire filter is reset. Protected by
91 * cs_main.
93 * Without this filter we'd be re-requesting txs from each of our peers,
94 * increasing bandwidth consumption considerably. For instance, with 100
95 * peers, half of which relay a tx we don't accept, that might be a 50x
96 * bandwidth increase. A flooding attacker attempting to roll-over the
97 * filter using minimum-sized, 60byte, transactions might manage to send
98 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
99 * two minute window to send invs to us.
101 * Decreasing the false positive rate is fairly cheap, so we pick one in a
102 * million to make it highly unlikely for users to have issues with this
103 * filter.
105 * Memory used: 1.3 MB
107 std::unique_ptr<CRollingBloomFilter> recentRejects;
108 uint256 hashRecentRejectsChainTip;
110 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
111 struct QueuedBlock {
112 uint256 hash;
113 const CBlockIndex* pindex; //!< Optional.
114 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
115 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
117 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
119 /** Stack of nodes which we have set to announce using compact blocks */
120 std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
122 /** Number of preferable block download peers. */
123 int nPreferredDownload = 0;
125 /** Number of peers from which we're downloading blocks. */
126 int nPeersWithValidatedDownloads = 0;
128 /** Number of outbound peers with m_chain_sync.m_protect. */
129 int g_outbound_peers_with_protect_from_disconnect = 0;
131 /** When our tip was last updated. */
132 int64_t g_last_tip_update = 0;
134 /** Relay map, protected by cs_main. */
135 typedef std::map<uint256, CTransactionRef> MapRelay;
136 MapRelay mapRelay;
137 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
138 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
139 } // namespace
141 namespace {
143 struct CBlockReject {
144 unsigned char chRejectCode;
145 std::string strRejectReason;
146 uint256 hashBlock;
150 * Maintain validation-specific state about nodes, protected by cs_main, instead
151 * by CNode's own locks. This simplifies asynchronous operation, where
152 * processing of incoming data is done after the ProcessMessage call returns,
153 * and we're no longer holding the node's locks.
155 struct CNodeState {
156 //! The peer's address
157 const CService address;
158 //! Whether we have a fully established connection.
159 bool fCurrentlyConnected;
160 //! Accumulated misbehaviour score for this peer.
161 int nMisbehavior;
162 //! Whether this peer should be disconnected and banned (unless whitelisted).
163 bool fShouldBan;
164 //! String name of this peer (debugging/logging purposes).
165 const std::string name;
166 //! List of asynchronously-determined block rejections to notify this peer about.
167 std::vector<CBlockReject> rejects;
168 //! The best known block we know this peer has announced.
169 const CBlockIndex *pindexBestKnownBlock;
170 //! The hash of the last unknown block this peer has announced.
171 uint256 hashLastUnknownBlock;
172 //! The last full block we both have.
173 const CBlockIndex *pindexLastCommonBlock;
174 //! The best header we have sent our peer.
175 const CBlockIndex *pindexBestHeaderSent;
176 //! Length of current-streak of unconnecting headers announcements
177 int nUnconnectingHeaders;
178 //! Whether we've started headers synchronization with this peer.
179 bool fSyncStarted;
180 //! When to potentially disconnect peer for stalling headers download
181 int64_t nHeadersSyncTimeout;
182 //! Since when we're stalling block download progress (in microseconds), or 0.
183 int64_t nStallingSince;
184 std::list<QueuedBlock> vBlocksInFlight;
185 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
186 int64_t nDownloadingSince;
187 int nBlocksInFlight;
188 int nBlocksInFlightValidHeaders;
189 //! Whether we consider this a preferred download peer.
190 bool fPreferredDownload;
191 //! Whether this peer wants invs or headers (when possible) for block announcements.
192 bool fPreferHeaders;
193 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
194 bool fPreferHeaderAndIDs;
196 * Whether this peer will send us cmpctblocks if we request them.
197 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
198 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
200 bool fProvidesHeaderAndIDs;
201 //! Whether this peer can give us witnesses
202 bool fHaveWitness;
203 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
204 bool fWantsCmpctWitness;
206 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
207 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
209 bool fSupportsDesiredCmpctVersion;
211 /** State used to enforce CHAIN_SYNC_TIMEOUT
212 * Only in effect for outbound, non-manual connections, with
213 * m_protect == false
214 * Algorithm: if a peer's best known block has less work than our tip,
215 * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
216 * - If at timeout their best known block now has more work than our tip
217 * when the timeout was set, then either reset the timeout or clear it
218 * (after comparing against our current tip's work)
219 * - If at timeout their best known block still has less work than our
220 * tip did when the timeout was set, then send a getheaders message,
221 * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
222 * If their best known block is still behind when that new timeout is
223 * reached, disconnect.
225 struct ChainSyncTimeoutState {
226 //! A timeout used for checking whether our peer has sufficiently synced
227 int64_t m_timeout;
228 //! A header with the work we require on our peer's chain
229 const CBlockIndex * m_work_header;
230 //! After timeout is reached, set to true after sending getheaders
231 bool m_sent_getheaders;
232 //! Whether this peer is protected from disconnection due to a bad/slow chain
233 bool m_protect;
236 ChainSyncTimeoutState m_chain_sync;
238 //! Time of last new block announcement
239 int64_t m_last_block_announcement;
241 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
242 fCurrentlyConnected = false;
243 nMisbehavior = 0;
244 fShouldBan = false;
245 pindexBestKnownBlock = nullptr;
246 hashLastUnknownBlock.SetNull();
247 pindexLastCommonBlock = nullptr;
248 pindexBestHeaderSent = nullptr;
249 nUnconnectingHeaders = 0;
250 fSyncStarted = false;
251 nHeadersSyncTimeout = 0;
252 nStallingSince = 0;
253 nDownloadingSince = 0;
254 nBlocksInFlight = 0;
255 nBlocksInFlightValidHeaders = 0;
256 fPreferredDownload = false;
257 fPreferHeaders = false;
258 fPreferHeaderAndIDs = false;
259 fProvidesHeaderAndIDs = false;
260 fHaveWitness = false;
261 fWantsCmpctWitness = false;
262 fSupportsDesiredCmpctVersion = false;
263 m_chain_sync = { 0, nullptr, false, false };
264 m_last_block_announcement = 0;
268 /** Map maintaining per-node state. Requires cs_main. */
269 std::map<NodeId, CNodeState> mapNodeState;
271 // Requires cs_main.
272 CNodeState *State(NodeId pnode) {
273 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
274 if (it == mapNodeState.end())
275 return nullptr;
276 return &it->second;
279 void UpdatePreferredDownload(CNode* node, CNodeState* state)
281 nPreferredDownload -= state->fPreferredDownload;
283 // Whether this node should be marked as a preferred download node.
284 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
286 nPreferredDownload += state->fPreferredDownload;
289 void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
291 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
292 uint64_t nonce = pnode->GetLocalNonce();
293 int nNodeStartingHeight = pnode->GetMyStartingHeight();
294 NodeId nodeid = pnode->GetId();
295 CAddress addr = pnode->addr;
297 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
298 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
300 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
301 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
303 if (fLogIPs) {
304 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);
305 } else {
306 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
310 // Requires cs_main.
311 // Returns a bool indicating whether we requested this block.
312 // Also used if a block was /not/ received and timed out or started with another peer
313 bool MarkBlockAsReceived(const uint256& hash) {
314 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
315 if (itInFlight != mapBlocksInFlight.end()) {
316 CNodeState *state = State(itInFlight->second.first);
317 assert(state != nullptr);
318 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
319 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
320 // Last validated block on the queue was received.
321 nPeersWithValidatedDownloads--;
323 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
324 // First block on the queue was received, update the start download time for the next one
325 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
327 state->vBlocksInFlight.erase(itInFlight->second.second);
328 state->nBlocksInFlight--;
329 state->nStallingSince = 0;
330 mapBlocksInFlight.erase(itInFlight);
331 return true;
333 return false;
336 // Requires cs_main.
337 // returns false, still setting pit, if the block was already in flight from the same peer
338 // pit will only be valid as long as the same cs_main lock is being held
339 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
340 CNodeState *state = State(nodeid);
341 assert(state != nullptr);
343 // Short-circuit most stuff in case its from the same node
344 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
345 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
346 if (pit) {
347 *pit = &itInFlight->second.second;
349 return false;
352 // Make sure it's not listed somewhere already.
353 MarkBlockAsReceived(hash);
355 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
356 {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
357 state->nBlocksInFlight++;
358 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
359 if (state->nBlocksInFlight == 1) {
360 // We're starting a block download (batch) from this peer.
361 state->nDownloadingSince = GetTimeMicros();
363 if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
364 nPeersWithValidatedDownloads++;
366 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
367 if (pit)
368 *pit = &itInFlight->second.second;
369 return true;
372 /** Check whether the last unknown block a peer advertised is not yet known. */
373 void ProcessBlockAvailability(NodeId nodeid) {
374 CNodeState *state = State(nodeid);
375 assert(state != nullptr);
377 if (!state->hashLastUnknownBlock.IsNull()) {
378 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
379 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
380 if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
381 state->pindexBestKnownBlock = itOld->second;
382 state->hashLastUnknownBlock.SetNull();
387 /** Update tracking information about which blocks a peer is assumed to have. */
388 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
389 CNodeState *state = State(nodeid);
390 assert(state != nullptr);
392 ProcessBlockAvailability(nodeid);
394 BlockMap::iterator it = mapBlockIndex.find(hash);
395 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
396 // An actually better block was announced.
397 if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
398 state->pindexBestKnownBlock = it->second;
399 } else {
400 // An unknown block was announced; just assume that the latest one is the best one.
401 state->hashLastUnknownBlock = hash;
405 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) {
406 AssertLockHeld(cs_main);
407 CNodeState* nodestate = State(nodeid);
408 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
409 // Never ask from peers who can't provide witnesses.
410 return;
412 if (nodestate->fProvidesHeaderAndIDs) {
413 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
414 if (*it == nodeid) {
415 lNodesAnnouncingHeaderAndIDs.erase(it);
416 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
417 return;
420 connman->ForNode(nodeid, [connman](CNode* pfrom){
421 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
422 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
423 // As per BIP152, we only get 3 of our peers to announce
424 // blocks using compact encodings.
425 connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
426 connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
427 return true;
429 lNodesAnnouncingHeaderAndIDs.pop_front();
431 connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
432 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
433 return true;
438 bool TipMayBeStale(const Consensus::Params &consensusParams)
440 AssertLockHeld(cs_main);
441 if (g_last_tip_update == 0) {
442 g_last_tip_update = GetTime();
444 return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
447 // Requires cs_main
448 bool CanDirectFetch(const Consensus::Params &consensusParams)
450 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
453 // Requires cs_main
454 bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
456 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
457 return true;
458 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
459 return true;
460 return false;
463 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
464 * at most count entries. */
465 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
466 if (count == 0)
467 return;
469 vBlocks.reserve(vBlocks.size() + count);
470 CNodeState *state = State(nodeid);
471 assert(state != nullptr);
473 // Make sure pindexBestKnownBlock is up to date, we'll need it.
474 ProcessBlockAvailability(nodeid);
476 if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
477 // This peer has nothing interesting.
478 return;
481 if (state->pindexLastCommonBlock == nullptr) {
482 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
483 // Guessing wrong in either direction is not a problem.
484 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
487 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
488 // of its current tip anymore. Go back enough to fix that.
489 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
490 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
491 return;
493 std::vector<const CBlockIndex*> vToFetch;
494 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
495 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
496 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
497 // download that next block if the window were 1 larger.
498 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
499 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
500 NodeId waitingfor = -1;
501 while (pindexWalk->nHeight < nMaxHeight) {
502 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
503 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
504 // as iterating over ~100 CBlockIndex* entries anyway.
505 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
506 vToFetch.resize(nToFetch);
507 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
508 vToFetch[nToFetch - 1] = pindexWalk;
509 for (unsigned int i = nToFetch - 1; i > 0; i--) {
510 vToFetch[i - 1] = vToFetch[i]->pprev;
513 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
514 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
515 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
516 // already part of our chain (and therefore don't need it even if pruned).
517 for (const CBlockIndex* pindex : vToFetch) {
518 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
519 // We consider the chain that this peer is on invalid.
520 return;
522 if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
523 // We wouldn't download this block or its descendants from this peer.
524 return;
526 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
527 if (pindex->nChainTx)
528 state->pindexLastCommonBlock = pindex;
529 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
530 // The block is not already downloaded, and not yet in flight.
531 if (pindex->nHeight > nWindowEnd) {
532 // We reached the end of the window.
533 if (vBlocks.size() == 0 && waitingfor != nodeid) {
534 // We aren't able to fetch anything, but we would be if the download window was one larger.
535 nodeStaller = waitingfor;
537 return;
539 vBlocks.push_back(pindex);
540 if (vBlocks.size() == count) {
541 return;
543 } else if (waitingfor == -1) {
544 // This is the first already-in-flight block.
545 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
551 } // namespace
553 // Returns true for outbound peers, excluding manual connections, feelers, and
554 // one-shots
555 bool IsOutboundDisconnectionCandidate(const CNode *node)
557 return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
560 void PeerLogicValidation::InitializeNode(CNode *pnode) {
561 CAddress addr = pnode->addr;
562 std::string addrName = pnode->GetAddrName();
563 NodeId nodeid = pnode->GetId();
565 LOCK(cs_main);
566 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
568 if(!pnode->fInbound)
569 PushNodeVersion(pnode, connman, GetTime());
572 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
573 fUpdateConnectionTime = false;
574 LOCK(cs_main);
575 CNodeState *state = State(nodeid);
576 assert(state != nullptr);
578 if (state->fSyncStarted)
579 nSyncStarted--;
581 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
582 fUpdateConnectionTime = true;
585 for (const QueuedBlock& entry : state->vBlocksInFlight) {
586 mapBlocksInFlight.erase(entry.hash);
588 EraseOrphansFor(nodeid);
589 nPreferredDownload -= state->fPreferredDownload;
590 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
591 assert(nPeersWithValidatedDownloads >= 0);
592 g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
593 assert(g_outbound_peers_with_protect_from_disconnect >= 0);
595 mapNodeState.erase(nodeid);
597 if (mapNodeState.empty()) {
598 // Do a consistency check after the last peer is removed.
599 assert(mapBlocksInFlight.empty());
600 assert(nPreferredDownload == 0);
601 assert(nPeersWithValidatedDownloads == 0);
602 assert(g_outbound_peers_with_protect_from_disconnect == 0);
604 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
607 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
608 LOCK(cs_main);
609 CNodeState *state = State(nodeid);
610 if (state == nullptr)
611 return false;
612 stats.nMisbehavior = state->nMisbehavior;
613 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
614 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
615 for (const QueuedBlock& queue : state->vBlocksInFlight) {
616 if (queue.pindex)
617 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
619 return true;
622 //////////////////////////////////////////////////////////////////////////////
624 // mapOrphanTransactions
627 void AddToCompactExtraTransactions(const CTransactionRef& tx)
629 size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
630 if (max_extra_txn <= 0)
631 return;
632 if (!vExtraTxnForCompact.size())
633 vExtraTxnForCompact.resize(max_extra_txn);
634 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
635 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
638 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
640 const uint256& hash = tx->GetHash();
641 if (mapOrphanTransactions.count(hash))
642 return false;
644 // Ignore big transactions, to avoid a
645 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
646 // large transaction with a missing parent then we assume
647 // it will rebroadcast it later, after the parent transaction(s)
648 // have been mined or received.
649 // 100 orphans, each of which is at most 99,999 bytes big is
650 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
651 unsigned int sz = GetTransactionWeight(*tx);
652 if (sz >= MAX_STANDARD_TX_WEIGHT)
654 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
655 return false;
658 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
659 assert(ret.second);
660 for (const CTxIn& txin : tx->vin) {
661 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
664 AddToCompactExtraTransactions(tx);
666 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
667 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
668 return true;
671 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
673 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
674 if (it == mapOrphanTransactions.end())
675 return 0;
676 for (const CTxIn& txin : it->second.tx->vin)
678 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
679 if (itPrev == mapOrphanTransactionsByPrev.end())
680 continue;
681 itPrev->second.erase(it);
682 if (itPrev->second.empty())
683 mapOrphanTransactionsByPrev.erase(itPrev);
685 mapOrphanTransactions.erase(it);
686 return 1;
689 void EraseOrphansFor(NodeId peer)
691 int nErased = 0;
692 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
693 while (iter != mapOrphanTransactions.end())
695 std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
696 if (maybeErase->second.fromPeer == peer)
698 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
701 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
705 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
707 unsigned int nEvicted = 0;
708 static int64_t nNextSweep;
709 int64_t nNow = GetTime();
710 if (nNextSweep <= nNow) {
711 // Sweep out expired orphan pool entries:
712 int nErased = 0;
713 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
714 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
715 while (iter != mapOrphanTransactions.end())
717 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
718 if (maybeErase->second.nTimeExpire <= nNow) {
719 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
720 } else {
721 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
724 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
725 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
726 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
728 while (mapOrphanTransactions.size() > nMaxOrphans)
730 // Evict a random orphan:
731 uint256 randomhash = GetRandHash();
732 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
733 if (it == mapOrphanTransactions.end())
734 it = mapOrphanTransactions.begin();
735 EraseOrphanTx(it->first);
736 ++nEvicted;
738 return nEvicted;
741 // Requires cs_main.
742 void Misbehaving(NodeId pnode, int howmuch)
744 if (howmuch == 0)
745 return;
747 CNodeState *state = State(pnode);
748 if (state == nullptr)
749 return;
751 state->nMisbehavior += howmuch;
752 int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
753 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
755 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
756 state->fShouldBan = true;
757 } else
758 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
768 //////////////////////////////////////////////////////////////////////////////
770 // blockchain -> download logic notification
773 // To prevent fingerprinting attacks, only send blocks/headers outside of the
774 // active chain if they are no more than a month older (both in time, and in
775 // best equivalent proof of work) than the best header chain we know about.
776 static bool StaleBlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
778 AssertLockHeld(cs_main);
779 return (pindexBestHeader != nullptr) &&
780 (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
781 (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
784 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler) : connman(connmanIn), m_stale_tip_check_time(0) {
785 // Initialize global variables that cannot be constructed at startup.
786 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
788 const Consensus::Params& consensusParams = Params().GetConsensus();
789 // Stale tip checking and peer eviction are on two different timers, but we
790 // don't want them to get out of sync due to drift in the scheduler, so we
791 // combine them in one function and schedule at the quicker (peer-eviction)
792 // timer.
793 static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
794 scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
797 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
798 LOCK(cs_main);
800 std::vector<uint256> vOrphanErase;
802 for (const CTransactionRef& ptx : pblock->vtx) {
803 const CTransaction& tx = *ptx;
805 // Which orphan pool entries must we evict?
806 for (const auto& txin : tx.vin) {
807 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
808 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
809 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
810 const CTransaction& orphanTx = *(*mi)->second.tx;
811 const uint256& orphanHash = orphanTx.GetHash();
812 vOrphanErase.push_back(orphanHash);
817 // Erase orphan transactions include or precluded by this block
818 if (vOrphanErase.size()) {
819 int nErased = 0;
820 for (uint256 &orphanHash : vOrphanErase) {
821 nErased += EraseOrphanTx(orphanHash);
823 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
826 g_last_tip_update = GetTime();
829 // All of the following cache a recent block, and are protected by cs_most_recent_block
830 static CCriticalSection cs_most_recent_block;
831 static std::shared_ptr<const CBlock> most_recent_block;
832 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
833 static uint256 most_recent_block_hash;
834 static bool fWitnessesPresentInMostRecentCompactBlock;
836 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
837 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
838 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
840 LOCK(cs_main);
842 static int nHighestFastAnnounce = 0;
843 if (pindex->nHeight <= nHighestFastAnnounce)
844 return;
845 nHighestFastAnnounce = pindex->nHeight;
847 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
848 uint256 hashBlock(pblock->GetHash());
851 LOCK(cs_most_recent_block);
852 most_recent_block_hash = hashBlock;
853 most_recent_block = pblock;
854 most_recent_compact_block = pcmpctblock;
855 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
858 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
859 // TODO: Avoid the repeated-serialization here
860 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
861 return;
862 ProcessBlockAvailability(pnode->GetId());
863 CNodeState &state = *State(pnode->GetId());
864 // If the peer has, or we announced to them the previous block already,
865 // but we don't think they have this one, go ahead and announce it
866 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
867 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
869 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
870 hashBlock.ToString(), pnode->GetId());
871 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
872 state.pindexBestHeaderSent = pindex;
877 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
878 const int nNewHeight = pindexNew->nHeight;
879 connman->SetBestHeight(nNewHeight);
881 if (!fInitialDownload) {
882 // Find the hashes of all blocks that weren't previously in the best chain.
883 std::vector<uint256> vHashes;
884 const CBlockIndex *pindexToAnnounce = pindexNew;
885 while (pindexToAnnounce != pindexFork) {
886 vHashes.push_back(pindexToAnnounce->GetBlockHash());
887 pindexToAnnounce = pindexToAnnounce->pprev;
888 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
889 // Limit announcements in case of a huge reorganization.
890 // Rely on the peer's synchronization mechanism in that case.
891 break;
894 // Relay inventory, but don't relay old inventory during initial block download.
895 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
896 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
897 for (const uint256& hash : reverse_iterate(vHashes)) {
898 pnode->PushBlockHash(hash);
902 connman->WakeMessageHandler();
905 nTimeBestReceived = GetTime();
908 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
909 LOCK(cs_main);
911 const uint256 hash(block.GetHash());
912 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
914 int nDoS = 0;
915 if (state.IsInvalid(nDoS)) {
916 // Don't send reject message with code 0 or an internal reject code.
917 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
918 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
919 State(it->second.first)->rejects.push_back(reject);
920 if (nDoS > 0 && it->second.second)
921 Misbehaving(it->second.first, nDoS);
924 // Check that:
925 // 1. The block is valid
926 // 2. We're not in initial block download
927 // 3. This is currently the best block we're aware of. We haven't updated
928 // the tip yet so we have no way to check this directly here. Instead we
929 // just check that there are currently no other blocks in flight.
930 else if (state.IsValid() &&
931 !IsInitialBlockDownload() &&
932 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
933 if (it != mapBlockSource.end()) {
934 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
937 if (it != mapBlockSource.end())
938 mapBlockSource.erase(it);
941 //////////////////////////////////////////////////////////////////////////////
943 // Messages
947 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
949 switch (inv.type)
951 case MSG_TX:
952 case MSG_WITNESS_TX:
954 assert(recentRejects);
955 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
957 // If the chain tip has changed previously rejected transactions
958 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
959 // or a double-spend. Reset the rejects filter and give those
960 // txs a second chance.
961 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
962 recentRejects->reset();
965 return recentRejects->contains(inv.hash) ||
966 mempool.exists(inv.hash) ||
967 mapOrphanTransactions.count(inv.hash) ||
968 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
969 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
971 case MSG_BLOCK:
972 case MSG_WITNESS_BLOCK:
973 return mapBlockIndex.count(inv.hash);
975 // Don't know what it is, just say we already got one
976 return true;
979 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
981 CInv inv(MSG_TX, tx.GetHash());
982 connman->ForEachNode([&inv](CNode* pnode)
984 pnode->PushInventory(inv);
988 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
990 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
992 // Relay to a limited number of other nodes
993 // Use deterministic randomness to send to the same nodes for 24 hours
994 // at a time so the addrKnowns of the chosen nodes prevent repeats
995 uint64_t hashAddr = addr.GetHash();
996 const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
997 FastRandomContext insecure_rand;
999 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
1000 assert(nRelayNodes <= best.size());
1002 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
1003 if (pnode->nVersion >= CADDR_TIME_VERSION) {
1004 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
1005 for (unsigned int i = 0; i < nRelayNodes; i++) {
1006 if (hashKey > best[i].first) {
1007 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1008 best[i] = std::make_pair(hashKey, pnode);
1009 break;
1015 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
1016 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1017 best[i].second->PushAddress(addr, insecure_rand);
1021 connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
1024 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1026 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1027 std::vector<CInv> vNotFound;
1028 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1029 LOCK(cs_main);
1031 while (it != pfrom->vRecvGetData.end()) {
1032 // Don't bother if send buffer is too full to respond anyway
1033 if (pfrom->fPauseSend)
1034 break;
1036 const CInv &inv = *it;
1038 if (interruptMsgProc)
1039 return;
1041 it++;
1043 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1045 bool send = false;
1046 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1047 std::shared_ptr<const CBlock> a_recent_block;
1048 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1049 bool fWitnessesPresentInARecentCompactBlock;
1051 LOCK(cs_most_recent_block);
1052 a_recent_block = most_recent_block;
1053 a_recent_compact_block = most_recent_compact_block;
1054 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1056 if (mi != mapBlockIndex.end())
1058 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1059 mi->second->IsValid(BLOCK_VALID_TREE)) {
1060 // If we have the block and all of its parents, but have not yet validated it,
1061 // we might be in the middle of connecting it (ie in the unlock of cs_main
1062 // before ActivateBestChain but after AcceptBlock).
1063 // In this case, we need to run ActivateBestChain prior to checking the relay
1064 // conditions below.
1065 CValidationState dummy;
1066 ActivateBestChain(dummy, Params(), a_recent_block);
1068 if (chainActive.Contains(mi->second)) {
1069 send = true;
1070 } else {
1071 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1072 StaleBlockRequestAllowed(mi->second, consensusParams);
1073 if (!send) {
1074 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1078 // disconnect node in case we have reached the outbound limit for serving historical blocks
1079 // never disconnect whitelisted nodes
1080 if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1082 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1084 //disconnect node
1085 pfrom->fDisconnect = true;
1086 send = false;
1088 // Pruned nodes may have deleted the block, so check whether
1089 // it's available before trying to send.
1090 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1092 std::shared_ptr<const CBlock> pblock;
1093 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1094 pblock = a_recent_block;
1095 } else {
1096 // Send block from disk
1097 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1098 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1099 assert(!"cannot load block from disk");
1100 pblock = pblockRead;
1102 if (inv.type == MSG_BLOCK)
1103 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1104 else if (inv.type == MSG_WITNESS_BLOCK)
1105 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1106 else if (inv.type == MSG_FILTERED_BLOCK)
1108 bool sendMerkleBlock = false;
1109 CMerkleBlock merkleBlock;
1111 LOCK(pfrom->cs_filter);
1112 if (pfrom->pfilter) {
1113 sendMerkleBlock = true;
1114 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1117 if (sendMerkleBlock) {
1118 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1119 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1120 // This avoids hurting performance by pointlessly requiring a round-trip
1121 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1122 // they must either disconnect and retry or request the full block.
1123 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1124 // however we MUST always provide at least what the remote peer needs
1125 typedef std::pair<unsigned int, uint256> PairType;
1126 for (PairType& pair : merkleBlock.vMatchedTxn)
1127 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1129 // else
1130 // no response
1132 else if (inv.type == MSG_CMPCT_BLOCK)
1134 // If a peer is asking for old blocks, we're almost guaranteed
1135 // they won't have a useful mempool to match against a compact block,
1136 // and we don't feel like constructing the object for them, so
1137 // instead we respond with the full, non-compact block.
1138 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1139 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1140 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1141 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1142 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1143 } else {
1144 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1145 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1147 } else {
1148 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1152 // Trigger the peer node to send a getblocks request for the next batch of inventory
1153 if (inv.hash == pfrom->hashContinue)
1155 // Bypass PushInventory, this must send even if redundant,
1156 // and we want it right after the last block so they don't
1157 // wait for other stuff first.
1158 std::vector<CInv> vInv;
1159 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1160 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1161 pfrom->hashContinue.SetNull();
1165 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1167 // Send stream from relay memory
1168 bool push = false;
1169 auto mi = mapRelay.find(inv.hash);
1170 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1171 if (mi != mapRelay.end()) {
1172 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1173 push = true;
1174 } else if (pfrom->timeLastMempoolReq) {
1175 auto txinfo = mempool.info(inv.hash);
1176 // To protect privacy, do not answer getdata using the mempool when
1177 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1178 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1179 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1180 push = true;
1183 if (!push) {
1184 vNotFound.push_back(inv);
1188 // Track requests for our stuff.
1189 GetMainSignals().Inventory(inv.hash);
1191 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1192 break;
1196 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1198 if (!vNotFound.empty()) {
1199 // Let the peer know that we didn't find what it asked for, so it doesn't
1200 // have to wait around forever. Currently only SPV clients actually care
1201 // about this message: it's needed when they are recursively walking the
1202 // dependencies of relevant unconfirmed transactions. SPV clients want to
1203 // do that because they want to know about (and store and rebroadcast and
1204 // risk analyze) the dependencies of transactions relevant to them, without
1205 // having to download the entire memory pool.
1206 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1210 uint32_t GetFetchFlags(CNode* pfrom) {
1211 uint32_t nFetchFlags = 0;
1212 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1213 nFetchFlags |= MSG_WITNESS_FLAG;
1215 return nFetchFlags;
1218 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
1219 BlockTransactions resp(req);
1220 for (size_t i = 0; i < req.indexes.size(); i++) {
1221 if (req.indexes[i] >= block.vtx.size()) {
1222 LOCK(cs_main);
1223 Misbehaving(pfrom->GetId(), 100);
1224 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1225 return;
1227 resp.txn[i] = block.vtx[req.indexes[i]];
1229 LOCK(cs_main);
1230 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1231 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1232 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1235 bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
1237 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1238 size_t nCount = headers.size();
1240 if (nCount == 0) {
1241 // Nothing interesting. Stop asking this peers for more headers.
1242 return true;
1245 bool received_new_header = false;
1246 const CBlockIndex *pindexLast = nullptr;
1248 LOCK(cs_main);
1249 CNodeState *nodestate = State(pfrom->GetId());
1251 // If this looks like it could be a block announcement (nCount <
1252 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1253 // don't connect:
1254 // - Send a getheaders message in response to try to connect the chain.
1255 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1256 // don't connect before giving DoS points
1257 // - Once a headers message is received that is valid and does connect,
1258 // nUnconnectingHeaders gets reset back to 0.
1259 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1260 nodestate->nUnconnectingHeaders++;
1261 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1262 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1263 headers[0].GetHash().ToString(),
1264 headers[0].hashPrevBlock.ToString(),
1265 pindexBestHeader->nHeight,
1266 pfrom->GetId(), nodestate->nUnconnectingHeaders);
1267 // Set hashLastUnknownBlock for this peer, so that if we
1268 // eventually get the headers - even from a different peer -
1269 // we can use this peer to download.
1270 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
1272 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
1273 Misbehaving(pfrom->GetId(), 20);
1275 return true;
1278 uint256 hashLastBlock;
1279 for (const CBlockHeader& header : headers) {
1280 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
1281 Misbehaving(pfrom->GetId(), 20);
1282 return error("non-continuous headers sequence");
1284 hashLastBlock = header.GetHash();
1287 // If we don't have the last header, then they'll have given us
1288 // something new (if these headers are valid).
1289 if (mapBlockIndex.find(hashLastBlock) == mapBlockIndex.end()) {
1290 received_new_header = true;
1294 CValidationState state;
1295 CBlockHeader first_invalid_header;
1296 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) {
1297 int nDoS;
1298 if (state.IsInvalid(nDoS)) {
1299 if (nDoS > 0) {
1300 LOCK(cs_main);
1301 Misbehaving(pfrom->GetId(), nDoS);
1303 if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
1304 // Goal: don't allow outbound peers to use up our outbound
1305 // connection slots if they are on incompatible chains.
1307 // We ask the caller to set punish_invalid appropriately based
1308 // on the peer and the method of header delivery (compact
1309 // blocks are allowed to be invalid in some circumstances,
1310 // under BIP 152).
1311 // Here, we try to detect the narrow situation that we have a
1312 // valid block header (ie it was valid at the time the header
1313 // was received, and hence stored in mapBlockIndex) but know the
1314 // block is invalid, and that a peer has announced that same
1315 // block as being on its active chain.
1316 // Disconnect the peer in such a situation.
1318 // Note: if the header that is invalid was not accepted to our
1319 // mapBlockIndex at all, that may also be grounds for
1320 // disconnecting the peer, as the chain they are on is likely
1321 // to be incompatible. However, there is a circumstance where
1322 // that does not hold: if the header's timestamp is more than
1323 // 2 hours ahead of our current time. In that case, the header
1324 // may become valid in the future, and we don't want to
1325 // disconnect a peer merely for serving us one too-far-ahead
1326 // block header, to prevent an attacker from splitting the
1327 // network by mining a block right at the 2 hour boundary.
1329 // TODO: update the DoS logic (or, rather, rewrite the
1330 // DoS-interface between validation and net_processing) so that
1331 // the interface is cleaner, and so that we disconnect on all the
1332 // reasons that a peer's headers chain is incompatible
1333 // with ours (eg block->nVersion softforks, MTP violations,
1334 // etc), and not just the duplicate-invalid case.
1335 pfrom->fDisconnect = true;
1337 return error("invalid header received");
1342 LOCK(cs_main);
1343 CNodeState *nodestate = State(pfrom->GetId());
1344 if (nodestate->nUnconnectingHeaders > 0) {
1345 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
1347 nodestate->nUnconnectingHeaders = 0;
1349 assert(pindexLast);
1350 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1352 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1353 // because it is set in UpdateBlockAvailability. Some nullptr checks
1354 // are still present, however, as belt-and-suspenders.
1356 if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) {
1357 nodestate->m_last_block_announcement = GetTime();
1360 if (nCount == MAX_HEADERS_RESULTS) {
1361 // Headers message had its maximum size; the peer may have more headers.
1362 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1363 // from there instead.
1364 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1365 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
1368 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
1369 // If this set of headers is valid and ends in a block with at least as
1370 // much work as our tip, download as much as possible.
1371 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
1372 std::vector<const CBlockIndex*> vToFetch;
1373 const CBlockIndex *pindexWalk = pindexLast;
1374 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1375 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1376 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
1377 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
1378 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
1379 // We don't have this block, and it's not yet in flight.
1380 vToFetch.push_back(pindexWalk);
1382 pindexWalk = pindexWalk->pprev;
1384 // If pindexWalk still isn't on our main chain, we're looking at a
1385 // very large reorg at a time we think we're close to caught up to
1386 // the main chain -- this shouldn't really happen. Bail out on the
1387 // direct fetch and rely on parallel download instead.
1388 if (!chainActive.Contains(pindexWalk)) {
1389 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
1390 pindexLast->GetBlockHash().ToString(),
1391 pindexLast->nHeight);
1392 } else {
1393 std::vector<CInv> vGetData;
1394 // Download as much as possible, from earliest to latest.
1395 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
1396 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1397 // Can't download any more from this peer
1398 break;
1400 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1401 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
1402 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
1403 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1404 pindex->GetBlockHash().ToString(), pfrom->GetId());
1406 if (vGetData.size() > 1) {
1407 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1408 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
1410 if (vGetData.size() > 0) {
1411 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1412 // In any case, we want to download using a compact block, not a regular one
1413 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
1415 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
1419 // If we're in IBD, we want outbound peers that will serve us a useful
1420 // chain. Disconnect peers that are on chains with insufficient work.
1421 if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
1422 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1423 // headers to fetch from this peer.
1424 if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1425 // This peer has too little work on their headers chain to help
1426 // us sync -- disconnect if using an outbound slot (unless
1427 // whitelisted or addnode).
1428 // Note: We compare their tip to nMinimumChainWork (rather than
1429 // chainActive.Tip()) because we won't start block download
1430 // until we have a headers chain that has at least
1431 // nMinimumChainWork, even if a peer has a chain past our tip,
1432 // as an anti-DoS measure.
1433 if (IsOutboundDisconnectionCandidate(pfrom)) {
1434 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
1435 pfrom->fDisconnect = true;
1440 if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
1441 // If this is an outbound peer, check to see if we should protect
1442 // it from the bad/lagging chain logic.
1443 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) {
1444 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId());
1445 nodestate->m_chain_sync.m_protect = true;
1446 ++g_outbound_peers_with_protect_from_disconnect;
1451 return true;
1454 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1456 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1457 if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
1459 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1460 return true;
1464 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1465 (strCommand == NetMsgType::FILTERLOAD ||
1466 strCommand == NetMsgType::FILTERADD))
1468 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1469 LOCK(cs_main);
1470 Misbehaving(pfrom->GetId(), 100);
1471 return false;
1472 } else {
1473 pfrom->fDisconnect = true;
1474 return false;
1478 if (strCommand == NetMsgType::REJECT)
1480 if (LogAcceptCategory(BCLog::NET)) {
1481 try {
1482 std::string strMsg; unsigned char ccode; std::string strReason;
1483 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1485 std::ostringstream ss;
1486 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1488 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1490 uint256 hash;
1491 vRecv >> hash;
1492 ss << ": hash " << hash.ToString();
1494 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1495 } catch (const std::ios_base::failure&) {
1496 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1497 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1502 else if (strCommand == NetMsgType::VERSION)
1504 // Each connection can only send one version message
1505 if (pfrom->nVersion != 0)
1507 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1508 LOCK(cs_main);
1509 Misbehaving(pfrom->GetId(), 1);
1510 return false;
1513 int64_t nTime;
1514 CAddress addrMe;
1515 CAddress addrFrom;
1516 uint64_t nNonce = 1;
1517 uint64_t nServiceInt;
1518 ServiceFlags nServices;
1519 int nVersion;
1520 int nSendVersion;
1521 std::string strSubVer;
1522 std::string cleanSubVer;
1523 int nStartingHeight = -1;
1524 bool fRelay = true;
1526 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1527 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1528 nServices = ServiceFlags(nServiceInt);
1529 if (!pfrom->fInbound)
1531 connman->SetServices(pfrom->addr, nServices);
1533 if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
1535 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
1536 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1537 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
1538 pfrom->fDisconnect = true;
1539 return false;
1542 if (nServices & ((1 << 7) | (1 << 5))) {
1543 if (GetTime() < 1533096000) {
1544 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1545 // These bits have been used as a flag to indicate that a node is running incompatible
1546 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1547 // based on these service bits, at least for a while.
1548 pfrom->fDisconnect = true;
1549 return false;
1553 if (nVersion < MIN_PEER_PROTO_VERSION)
1555 // disconnect from peers older than this proto version
1556 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1557 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1558 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1559 pfrom->fDisconnect = true;
1560 return false;
1563 if (nVersion == 10300)
1564 nVersion = 300;
1565 if (!vRecv.empty())
1566 vRecv >> addrFrom >> nNonce;
1567 if (!vRecv.empty()) {
1568 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1569 cleanSubVer = SanitizeString(strSubVer);
1571 if (!vRecv.empty()) {
1572 vRecv >> nStartingHeight;
1574 if (!vRecv.empty())
1575 vRecv >> fRelay;
1576 // Disconnect if we connected to ourself
1577 if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
1579 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1580 pfrom->fDisconnect = true;
1581 return true;
1584 if (pfrom->fInbound && addrMe.IsRoutable())
1586 SeenLocal(addrMe);
1589 // Be shy and don't send version until we hear
1590 if (pfrom->fInbound)
1591 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1593 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1595 pfrom->nServices = nServices;
1596 pfrom->SetAddrLocal(addrMe);
1598 LOCK(pfrom->cs_SubVer);
1599 pfrom->strSubVer = strSubVer;
1600 pfrom->cleanSubVer = cleanSubVer;
1602 pfrom->nStartingHeight = nStartingHeight;
1603 pfrom->fClient = !(nServices & NODE_NETWORK);
1605 LOCK(pfrom->cs_filter);
1606 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1609 // Change version
1610 pfrom->SetSendVersion(nSendVersion);
1611 pfrom->nVersion = nVersion;
1613 if((nServices & NODE_WITNESS))
1615 LOCK(cs_main);
1616 State(pfrom->GetId())->fHaveWitness = true;
1619 // Potentially mark this peer as a preferred download peer.
1621 LOCK(cs_main);
1622 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1625 if (!pfrom->fInbound)
1627 // Advertise our address
1628 if (fListen && !IsInitialBlockDownload())
1630 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1631 FastRandomContext insecure_rand;
1632 if (addr.IsRoutable())
1634 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1635 pfrom->PushAddress(addr, insecure_rand);
1636 } else if (IsPeerAddrLocalGood(pfrom)) {
1637 addr.SetIP(addrMe);
1638 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1639 pfrom->PushAddress(addr, insecure_rand);
1643 // Get recent addresses
1644 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
1646 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1647 pfrom->fGetAddr = true;
1649 connman->MarkAddressGood(pfrom->addr);
1652 std::string remoteAddr;
1653 if (fLogIPs)
1654 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1656 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1657 cleanSubVer, pfrom->nVersion,
1658 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1659 remoteAddr);
1661 int64_t nTimeOffset = nTime - GetTime();
1662 pfrom->nTimeOffset = nTimeOffset;
1663 AddTimeData(pfrom->addr, nTimeOffset);
1665 // If the peer is old enough to have the old alert system, send it the final alert.
1666 if (pfrom->nVersion <= 70012) {
1667 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1668 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1671 // Feeler connections exist only to verify if address is online.
1672 if (pfrom->fFeeler) {
1673 assert(pfrom->fInbound == false);
1674 pfrom->fDisconnect = true;
1676 return true;
1680 else if (pfrom->nVersion == 0)
1682 // Must have a version message before anything else
1683 LOCK(cs_main);
1684 Misbehaving(pfrom->GetId(), 1);
1685 return false;
1688 // At this point, the outgoing message serialization version can't change.
1689 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1691 if (strCommand == NetMsgType::VERACK)
1693 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1695 if (!pfrom->fInbound) {
1696 // Mark this node as currently connected, so we update its timestamp later.
1697 LOCK(cs_main);
1698 State(pfrom->GetId())->fCurrentlyConnected = true;
1701 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1702 // Tell our peer we prefer to receive headers rather than inv's
1703 // We send this to non-NODE NETWORK peers as well, because even
1704 // non-NODE NETWORK peers can announce blocks (such as pruning
1705 // nodes)
1706 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1708 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1709 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1710 // However, we do not request new block announcements using
1711 // cmpctblock messages.
1712 // We send this to non-NODE NETWORK peers as well, because
1713 // they may wish to request compact blocks from us
1714 bool fAnnounceUsingCMPCTBLOCK = false;
1715 uint64_t nCMPCTBLOCKVersion = 2;
1716 if (pfrom->GetLocalServices() & NODE_WITNESS)
1717 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1718 nCMPCTBLOCKVersion = 1;
1719 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1721 pfrom->fSuccessfullyConnected = true;
1724 else if (!pfrom->fSuccessfullyConnected)
1726 // Must have a verack message before anything else
1727 LOCK(cs_main);
1728 Misbehaving(pfrom->GetId(), 1);
1729 return false;
1732 else if (strCommand == NetMsgType::ADDR)
1734 std::vector<CAddress> vAddr;
1735 vRecv >> vAddr;
1737 // Don't want addr from older versions unless seeding
1738 if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
1739 return true;
1740 if (vAddr.size() > 1000)
1742 LOCK(cs_main);
1743 Misbehaving(pfrom->GetId(), 20);
1744 return error("message addr size() = %u", vAddr.size());
1747 // Store the new addresses
1748 std::vector<CAddress> vAddrOk;
1749 int64_t nNow = GetAdjustedTime();
1750 int64_t nSince = nNow - 10 * 60;
1751 for (CAddress& addr : vAddr)
1753 if (interruptMsgProc)
1754 return true;
1756 // We only bother storing full nodes, though this may include
1757 // things which we would not make an outbound connection to, in
1758 // part because we may make feeler connections to them.
1759 if (!MayHaveUsefulAddressDB(addr.nServices))
1760 continue;
1762 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1763 addr.nTime = nNow - 5 * 24 * 60 * 60;
1764 pfrom->AddAddressKnown(addr);
1765 bool fReachable = IsReachable(addr);
1766 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1768 // Relay to a limited number of other nodes
1769 RelayAddress(addr, fReachable, connman);
1771 // Do not store addresses outside our network
1772 if (fReachable)
1773 vAddrOk.push_back(addr);
1775 connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1776 if (vAddr.size() < 1000)
1777 pfrom->fGetAddr = false;
1778 if (pfrom->fOneShot)
1779 pfrom->fDisconnect = true;
1782 else if (strCommand == NetMsgType::SENDHEADERS)
1784 LOCK(cs_main);
1785 State(pfrom->GetId())->fPreferHeaders = true;
1788 else if (strCommand == NetMsgType::SENDCMPCT)
1790 bool fAnnounceUsingCMPCTBLOCK = false;
1791 uint64_t nCMPCTBLOCKVersion = 0;
1792 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1793 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1794 LOCK(cs_main);
1795 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1796 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1797 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1798 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1800 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1801 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1802 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1803 if (pfrom->GetLocalServices() & NODE_WITNESS)
1804 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1805 else
1806 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1812 else if (strCommand == NetMsgType::INV)
1814 std::vector<CInv> vInv;
1815 vRecv >> vInv;
1816 if (vInv.size() > MAX_INV_SZ)
1818 LOCK(cs_main);
1819 Misbehaving(pfrom->GetId(), 20);
1820 return error("message inv size() = %u", vInv.size());
1823 bool fBlocksOnly = !fRelayTxes;
1825 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1826 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1827 fBlocksOnly = false;
1829 LOCK(cs_main);
1831 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1833 for (CInv &inv : vInv)
1835 if (interruptMsgProc)
1836 return true;
1838 bool fAlreadyHave = AlreadyHave(inv);
1839 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1841 if (inv.type == MSG_TX) {
1842 inv.type |= nFetchFlags;
1845 if (inv.type == MSG_BLOCK) {
1846 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1847 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1848 // We used to request the full block here, but since headers-announcements are now the
1849 // primary method of announcement on the network, and since, in the case that a node
1850 // fell back to inv we probably have a reorg which we should get the headers for first,
1851 // we now only provide a getheaders response here. When we receive the headers, we will
1852 // then ask for the blocks we need.
1853 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1854 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1857 else
1859 pfrom->AddInventoryKnown(inv);
1860 if (fBlocksOnly) {
1861 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1862 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1863 pfrom->AskFor(inv);
1867 // Track requests for our stuff
1868 GetMainSignals().Inventory(inv.hash);
1873 else if (strCommand == NetMsgType::GETDATA)
1875 std::vector<CInv> vInv;
1876 vRecv >> vInv;
1877 if (vInv.size() > MAX_INV_SZ)
1879 LOCK(cs_main);
1880 Misbehaving(pfrom->GetId(), 20);
1881 return error("message getdata size() = %u", vInv.size());
1884 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1886 if (vInv.size() > 0) {
1887 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1890 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1891 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1895 else if (strCommand == NetMsgType::GETBLOCKS)
1897 CBlockLocator locator;
1898 uint256 hashStop;
1899 vRecv >> locator >> hashStop;
1901 // We might have announced the currently-being-connected tip using a
1902 // compact block, which resulted in the peer sending a getblocks
1903 // request, which we would otherwise respond to without the new block.
1904 // To avoid this situation we simply verify that we are on our best
1905 // known chain now. This is super overkill, but we handle it better
1906 // for getheaders requests, and there are no known nodes which support
1907 // compact blocks but still use getblocks to request blocks.
1909 std::shared_ptr<const CBlock> a_recent_block;
1911 LOCK(cs_most_recent_block);
1912 a_recent_block = most_recent_block;
1914 CValidationState dummy;
1915 ActivateBestChain(dummy, Params(), a_recent_block);
1918 LOCK(cs_main);
1920 // Find the last block the caller has in the main chain
1921 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1923 // Send the rest of the chain
1924 if (pindex)
1925 pindex = chainActive.Next(pindex);
1926 int nLimit = 500;
1927 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());
1928 for (; pindex; pindex = chainActive.Next(pindex))
1930 if (pindex->GetBlockHash() == hashStop)
1932 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1933 break;
1935 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1936 // for some reasonable time window (1 hour) that block relay might require.
1937 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1938 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1940 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1941 break;
1943 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1944 if (--nLimit <= 0)
1946 // When this block is requested, we'll send an inv that'll
1947 // trigger the peer to getblocks the next batch of inventory.
1948 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1949 pfrom->hashContinue = pindex->GetBlockHash();
1950 break;
1956 else if (strCommand == NetMsgType::GETBLOCKTXN)
1958 BlockTransactionsRequest req;
1959 vRecv >> req;
1961 std::shared_ptr<const CBlock> recent_block;
1963 LOCK(cs_most_recent_block);
1964 if (most_recent_block_hash == req.blockhash)
1965 recent_block = most_recent_block;
1966 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1968 if (recent_block) {
1969 SendBlockTransactions(*recent_block, req, pfrom, connman);
1970 return true;
1973 LOCK(cs_main);
1975 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1976 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1977 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
1978 return true;
1981 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1982 // If an older block is requested (should never happen in practice,
1983 // but can happen in tests) send a block response instead of a
1984 // blocktxn response. Sending a full block response instead of a
1985 // small blocktxn response is preferable in the case where a peer
1986 // might maliciously send lots of getblocktxn requests to trigger
1987 // expensive disk reads, because it will require the peer to
1988 // actually receive all the data read from disk over the network.
1989 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
1990 CInv inv;
1991 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
1992 inv.hash = req.blockhash;
1993 pfrom->vRecvGetData.push_back(inv);
1994 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1995 return true;
1998 CBlock block;
1999 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
2000 assert(ret);
2002 SendBlockTransactions(block, req, pfrom, connman);
2006 else if (strCommand == NetMsgType::GETHEADERS)
2008 CBlockLocator locator;
2009 uint256 hashStop;
2010 vRecv >> locator >> hashStop;
2012 LOCK(cs_main);
2013 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
2014 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
2015 return true;
2018 CNodeState *nodestate = State(pfrom->GetId());
2019 const CBlockIndex* pindex = nullptr;
2020 if (locator.IsNull())
2022 // If locator is null, return the hashStop block
2023 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
2024 if (mi == mapBlockIndex.end())
2025 return true;
2026 pindex = (*mi).second;
2028 if (!chainActive.Contains(pindex) &&
2029 !StaleBlockRequestAllowed(pindex, chainparams.GetConsensus())) {
2030 LogPrintf("%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
2031 return true;
2034 else
2036 // Find the last block the caller has in the main chain
2037 pindex = FindForkInGlobalIndex(chainActive, locator);
2038 if (pindex)
2039 pindex = chainActive.Next(pindex);
2042 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2043 std::vector<CBlock> vHeaders;
2044 int nLimit = MAX_HEADERS_RESULTS;
2045 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
2046 for (; pindex; pindex = chainActive.Next(pindex))
2048 vHeaders.push_back(pindex->GetBlockHeader());
2049 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2050 break;
2052 // pindex can be nullptr either if we sent chainActive.Tip() OR
2053 // if our peer has chainActive.Tip() (and thus we are sending an empty
2054 // headers message). In both cases it's safe to update
2055 // pindexBestHeaderSent to be our tip.
2057 // It is important that we simply reset the BestHeaderSent value here,
2058 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2059 // the currently-being-connected tip using a compact block, which
2060 // resulted in the peer sending a headers request, which we respond to
2061 // without the new block. By resetting the BestHeaderSent, we ensure we
2062 // will re-announce the new block via headers (or compact blocks again)
2063 // in the SendMessages logic.
2064 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
2065 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2069 else if (strCommand == NetMsgType::TX)
2071 // Stop processing the transaction early if
2072 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2073 if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
2075 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
2076 return true;
2079 std::deque<COutPoint> vWorkQueue;
2080 std::vector<uint256> vEraseQueue;
2081 CTransactionRef ptx;
2082 vRecv >> ptx;
2083 const CTransaction& tx = *ptx;
2085 CInv inv(MSG_TX, tx.GetHash());
2086 pfrom->AddInventoryKnown(inv);
2088 LOCK(cs_main);
2090 bool fMissingInputs = false;
2091 CValidationState state;
2093 pfrom->setAskFor.erase(inv.hash);
2094 mapAlreadyAskedFor.erase(inv.hash);
2096 std::list<CTransactionRef> lRemovedTxn;
2098 if (!AlreadyHave(inv) &&
2099 AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2100 mempool.check(pcoinsTip);
2101 RelayTransaction(tx, connman);
2102 for (unsigned int i = 0; i < tx.vout.size(); i++) {
2103 vWorkQueue.emplace_back(inv.hash, i);
2106 pfrom->nLastTXTime = GetTime();
2108 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2109 pfrom->GetId(),
2110 tx.GetHash().ToString(),
2111 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
2113 // Recursively process any orphan transactions that depended on this one
2114 std::set<NodeId> setMisbehaving;
2115 while (!vWorkQueue.empty()) {
2116 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
2117 vWorkQueue.pop_front();
2118 if (itByPrev == mapOrphanTransactionsByPrev.end())
2119 continue;
2120 for (auto mi = itByPrev->second.begin();
2121 mi != itByPrev->second.end();
2122 ++mi)
2124 const CTransactionRef& porphanTx = (*mi)->second.tx;
2125 const CTransaction& orphanTx = *porphanTx;
2126 const uint256& orphanHash = orphanTx.GetHash();
2127 NodeId fromPeer = (*mi)->second.fromPeer;
2128 bool fMissingInputs2 = false;
2129 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2130 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2131 // anyone relaying LegitTxX banned)
2132 CValidationState stateDummy;
2135 if (setMisbehaving.count(fromPeer))
2136 continue;
2137 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2138 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2139 RelayTransaction(orphanTx, connman);
2140 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
2141 vWorkQueue.emplace_back(orphanHash, i);
2143 vEraseQueue.push_back(orphanHash);
2145 else if (!fMissingInputs2)
2147 int nDos = 0;
2148 if (stateDummy.IsInvalid(nDos) && nDos > 0)
2150 // Punish peer that gave us an invalid orphan tx
2151 Misbehaving(fromPeer, nDos);
2152 setMisbehaving.insert(fromPeer);
2153 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
2155 // Has inputs but not accepted to mempool
2156 // Probably non-standard or insufficient fee
2157 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2158 vEraseQueue.push_back(orphanHash);
2159 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
2160 // Do not use rejection cache for witness transactions or
2161 // witness-stripped transactions, as they can have been malleated.
2162 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2163 assert(recentRejects);
2164 recentRejects->insert(orphanHash);
2167 mempool.check(pcoinsTip);
2171 for (uint256 hash : vEraseQueue)
2172 EraseOrphanTx(hash);
2174 else if (fMissingInputs)
2176 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
2177 for (const CTxIn& txin : tx.vin) {
2178 if (recentRejects->contains(txin.prevout.hash)) {
2179 fRejectedParents = true;
2180 break;
2183 if (!fRejectedParents) {
2184 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2185 for (const CTxIn& txin : tx.vin) {
2186 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
2187 pfrom->AddInventoryKnown(_inv);
2188 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
2190 AddOrphanTx(ptx, pfrom->GetId());
2192 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2193 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
2194 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
2195 if (nEvicted > 0) {
2196 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
2198 } else {
2199 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
2200 // We will continue to reject this tx since it has rejected
2201 // parents so avoid re-requesting it from other peers.
2202 recentRejects->insert(tx.GetHash());
2204 } else {
2205 if (!tx.HasWitness() && !state.CorruptionPossible()) {
2206 // Do not use rejection cache for witness transactions or
2207 // witness-stripped transactions, as they can have been malleated.
2208 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2209 assert(recentRejects);
2210 recentRejects->insert(tx.GetHash());
2211 if (RecursiveDynamicUsage(*ptx) < 100000) {
2212 AddToCompactExtraTransactions(ptx);
2214 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
2215 AddToCompactExtraTransactions(ptx);
2218 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
2219 // Always relay transactions received from whitelisted peers, even
2220 // if they were already in the mempool or rejected from it due
2221 // to policy, allowing the node to function as a gateway for
2222 // nodes hidden behind it.
2224 // Never relay transactions that we would assign a non-zero DoS
2225 // score for, as we expect peers to do the same with us in that
2226 // case.
2227 int nDoS = 0;
2228 if (!state.IsInvalid(nDoS) || nDoS == 0) {
2229 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
2230 RelayTransaction(tx, connman);
2231 } else {
2232 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
2237 for (const CTransactionRef& removedTx : lRemovedTxn)
2238 AddToCompactExtraTransactions(removedTx);
2240 int nDoS = 0;
2241 if (state.IsInvalid(nDoS))
2243 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
2244 pfrom->GetId(),
2245 FormatStateMessage(state));
2246 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
2247 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
2248 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
2249 if (nDoS > 0) {
2250 Misbehaving(pfrom->GetId(), nDoS);
2256 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2258 CBlockHeaderAndShortTxIDs cmpctblock;
2259 vRecv >> cmpctblock;
2261 bool received_new_header = false;
2264 LOCK(cs_main);
2266 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
2267 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2268 if (!IsInitialBlockDownload())
2269 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2270 return true;
2273 if (mapBlockIndex.find(cmpctblock.header.GetHash()) == mapBlockIndex.end()) {
2274 received_new_header = true;
2278 const CBlockIndex *pindex = nullptr;
2279 CValidationState state;
2280 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
2281 int nDoS;
2282 if (state.IsInvalid(nDoS)) {
2283 if (nDoS > 0) {
2284 LOCK(cs_main);
2285 Misbehaving(pfrom->GetId(), nDoS);
2287 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2288 return true;
2292 // When we succeed in decoding a block's txids from a cmpctblock
2293 // message we typically jump to the BLOCKTXN handling code, with a
2294 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2295 // completing processing of the putative block (without cs_main).
2296 bool fProcessBLOCKTXN = false;
2297 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2299 // If we end up treating this as a plain headers message, call that as well
2300 // without cs_main.
2301 bool fRevertToHeaderProcessing = false;
2303 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2304 // below)
2305 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2306 bool fBlockReconstructed = false;
2309 LOCK(cs_main);
2310 // If AcceptBlockHeader returned true, it set pindex
2311 assert(pindex);
2312 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2314 CNodeState *nodestate = State(pfrom->GetId());
2316 // If this was a new header with more work than our tip, update the
2317 // peer's last block announcement time
2318 if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) {
2319 nodestate->m_last_block_announcement = GetTime();
2322 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2323 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2325 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2326 return true;
2328 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2329 pindex->nTx != 0) { // We had this block at some point, but pruned it
2330 if (fAlreadyInFlight) {
2331 // We requested this block for some reason, but our mempool will probably be useless
2332 // so we just grab the block via normal getdata
2333 std::vector<CInv> vInv(1);
2334 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2335 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2337 return true;
2340 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2341 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2342 return true;
2344 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2345 // Don't bother trying to process compact blocks from v1 peers
2346 // after segwit activates.
2347 return true;
2350 // We want to be a bit conservative just to be extra careful about DoS
2351 // possibilities in compact block processing...
2352 if (pindex->nHeight <= chainActive.Height() + 2) {
2353 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2354 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2355 std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
2356 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2357 if (!(*queuedBlockIt)->partialBlock)
2358 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2359 else {
2360 // The block was already in flight using compact blocks from the same peer
2361 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2362 return true;
2366 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2367 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2368 if (status == READ_STATUS_INVALID) {
2369 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2370 Misbehaving(pfrom->GetId(), 100);
2371 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2372 return true;
2373 } else if (status == READ_STATUS_FAILED) {
2374 // Duplicate txindexes, the block is now in-flight, so just request it
2375 std::vector<CInv> vInv(1);
2376 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2377 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2378 return true;
2381 BlockTransactionsRequest req;
2382 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2383 if (!partialBlock.IsTxAvailable(i))
2384 req.indexes.push_back(i);
2386 if (req.indexes.empty()) {
2387 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2388 BlockTransactions txn;
2389 txn.blockhash = cmpctblock.header.GetHash();
2390 blockTxnMsg << txn;
2391 fProcessBLOCKTXN = true;
2392 } else {
2393 req.blockhash = pindex->GetBlockHash();
2394 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2396 } else {
2397 // This block is either already in flight from a different
2398 // peer, or this peer has too many blocks outstanding to
2399 // download from.
2400 // Optimistically try to reconstruct anyway since we might be
2401 // able to without any round trips.
2402 PartiallyDownloadedBlock tempBlock(&mempool);
2403 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2404 if (status != READ_STATUS_OK) {
2405 // TODO: don't ignore failures
2406 return true;
2408 std::vector<CTransactionRef> dummy;
2409 status = tempBlock.FillBlock(*pblock, dummy);
2410 if (status == READ_STATUS_OK) {
2411 fBlockReconstructed = true;
2414 } else {
2415 if (fAlreadyInFlight) {
2416 // We requested this block, but its far into the future, so our
2417 // mempool will probably be useless - request the block normally
2418 std::vector<CInv> vInv(1);
2419 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2420 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2421 return true;
2422 } else {
2423 // If this was an announce-cmpctblock, we want the same treatment as a header message
2424 fRevertToHeaderProcessing = true;
2427 } // cs_main
2429 if (fProcessBLOCKTXN)
2430 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2432 if (fRevertToHeaderProcessing) {
2433 // Headers received from HB compact block peers are permitted to be
2434 // relayed before full validation (see BIP 152), so we don't want to disconnect
2435 // the peer if the header turns out to be for an invalid block.
2436 // Note that if a peer tries to build on an invalid chain, that
2437 // will be detected and the peer will be banned.
2438 return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
2441 if (fBlockReconstructed) {
2442 // If we got here, we were able to optimistically reconstruct a
2443 // block that is in flight from some other peer.
2445 LOCK(cs_main);
2446 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2448 bool fNewBlock = false;
2449 // Setting fForceProcessing to true means that we bypass some of
2450 // our anti-DoS protections in AcceptBlock, which filters
2451 // unrequested blocks that might be trying to waste our resources
2452 // (eg disk space). Because we only try to reconstruct blocks when
2453 // we're close to caught up (via the CanDirectFetch() requirement
2454 // above, combined with the behavior of not requesting blocks until
2455 // we have a chain with at least nMinimumChainWork), and we ignore
2456 // compact blocks with less work than our tip, it is safe to treat
2457 // reconstructed compact blocks as having been requested.
2458 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2459 if (fNewBlock) {
2460 pfrom->nLastBlockTime = GetTime();
2461 } else {
2462 LOCK(cs_main);
2463 mapBlockSource.erase(pblock->GetHash());
2465 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2466 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2467 // Clear download state for this block, which is in
2468 // process from some other peer. We do this after calling
2469 // ProcessNewBlock so that a malleated cmpctblock announcement
2470 // can't be used to interfere with block relay.
2471 MarkBlockAsReceived(pblock->GetHash());
2477 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2479 BlockTransactions resp;
2480 vRecv >> resp;
2482 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2483 bool fBlockRead = false;
2485 LOCK(cs_main);
2487 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2488 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2489 it->second.first != pfrom->GetId()) {
2490 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2491 return true;
2494 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2495 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2496 if (status == READ_STATUS_INVALID) {
2497 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2498 Misbehaving(pfrom->GetId(), 100);
2499 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2500 return true;
2501 } else if (status == READ_STATUS_FAILED) {
2502 // Might have collided, fall back to getdata now :(
2503 std::vector<CInv> invs;
2504 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2505 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2506 } else {
2507 // Block is either okay, or possibly we received
2508 // READ_STATUS_CHECKBLOCK_FAILED.
2509 // Note that CheckBlock can only fail for one of a few reasons:
2510 // 1. bad-proof-of-work (impossible here, because we've already
2511 // accepted the header)
2512 // 2. merkleroot doesn't match the transactions given (already
2513 // caught in FillBlock with READ_STATUS_FAILED, so
2514 // impossible here)
2515 // 3. the block is otherwise invalid (eg invalid coinbase,
2516 // block is too big, too many legacy sigops, etc).
2517 // So if CheckBlock failed, #3 is the only possibility.
2518 // Under BIP 152, we don't DoS-ban unless proof of work is
2519 // invalid (we don't require all the stateless checks to have
2520 // been run). This is handled below, so just treat this as
2521 // though the block was successfully read, and rely on the
2522 // handling in ProcessNewBlock to ensure the block index is
2523 // updated, reject messages go out, etc.
2524 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2525 fBlockRead = true;
2526 // mapBlockSource is only used for sending reject messages and DoS scores,
2527 // so the race between here and cs_main in ProcessNewBlock is fine.
2528 // BIP 152 permits peers to relay compact blocks after validating
2529 // the header only; we should not punish peers if the block turns
2530 // out to be invalid.
2531 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2533 } // Don't hold cs_main when we call into ProcessNewBlock
2534 if (fBlockRead) {
2535 bool fNewBlock = false;
2536 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2537 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2538 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2539 // disk-space attacks), but this should be safe due to the
2540 // protections in the compact block handler -- see related comment
2541 // in compact block optimistic reconstruction handling.
2542 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2543 if (fNewBlock) {
2544 pfrom->nLastBlockTime = GetTime();
2545 } else {
2546 LOCK(cs_main);
2547 mapBlockSource.erase(pblock->GetHash());
2553 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2555 std::vector<CBlockHeader> headers;
2557 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2558 unsigned int nCount = ReadCompactSize(vRecv);
2559 if (nCount > MAX_HEADERS_RESULTS) {
2560 LOCK(cs_main);
2561 Misbehaving(pfrom->GetId(), 20);
2562 return error("headers message size = %u", nCount);
2564 headers.resize(nCount);
2565 for (unsigned int n = 0; n < nCount; n++) {
2566 vRecv >> headers[n];
2567 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2570 // Headers received via a HEADERS message should be valid, and reflect
2571 // the chain the peer is on. If we receive a known-invalid header,
2572 // disconnect the peer if it is using one of our outbound connection
2573 // slots.
2574 bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
2575 return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
2578 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2580 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2581 vRecv >> *pblock;
2583 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2585 // Process all blocks from whitelisted peers, even if not requested,
2586 // unless we're still syncing with the network.
2587 // Such an unrequested block may still be processed, subject to the
2588 // conditions in AcceptBlock().
2589 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
2590 const uint256 hash(pblock->GetHash());
2592 LOCK(cs_main);
2593 // Also always process if we requested the block explicitly, as we may
2594 // need it even though it is not a candidate for a new best tip.
2595 forceProcessing |= MarkBlockAsReceived(hash);
2596 // mapBlockSource is only used for sending reject messages and DoS scores,
2597 // so the race between here and cs_main in ProcessNewBlock is fine.
2598 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2600 bool fNewBlock = false;
2601 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2602 if (fNewBlock) {
2603 pfrom->nLastBlockTime = GetTime();
2604 } else {
2605 LOCK(cs_main);
2606 mapBlockSource.erase(pblock->GetHash());
2611 else if (strCommand == NetMsgType::GETADDR)
2613 // This asymmetric behavior for inbound and outbound connections was introduced
2614 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2615 // to users' AddrMan and later request them by sending getaddr messages.
2616 // Making nodes which are behind NAT and can only make outgoing connections ignore
2617 // the getaddr message mitigates the attack.
2618 if (!pfrom->fInbound) {
2619 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2620 return true;
2623 // Only send one GetAddr response per connection to reduce resource waste
2624 // and discourage addr stamping of INV announcements.
2625 if (pfrom->fSentAddr) {
2626 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2627 return true;
2629 pfrom->fSentAddr = true;
2631 pfrom->vAddrToSend.clear();
2632 std::vector<CAddress> vAddr = connman->GetAddresses();
2633 FastRandomContext insecure_rand;
2634 for (const CAddress &addr : vAddr)
2635 pfrom->PushAddress(addr, insecure_rand);
2639 else if (strCommand == NetMsgType::MEMPOOL)
2641 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2643 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2644 pfrom->fDisconnect = true;
2645 return true;
2648 if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
2650 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2651 pfrom->fDisconnect = true;
2652 return true;
2655 LOCK(pfrom->cs_inventory);
2656 pfrom->fSendMempool = true;
2660 else if (strCommand == NetMsgType::PING)
2662 if (pfrom->nVersion > BIP0031_VERSION)
2664 uint64_t nonce = 0;
2665 vRecv >> nonce;
2666 // Echo the message back with the nonce. This allows for two useful features:
2668 // 1) A remote node can quickly check if the connection is operational
2669 // 2) Remote nodes can measure the latency of the network thread. If this node
2670 // is overloaded it won't respond to pings quickly and the remote node can
2671 // avoid sending us more work, like chain download requests.
2673 // The nonce stops the remote getting confused between different pings: without
2674 // it, if the remote node sends a ping once per second and this node takes 5
2675 // seconds to respond to each, the 5th ping the remote sends would appear to
2676 // return very quickly.
2677 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2682 else if (strCommand == NetMsgType::PONG)
2684 int64_t pingUsecEnd = nTimeReceived;
2685 uint64_t nonce = 0;
2686 size_t nAvail = vRecv.in_avail();
2687 bool bPingFinished = false;
2688 std::string sProblem;
2690 if (nAvail >= sizeof(nonce)) {
2691 vRecv >> nonce;
2693 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2694 if (pfrom->nPingNonceSent != 0) {
2695 if (nonce == pfrom->nPingNonceSent) {
2696 // Matching pong received, this ping is no longer outstanding
2697 bPingFinished = true;
2698 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2699 if (pingUsecTime > 0) {
2700 // Successful ping time measurement, replace previous
2701 pfrom->nPingUsecTime = pingUsecTime;
2702 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2703 } else {
2704 // This should never happen
2705 sProblem = "Timing mishap";
2707 } else {
2708 // Nonce mismatches are normal when pings are overlapping
2709 sProblem = "Nonce mismatch";
2710 if (nonce == 0) {
2711 // This is most likely a bug in another implementation somewhere; cancel this ping
2712 bPingFinished = true;
2713 sProblem = "Nonce zero";
2716 } else {
2717 sProblem = "Unsolicited pong without ping";
2719 } else {
2720 // This is most likely a bug in another implementation somewhere; cancel this ping
2721 bPingFinished = true;
2722 sProblem = "Short payload";
2725 if (!(sProblem.empty())) {
2726 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2727 pfrom->GetId(),
2728 sProblem,
2729 pfrom->nPingNonceSent,
2730 nonce,
2731 nAvail);
2733 if (bPingFinished) {
2734 pfrom->nPingNonceSent = 0;
2739 else if (strCommand == NetMsgType::FILTERLOAD)
2741 CBloomFilter filter;
2742 vRecv >> filter;
2744 if (!filter.IsWithinSizeConstraints())
2746 // There is no excuse for sending a too-large filter
2747 LOCK(cs_main);
2748 Misbehaving(pfrom->GetId(), 100);
2750 else
2752 LOCK(pfrom->cs_filter);
2753 delete pfrom->pfilter;
2754 pfrom->pfilter = new CBloomFilter(filter);
2755 pfrom->pfilter->UpdateEmptyFull();
2756 pfrom->fRelayTxes = true;
2761 else if (strCommand == NetMsgType::FILTERADD)
2763 std::vector<unsigned char> vData;
2764 vRecv >> vData;
2766 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2767 // and thus, the maximum size any matched object can have) in a filteradd message
2768 bool bad = false;
2769 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2770 bad = true;
2771 } else {
2772 LOCK(pfrom->cs_filter);
2773 if (pfrom->pfilter) {
2774 pfrom->pfilter->insert(vData);
2775 } else {
2776 bad = true;
2779 if (bad) {
2780 LOCK(cs_main);
2781 Misbehaving(pfrom->GetId(), 100);
2786 else if (strCommand == NetMsgType::FILTERCLEAR)
2788 LOCK(pfrom->cs_filter);
2789 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2790 delete pfrom->pfilter;
2791 pfrom->pfilter = new CBloomFilter();
2793 pfrom->fRelayTxes = true;
2796 else if (strCommand == NetMsgType::FEEFILTER) {
2797 CAmount newFeeFilter = 0;
2798 vRecv >> newFeeFilter;
2799 if (MoneyRange(newFeeFilter)) {
2801 LOCK(pfrom->cs_feeFilter);
2802 pfrom->minFeeFilter = newFeeFilter;
2804 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2808 else if (strCommand == NetMsgType::NOTFOUND) {
2809 // We do not care about the NOTFOUND message, but logging an Unknown Command
2810 // message would be undesirable as we transmit it ourselves.
2813 else {
2814 // Ignore unknown commands for extensibility
2815 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2820 return true;
2823 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
2825 AssertLockHeld(cs_main);
2826 CNodeState &state = *State(pnode->GetId());
2828 for (const CBlockReject& reject : state.rejects) {
2829 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2831 state.rejects.clear();
2833 if (state.fShouldBan) {
2834 state.fShouldBan = false;
2835 if (pnode->fWhitelisted)
2836 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2837 else if (pnode->m_manual_connection)
2838 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
2839 else {
2840 pnode->fDisconnect = true;
2841 if (pnode->addr.IsLocal())
2842 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2843 else
2845 connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2848 return true;
2850 return false;
2853 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2855 const CChainParams& chainparams = Params();
2857 // Message format
2858 // (4) message start
2859 // (12) command
2860 // (4) size
2861 // (4) checksum
2862 // (x) data
2864 bool fMoreWork = false;
2866 if (!pfrom->vRecvGetData.empty())
2867 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2869 if (pfrom->fDisconnect)
2870 return false;
2872 // this maintains the order of responses
2873 if (!pfrom->vRecvGetData.empty()) return true;
2875 // Don't bother if send buffer is too full to respond anyway
2876 if (pfrom->fPauseSend)
2877 return false;
2879 std::list<CNetMessage> msgs;
2881 LOCK(pfrom->cs_vProcessMsg);
2882 if (pfrom->vProcessMsg.empty())
2883 return false;
2884 // Just take one message
2885 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2886 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2887 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize();
2888 fMoreWork = !pfrom->vProcessMsg.empty();
2890 CNetMessage& msg(msgs.front());
2892 msg.SetVersion(pfrom->GetRecvVersion());
2893 // Scan for message start
2894 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2895 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2896 pfrom->fDisconnect = true;
2897 return false;
2900 // Read header
2901 CMessageHeader& hdr = msg.hdr;
2902 if (!hdr.IsValid(chainparams.MessageStart()))
2904 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2905 return fMoreWork;
2907 std::string strCommand = hdr.GetCommand();
2909 // Message size
2910 unsigned int nMessageSize = hdr.nMessageSize;
2912 // Checksum
2913 CDataStream& vRecv = msg.vRecv;
2914 const uint256& hash = msg.GetMessageHash();
2915 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2917 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2918 SanitizeString(strCommand), nMessageSize,
2919 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2920 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2921 return fMoreWork;
2924 // Process message
2925 bool fRet = false;
2928 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2929 if (interruptMsgProc)
2930 return false;
2931 if (!pfrom->vRecvGetData.empty())
2932 fMoreWork = true;
2934 catch (const std::ios_base::failure& e)
2936 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2937 if (strstr(e.what(), "end of data"))
2939 // Allow exceptions from under-length message on vRecv
2940 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());
2942 else if (strstr(e.what(), "size too large"))
2944 // Allow exceptions from over-long size
2945 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2947 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2949 // Allow exceptions from non-canonical encoding
2950 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2952 else
2954 PrintExceptionContinue(&e, "ProcessMessages()");
2957 catch (const std::exception& e) {
2958 PrintExceptionContinue(&e, "ProcessMessages()");
2959 } catch (...) {
2960 PrintExceptionContinue(nullptr, "ProcessMessages()");
2963 if (!fRet) {
2964 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
2967 LOCK(cs_main);
2968 SendRejectsAndCheckIfBanned(pfrom, connman);
2970 return fMoreWork;
2973 void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
2975 AssertLockHeld(cs_main);
2977 CNodeState &state = *State(pto->GetId());
2978 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2980 if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
2981 // This is an outbound peer subject to disconnection if they don't
2982 // announce a block with as much work as the current tip within
2983 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
2984 // their chain has more work than ours, we should sync to it,
2985 // unless it's invalid, in which case we should find that out and
2986 // disconnect from them elsewhere).
2987 if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
2988 if (state.m_chain_sync.m_timeout != 0) {
2989 state.m_chain_sync.m_timeout = 0;
2990 state.m_chain_sync.m_work_header = nullptr;
2991 state.m_chain_sync.m_sent_getheaders = false;
2993 } 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)) {
2994 // Our best block known by this peer is behind our tip, and we're either noticing
2995 // that for the first time, OR this peer was able to catch up to some earlier point
2996 // where we checked against our tip.
2997 // Either way, set a new timeout based on current tip.
2998 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
2999 state.m_chain_sync.m_work_header = chainActive.Tip();
3000 state.m_chain_sync.m_sent_getheaders = false;
3001 } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
3002 // No evidence yet that our peer has synced to a chain with work equal to that
3003 // of our tip, when we first detected it was behind. Send a single getheaders
3004 // message to give the peer a chance to update us.
3005 if (state.m_chain_sync.m_sent_getheaders) {
3006 // They've run out of time to catch up!
3007 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
3008 pto->fDisconnect = true;
3009 } else {
3010 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());
3011 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
3012 state.m_chain_sync.m_sent_getheaders = true;
3013 constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
3014 // Bump the timeout to allow a response, which could clear the timeout
3015 // (if the response shows the peer has synced), reset the timeout (if
3016 // the peer syncs to the required work but not to our tip), or result
3017 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3018 // has not sufficiently progressed)
3019 state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
3025 void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
3027 // Check whether we have too many outbound peers
3028 int extra_peers = connman->GetExtraOutboundCount();
3029 if (extra_peers > 0) {
3030 // If we have more outbound peers than we target, disconnect one.
3031 // Pick the outbound peer that least recently announced
3032 // us a new block, with ties broken by choosing the more recent
3033 // connection (higher node id)
3034 NodeId worst_peer = -1;
3035 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
3037 LOCK(cs_main);
3039 connman->ForEachNode([&](CNode* pnode) {
3040 // Ignore non-outbound peers, or nodes marked for disconnect already
3041 if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
3042 CNodeState *state = State(pnode->GetId());
3043 if (state == nullptr) return; // shouldn't be possible, but just in case
3044 // Don't evict our protected peers
3045 if (state->m_chain_sync.m_protect) return;
3046 if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
3047 worst_peer = pnode->GetId();
3048 oldest_block_announcement = state->m_last_block_announcement;
3051 if (worst_peer != -1) {
3052 bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
3053 // Only disconnect a peer that has been connected to us for
3054 // some reasonable fraction of our check-frequency, to give
3055 // it time for new information to have arrived.
3056 // Also don't disconnect any peer we're trying to download a
3057 // block from.
3058 CNodeState &state = *State(pnode->GetId());
3059 if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
3060 LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
3061 pnode->fDisconnect = true;
3062 return true;
3063 } else {
3064 LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
3065 return false;
3068 if (disconnected) {
3069 // If we disconnected an extra peer, that means we successfully
3070 // connected to at least one peer after the last time we
3071 // detected a stale tip. Don't try any more extra peers until
3072 // we next detect a stale tip, to limit the load we put on the
3073 // network from these extra connections.
3074 connman->SetTryNewOutboundPeer(false);
3080 void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
3082 if (connman == nullptr) return;
3084 int64_t time_in_seconds = GetTime();
3086 EvictExtraOutboundPeers(time_in_seconds);
3088 if (time_in_seconds > m_stale_tip_check_time) {
3089 LOCK(cs_main);
3090 // Check whether our tip is stale, and if so, allow using an extra
3091 // outbound peer
3092 if (TipMayBeStale(consensusParams)) {
3093 LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update);
3094 connman->SetTryNewOutboundPeer(true);
3095 } else if (connman->GetTryNewOutboundPeer()) {
3096 connman->SetTryNewOutboundPeer(false);
3098 m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
3102 class CompareInvMempoolOrder
3104 CTxMemPool *mp;
3105 public:
3106 explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
3108 mp = _mempool;
3111 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
3113 /* As std::make_heap produces a max-heap, we want the entries with the
3114 * fewest ancestors/highest fee to sort later. */
3115 return mp->CompareDepthAndScore(*b, *a);
3119 bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
3121 const Consensus::Params& consensusParams = Params().GetConsensus();
3123 // Don't send anything until the version handshake is complete
3124 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
3125 return true;
3127 // If we get here, the outgoing message serialization version is set and can't change.
3128 const CNetMsgMaker msgMaker(pto->GetSendVersion());
3131 // Message: ping
3133 bool pingSend = false;
3134 if (pto->fPingQueued) {
3135 // RPC ping request by user
3136 pingSend = true;
3138 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
3139 // Ping automatically sent as a latency probe & keepalive.
3140 pingSend = true;
3142 if (pingSend) {
3143 uint64_t nonce = 0;
3144 while (nonce == 0) {
3145 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
3147 pto->fPingQueued = false;
3148 pto->nPingUsecStart = GetTimeMicros();
3149 if (pto->nVersion > BIP0031_VERSION) {
3150 pto->nPingNonceSent = nonce;
3151 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
3152 } else {
3153 // Peer is too old to support ping command with nonce, pong will never arrive.
3154 pto->nPingNonceSent = 0;
3155 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
3159 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3160 if (!lockMain)
3161 return true;
3163 if (SendRejectsAndCheckIfBanned(pto, connman))
3164 return true;
3165 CNodeState &state = *State(pto->GetId());
3167 // Address refresh broadcast
3168 int64_t nNow = GetTimeMicros();
3169 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3170 AdvertiseLocal(pto);
3171 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
3175 // Message: addr
3177 if (pto->nNextAddrSend < nNow) {
3178 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
3179 std::vector<CAddress> vAddr;
3180 vAddr.reserve(pto->vAddrToSend.size());
3181 for (const CAddress& addr : pto->vAddrToSend)
3183 if (!pto->addrKnown.contains(addr.GetKey()))
3185 pto->addrKnown.insert(addr.GetKey());
3186 vAddr.push_back(addr);
3187 // receiver rejects addr messages larger than 1000
3188 if (vAddr.size() >= 1000)
3190 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3191 vAddr.clear();
3195 pto->vAddrToSend.clear();
3196 if (!vAddr.empty())
3197 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3198 // we only send the big addr message once
3199 if (pto->vAddrToSend.capacity() > 40)
3200 pto->vAddrToSend.shrink_to_fit();
3203 // Start block sync
3204 if (pindexBestHeader == nullptr)
3205 pindexBestHeader = chainActive.Tip();
3206 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.
3207 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
3208 // Only actively request headers from a single peer, unless we're close to today.
3209 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3210 state.fSyncStarted = true;
3211 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
3212 nSyncStarted++;
3213 const CBlockIndex *pindexStart = pindexBestHeader;
3214 /* If possible, start at the block preceding the currently
3215 best known header. This ensures that we always get a
3216 non-empty list of headers back as long as the peer
3217 is up-to-date. With a non-empty response, we can initialise
3218 the peer's known best block. This wouldn't be possible
3219 if we requested starting at pindexBestHeader and
3220 got back an empty response. */
3221 if (pindexStart->pprev)
3222 pindexStart = pindexStart->pprev;
3223 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
3224 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
3228 // Resend wallet transactions that haven't gotten in a block yet
3229 // Except during reindex, importing and IBD, when old wallet
3230 // transactions become unconfirmed and spams other nodes.
3231 if (!fReindex && !fImporting && !IsInitialBlockDownload())
3233 GetMainSignals().Broadcast(nTimeBestReceived, connman);
3237 // Try sending block announcements via headers
3240 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3241 // list of block hashes we're relaying, and our peer wants
3242 // headers announcements, then find the first header
3243 // not yet known to our peer but would connect, and send.
3244 // If no header would connect, or if we have too many
3245 // blocks, or if the peer doesn't want headers, just
3246 // add all to the inv queue.
3247 LOCK(pto->cs_inventory);
3248 std::vector<CBlock> vHeaders;
3249 bool fRevertToInv = ((!state.fPreferHeaders &&
3250 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
3251 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
3252 const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
3253 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
3255 if (!fRevertToInv) {
3256 bool fFoundStartingHeader = false;
3257 // Try to find first header that our peer doesn't have, and
3258 // then send all headers past that one. If we come across any
3259 // headers that aren't on chainActive, give up.
3260 for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3261 BlockMap::iterator mi = mapBlockIndex.find(hash);
3262 assert(mi != mapBlockIndex.end());
3263 const CBlockIndex *pindex = mi->second;
3264 if (chainActive[pindex->nHeight] != pindex) {
3265 // Bail out if we reorged away from this block
3266 fRevertToInv = true;
3267 break;
3269 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
3270 // This means that the list of blocks to announce don't
3271 // connect to each other.
3272 // This shouldn't really be possible to hit during
3273 // regular operation (because reorgs should take us to
3274 // a chain that has some block not on the prior chain,
3275 // which should be caught by the prior check), but one
3276 // way this could happen is by using invalidateblock /
3277 // reconsiderblock repeatedly on the tip, causing it to
3278 // be added multiple times to vBlockHashesToAnnounce.
3279 // Robustly deal with this rare situation by reverting
3280 // to an inv.
3281 fRevertToInv = true;
3282 break;
3284 pBestIndex = pindex;
3285 if (fFoundStartingHeader) {
3286 // add this to the headers message
3287 vHeaders.push_back(pindex->GetBlockHeader());
3288 } else if (PeerHasHeader(&state, pindex)) {
3289 continue; // keep looking for the first new block
3290 } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
3291 // Peer doesn't have this header but they do have the prior one.
3292 // Start sending headers.
3293 fFoundStartingHeader = true;
3294 vHeaders.push_back(pindex->GetBlockHeader());
3295 } else {
3296 // Peer doesn't have this header or the prior one -- nothing will
3297 // connect, so bail out.
3298 fRevertToInv = true;
3299 break;
3303 if (!fRevertToInv && !vHeaders.empty()) {
3304 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
3305 // We only send up to 1 block as header-and-ids, as otherwise
3306 // probably means we're doing an initial-ish-sync or they're slow
3307 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
3308 vHeaders.front().GetHash().ToString(), pto->GetId());
3310 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
3312 bool fGotBlockFromCache = false;
3314 LOCK(cs_most_recent_block);
3315 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
3316 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
3317 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
3318 else {
3319 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
3320 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3322 fGotBlockFromCache = true;
3325 if (!fGotBlockFromCache) {
3326 CBlock block;
3327 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3328 assert(ret);
3329 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3330 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3332 state.pindexBestHeaderSent = pBestIndex;
3333 } else if (state.fPreferHeaders) {
3334 if (vHeaders.size() > 1) {
3335 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3336 vHeaders.size(),
3337 vHeaders.front().GetHash().ToString(),
3338 vHeaders.back().GetHash().ToString(), pto->GetId());
3339 } else {
3340 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3341 vHeaders.front().GetHash().ToString(), pto->GetId());
3343 connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3344 state.pindexBestHeaderSent = pBestIndex;
3345 } else
3346 fRevertToInv = true;
3348 if (fRevertToInv) {
3349 // If falling back to using an inv, just try to inv the tip.
3350 // The last entry in vBlockHashesToAnnounce was our tip at some point
3351 // in the past.
3352 if (!pto->vBlockHashesToAnnounce.empty()) {
3353 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3354 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3355 assert(mi != mapBlockIndex.end());
3356 const CBlockIndex *pindex = mi->second;
3358 // Warn if we're announcing a block that is not on the main chain.
3359 // This should be very rare and could be optimized out.
3360 // Just log for now.
3361 if (chainActive[pindex->nHeight] != pindex) {
3362 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3363 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3366 // If the peer's chain has this block, don't inv it back.
3367 if (!PeerHasHeader(&state, pindex)) {
3368 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3369 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3370 pto->GetId(), hashToAnnounce.ToString());
3374 pto->vBlockHashesToAnnounce.clear();
3378 // Message: inventory
3380 std::vector<CInv> vInv;
3382 LOCK(pto->cs_inventory);
3383 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3385 // Add blocks
3386 for (const uint256& hash : pto->vInventoryBlockToSend) {
3387 vInv.push_back(CInv(MSG_BLOCK, hash));
3388 if (vInv.size() == MAX_INV_SZ) {
3389 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3390 vInv.clear();
3393 pto->vInventoryBlockToSend.clear();
3395 // Check whether periodic sends should happen
3396 bool fSendTrickle = pto->fWhitelisted;
3397 if (pto->nNextInvSend < nNow) {
3398 fSendTrickle = true;
3399 // Use half the delay for outbound peers, as there is less privacy concern for them.
3400 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3403 // Time to send but the peer has requested we not relay transactions.
3404 if (fSendTrickle) {
3405 LOCK(pto->cs_filter);
3406 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3409 // Respond to BIP35 mempool requests
3410 if (fSendTrickle && pto->fSendMempool) {
3411 auto vtxinfo = mempool.infoAll();
3412 pto->fSendMempool = false;
3413 CAmount filterrate = 0;
3415 LOCK(pto->cs_feeFilter);
3416 filterrate = pto->minFeeFilter;
3419 LOCK(pto->cs_filter);
3421 for (const auto& txinfo : vtxinfo) {
3422 const uint256& hash = txinfo.tx->GetHash();
3423 CInv inv(MSG_TX, hash);
3424 pto->setInventoryTxToSend.erase(hash);
3425 if (filterrate) {
3426 if (txinfo.feeRate.GetFeePerK() < filterrate)
3427 continue;
3429 if (pto->pfilter) {
3430 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3432 pto->filterInventoryKnown.insert(hash);
3433 vInv.push_back(inv);
3434 if (vInv.size() == MAX_INV_SZ) {
3435 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3436 vInv.clear();
3439 pto->timeLastMempoolReq = GetTime();
3442 // Determine transactions to relay
3443 if (fSendTrickle) {
3444 // Produce a vector with all candidates for sending
3445 std::vector<std::set<uint256>::iterator> vInvTx;
3446 vInvTx.reserve(pto->setInventoryTxToSend.size());
3447 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3448 vInvTx.push_back(it);
3450 CAmount filterrate = 0;
3452 LOCK(pto->cs_feeFilter);
3453 filterrate = pto->minFeeFilter;
3455 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3456 // A heap is used so that not all items need sorting if only a few are being sent.
3457 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3458 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3459 // No reason to drain out at many times the network's capacity,
3460 // especially since we have many peers and some will draw much shorter delays.
3461 unsigned int nRelayedTransactions = 0;
3462 LOCK(pto->cs_filter);
3463 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3464 // Fetch the top element from the heap
3465 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3466 std::set<uint256>::iterator it = vInvTx.back();
3467 vInvTx.pop_back();
3468 uint256 hash = *it;
3469 // Remove it from the to-be-sent set
3470 pto->setInventoryTxToSend.erase(it);
3471 // Check if not in the filter already
3472 if (pto->filterInventoryKnown.contains(hash)) {
3473 continue;
3475 // Not in the mempool anymore? don't bother sending it.
3476 auto txinfo = mempool.info(hash);
3477 if (!txinfo.tx) {
3478 continue;
3480 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3481 continue;
3483 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3484 // Send
3485 vInv.push_back(CInv(MSG_TX, hash));
3486 nRelayedTransactions++;
3488 // Expire old relay messages
3489 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3491 mapRelay.erase(vRelayExpiration.front().second);
3492 vRelayExpiration.pop_front();
3495 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3496 if (ret.second) {
3497 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3500 if (vInv.size() == MAX_INV_SZ) {
3501 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3502 vInv.clear();
3504 pto->filterInventoryKnown.insert(hash);
3508 if (!vInv.empty())
3509 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3511 // Detect whether we're stalling
3512 nNow = GetTimeMicros();
3513 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3514 // Stalling only triggers when the block download window cannot move. During normal steady state,
3515 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3516 // should only happen during initial block download.
3517 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3518 pto->fDisconnect = true;
3519 return true;
3521 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3522 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3523 // We compensate for other peers to prevent killing off peers due to our own downstream link
3524 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3525 // to unreasonably increase our timeout.
3526 if (state.vBlocksInFlight.size() > 0) {
3527 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3528 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3529 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3530 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3531 pto->fDisconnect = true;
3532 return true;
3535 // Check for headers sync timeouts
3536 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3537 // Detect whether this is a stalling initial-headers-sync peer
3538 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3539 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3540 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3541 // and we have others we could be using instead.
3542 // Note: If all our peers are inbound, then we won't
3543 // disconnect our sync peer for stalling; we have bigger
3544 // problems if we can't get any outbound peers.
3545 if (!pto->fWhitelisted) {
3546 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3547 pto->fDisconnect = true;
3548 return true;
3549 } else {
3550 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3551 // Reset the headers sync state so that we have a
3552 // chance to try downloading from a different peer.
3553 // Note: this will also result in at least one more
3554 // getheaders message to be sent to
3555 // this peer (eventually).
3556 state.fSyncStarted = false;
3557 nSyncStarted--;
3558 state.nHeadersSyncTimeout = 0;
3561 } else {
3562 // After we've caught up once, reset the timeout so we can't trigger
3563 // disconnect later.
3564 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3568 // Check that outbound peers have reasonable chains
3569 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3570 ConsiderEviction(pto, GetTime());
3573 // Message: getdata (blocks)
3575 std::vector<CInv> vGetData;
3576 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3577 std::vector<const CBlockIndex*> vToDownload;
3578 NodeId staller = -1;
3579 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3580 for (const CBlockIndex *pindex : vToDownload) {
3581 uint32_t nFetchFlags = GetFetchFlags(pto);
3582 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3583 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3584 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3585 pindex->nHeight, pto->GetId());
3587 if (state.nBlocksInFlight == 0 && staller != -1) {
3588 if (State(staller)->nStallingSince == 0) {
3589 State(staller)->nStallingSince = nNow;
3590 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3596 // Message: getdata (non-blocks)
3598 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3600 const CInv& inv = (*pto->mapAskFor.begin()).second;
3601 if (!AlreadyHave(inv))
3603 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3604 vGetData.push_back(inv);
3605 if (vGetData.size() >= 1000)
3607 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3608 vGetData.clear();
3610 } else {
3611 //If we're not going to ask, don't expect a response.
3612 pto->setAskFor.erase(inv.hash);
3614 pto->mapAskFor.erase(pto->mapAskFor.begin());
3616 if (!vGetData.empty())
3617 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3620 // Message: feefilter
3622 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3623 if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3624 !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3625 CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3626 int64_t timeNow = GetTimeMicros();
3627 if (timeNow > pto->nextSendTimeFeeFilter) {
3628 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3629 static FeeFilterRounder filterRounder(default_feerate);
3630 CAmount filterToSend = filterRounder.round(currentFilter);
3631 // We always have a fee filter of at least minRelayTxFee
3632 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3633 if (filterToSend != pto->lastSentFeeFilter) {
3634 connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3635 pto->lastSentFeeFilter = filterToSend;
3637 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3639 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3640 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3641 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3642 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3643 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3647 return true;
3650 class CNetProcessingCleanup
3652 public:
3653 CNetProcessingCleanup() {}
3654 ~CNetProcessingCleanup() {
3655 // orphan transactions
3656 mapOrphanTransactions.clear();
3657 mapOrphanTransactionsByPrev.clear();
3659 } instance_of_cnetprocessingcleanup;