Use unique_ptr for pcoinscatcher/pcoinsdbview/pcoinsTip/pblocktree
[bitcoinplatinum.git] / src / net_processing.cpp
blobff6f796b3383691fd5ff30b77bc77c1225748ab8
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 // This function is used for testing the stale tip eviction logic, see
554 // DoS_tests.cpp
555 void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
557 LOCK(cs_main);
558 CNodeState *state = State(node);
559 if (state) state->m_last_block_announcement = time_in_seconds;
562 // Returns true for outbound peers, excluding manual connections, feelers, and
563 // one-shots
564 bool IsOutboundDisconnectionCandidate(const CNode *node)
566 return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
569 void PeerLogicValidation::InitializeNode(CNode *pnode) {
570 CAddress addr = pnode->addr;
571 std::string addrName = pnode->GetAddrName();
572 NodeId nodeid = pnode->GetId();
574 LOCK(cs_main);
575 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
577 if(!pnode->fInbound)
578 PushNodeVersion(pnode, connman, GetTime());
581 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
582 fUpdateConnectionTime = false;
583 LOCK(cs_main);
584 CNodeState *state = State(nodeid);
585 assert(state != nullptr);
587 if (state->fSyncStarted)
588 nSyncStarted--;
590 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
591 fUpdateConnectionTime = true;
594 for (const QueuedBlock& entry : state->vBlocksInFlight) {
595 mapBlocksInFlight.erase(entry.hash);
597 EraseOrphansFor(nodeid);
598 nPreferredDownload -= state->fPreferredDownload;
599 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
600 assert(nPeersWithValidatedDownloads >= 0);
601 g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
602 assert(g_outbound_peers_with_protect_from_disconnect >= 0);
604 mapNodeState.erase(nodeid);
606 if (mapNodeState.empty()) {
607 // Do a consistency check after the last peer is removed.
608 assert(mapBlocksInFlight.empty());
609 assert(nPreferredDownload == 0);
610 assert(nPeersWithValidatedDownloads == 0);
611 assert(g_outbound_peers_with_protect_from_disconnect == 0);
613 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
616 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
617 LOCK(cs_main);
618 CNodeState *state = State(nodeid);
619 if (state == nullptr)
620 return false;
621 stats.nMisbehavior = state->nMisbehavior;
622 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
623 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
624 for (const QueuedBlock& queue : state->vBlocksInFlight) {
625 if (queue.pindex)
626 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
628 return true;
631 //////////////////////////////////////////////////////////////////////////////
633 // mapOrphanTransactions
636 void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
638 size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
639 if (max_extra_txn <= 0)
640 return;
641 if (!vExtraTxnForCompact.size())
642 vExtraTxnForCompact.resize(max_extra_txn);
643 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
644 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
647 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
649 const uint256& hash = tx->GetHash();
650 if (mapOrphanTransactions.count(hash))
651 return false;
653 // Ignore big transactions, to avoid a
654 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
655 // large transaction with a missing parent then we assume
656 // it will rebroadcast it later, after the parent transaction(s)
657 // have been mined or received.
658 // 100 orphans, each of which is at most 99,999 bytes big is
659 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
660 unsigned int sz = GetTransactionWeight(*tx);
661 if (sz >= MAX_STANDARD_TX_WEIGHT)
663 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
664 return false;
667 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
668 assert(ret.second);
669 for (const CTxIn& txin : tx->vin) {
670 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
673 AddToCompactExtraTransactions(tx);
675 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
676 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
677 return true;
680 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
682 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
683 if (it == mapOrphanTransactions.end())
684 return 0;
685 for (const CTxIn& txin : it->second.tx->vin)
687 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
688 if (itPrev == mapOrphanTransactionsByPrev.end())
689 continue;
690 itPrev->second.erase(it);
691 if (itPrev->second.empty())
692 mapOrphanTransactionsByPrev.erase(itPrev);
694 mapOrphanTransactions.erase(it);
695 return 1;
698 void EraseOrphansFor(NodeId peer)
700 int nErased = 0;
701 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
702 while (iter != mapOrphanTransactions.end())
704 std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
705 if (maybeErase->second.fromPeer == peer)
707 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
710 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
714 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
716 unsigned int nEvicted = 0;
717 static int64_t nNextSweep;
718 int64_t nNow = GetTime();
719 if (nNextSweep <= nNow) {
720 // Sweep out expired orphan pool entries:
721 int nErased = 0;
722 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
723 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
724 while (iter != mapOrphanTransactions.end())
726 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
727 if (maybeErase->second.nTimeExpire <= nNow) {
728 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
729 } else {
730 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
733 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
734 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
735 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
737 while (mapOrphanTransactions.size() > nMaxOrphans)
739 // Evict a random orphan:
740 uint256 randomhash = GetRandHash();
741 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
742 if (it == mapOrphanTransactions.end())
743 it = mapOrphanTransactions.begin();
744 EraseOrphanTx(it->first);
745 ++nEvicted;
747 return nEvicted;
750 // Requires cs_main.
751 void Misbehaving(NodeId pnode, int howmuch)
753 if (howmuch == 0)
754 return;
756 CNodeState *state = State(pnode);
757 if (state == nullptr)
758 return;
760 state->nMisbehavior += howmuch;
761 int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
762 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
764 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
765 state->fShouldBan = true;
766 } else
767 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
777 //////////////////////////////////////////////////////////////////////////////
779 // blockchain -> download logic notification
782 // To prevent fingerprinting attacks, only send blocks/headers outside of the
783 // active chain if they are no more than a month older (both in time, and in
784 // best equivalent proof of work) than the best header chain we know about.
785 static bool StaleBlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
787 AssertLockHeld(cs_main);
788 return (pindexBestHeader != nullptr) &&
789 (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
790 (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
793 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler) : connman(connmanIn), m_stale_tip_check_time(0) {
794 // Initialize global variables that cannot be constructed at startup.
795 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
797 const Consensus::Params& consensusParams = Params().GetConsensus();
798 // Stale tip checking and peer eviction are on two different timers, but we
799 // don't want them to get out of sync due to drift in the scheduler, so we
800 // combine them in one function and schedule at the quicker (peer-eviction)
801 // timer.
802 static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
803 scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
806 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
807 LOCK(cs_main);
809 std::vector<uint256> vOrphanErase;
811 for (const CTransactionRef& ptx : pblock->vtx) {
812 const CTransaction& tx = *ptx;
814 // Which orphan pool entries must we evict?
815 for (const auto& txin : tx.vin) {
816 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
817 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
818 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
819 const CTransaction& orphanTx = *(*mi)->second.tx;
820 const uint256& orphanHash = orphanTx.GetHash();
821 vOrphanErase.push_back(orphanHash);
826 // Erase orphan transactions include or precluded by this block
827 if (vOrphanErase.size()) {
828 int nErased = 0;
829 for (uint256 &orphanHash : vOrphanErase) {
830 nErased += EraseOrphanTx(orphanHash);
832 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
835 g_last_tip_update = GetTime();
838 // All of the following cache a recent block, and are protected by cs_most_recent_block
839 static CCriticalSection cs_most_recent_block;
840 static std::shared_ptr<const CBlock> most_recent_block;
841 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
842 static uint256 most_recent_block_hash;
843 static bool fWitnessesPresentInMostRecentCompactBlock;
845 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
846 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
847 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
849 LOCK(cs_main);
851 static int nHighestFastAnnounce = 0;
852 if (pindex->nHeight <= nHighestFastAnnounce)
853 return;
854 nHighestFastAnnounce = pindex->nHeight;
856 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
857 uint256 hashBlock(pblock->GetHash());
860 LOCK(cs_most_recent_block);
861 most_recent_block_hash = hashBlock;
862 most_recent_block = pblock;
863 most_recent_compact_block = pcmpctblock;
864 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
867 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
868 // TODO: Avoid the repeated-serialization here
869 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
870 return;
871 ProcessBlockAvailability(pnode->GetId());
872 CNodeState &state = *State(pnode->GetId());
873 // If the peer has, or we announced to them the previous block already,
874 // but we don't think they have this one, go ahead and announce it
875 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
876 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
878 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
879 hashBlock.ToString(), pnode->GetId());
880 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
881 state.pindexBestHeaderSent = pindex;
886 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
887 const int nNewHeight = pindexNew->nHeight;
888 connman->SetBestHeight(nNewHeight);
890 if (!fInitialDownload) {
891 // Find the hashes of all blocks that weren't previously in the best chain.
892 std::vector<uint256> vHashes;
893 const CBlockIndex *pindexToAnnounce = pindexNew;
894 while (pindexToAnnounce != pindexFork) {
895 vHashes.push_back(pindexToAnnounce->GetBlockHash());
896 pindexToAnnounce = pindexToAnnounce->pprev;
897 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
898 // Limit announcements in case of a huge reorganization.
899 // Rely on the peer's synchronization mechanism in that case.
900 break;
903 // Relay inventory, but don't relay old inventory during initial block download.
904 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
905 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
906 for (const uint256& hash : reverse_iterate(vHashes)) {
907 pnode->PushBlockHash(hash);
911 connman->WakeMessageHandler();
914 nTimeBestReceived = GetTime();
917 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
918 LOCK(cs_main);
920 const uint256 hash(block.GetHash());
921 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
923 int nDoS = 0;
924 if (state.IsInvalid(nDoS)) {
925 // Don't send reject message with code 0 or an internal reject code.
926 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
927 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
928 State(it->second.first)->rejects.push_back(reject);
929 if (nDoS > 0 && it->second.second)
930 Misbehaving(it->second.first, nDoS);
933 // Check that:
934 // 1. The block is valid
935 // 2. We're not in initial block download
936 // 3. This is currently the best block we're aware of. We haven't updated
937 // the tip yet so we have no way to check this directly here. Instead we
938 // just check that there are currently no other blocks in flight.
939 else if (state.IsValid() &&
940 !IsInitialBlockDownload() &&
941 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
942 if (it != mapBlockSource.end()) {
943 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
946 if (it != mapBlockSource.end())
947 mapBlockSource.erase(it);
950 //////////////////////////////////////////////////////////////////////////////
952 // Messages
956 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
958 switch (inv.type)
960 case MSG_TX:
961 case MSG_WITNESS_TX:
963 assert(recentRejects);
964 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
966 // If the chain tip has changed previously rejected transactions
967 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
968 // or a double-spend. Reset the rejects filter and give those
969 // txs a second chance.
970 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
971 recentRejects->reset();
974 return recentRejects->contains(inv.hash) ||
975 mempool.exists(inv.hash) ||
976 mapOrphanTransactions.count(inv.hash) ||
977 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
978 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
980 case MSG_BLOCK:
981 case MSG_WITNESS_BLOCK:
982 return mapBlockIndex.count(inv.hash);
984 // Don't know what it is, just say we already got one
985 return true;
988 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
990 CInv inv(MSG_TX, tx.GetHash());
991 connman->ForEachNode([&inv](CNode* pnode)
993 pnode->PushInventory(inv);
997 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
999 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
1001 // Relay to a limited number of other nodes
1002 // Use deterministic randomness to send to the same nodes for 24 hours
1003 // at a time so the addrKnowns of the chosen nodes prevent repeats
1004 uint64_t hashAddr = addr.GetHash();
1005 const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
1006 FastRandomContext insecure_rand;
1008 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
1009 assert(nRelayNodes <= best.size());
1011 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
1012 if (pnode->nVersion >= CADDR_TIME_VERSION) {
1013 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
1014 for (unsigned int i = 0; i < nRelayNodes; i++) {
1015 if (hashKey > best[i].first) {
1016 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1017 best[i] = std::make_pair(hashKey, pnode);
1018 break;
1024 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
1025 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1026 best[i].second->PushAddress(addr, insecure_rand);
1030 connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
1033 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1035 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1036 std::vector<CInv> vNotFound;
1037 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1038 LOCK(cs_main);
1040 while (it != pfrom->vRecvGetData.end()) {
1041 // Don't bother if send buffer is too full to respond anyway
1042 if (pfrom->fPauseSend)
1043 break;
1045 const CInv &inv = *it;
1047 if (interruptMsgProc)
1048 return;
1050 it++;
1052 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1054 bool send = false;
1055 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1056 std::shared_ptr<const CBlock> a_recent_block;
1057 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1058 bool fWitnessesPresentInARecentCompactBlock;
1060 LOCK(cs_most_recent_block);
1061 a_recent_block = most_recent_block;
1062 a_recent_compact_block = most_recent_compact_block;
1063 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1065 if (mi != mapBlockIndex.end())
1067 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1068 mi->second->IsValid(BLOCK_VALID_TREE)) {
1069 // If we have the block and all of its parents, but have not yet validated it,
1070 // we might be in the middle of connecting it (ie in the unlock of cs_main
1071 // before ActivateBestChain but after AcceptBlock).
1072 // In this case, we need to run ActivateBestChain prior to checking the relay
1073 // conditions below.
1074 CValidationState dummy;
1075 ActivateBestChain(dummy, Params(), a_recent_block);
1077 if (chainActive.Contains(mi->second)) {
1078 send = true;
1079 } else {
1080 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1081 StaleBlockRequestAllowed(mi->second, consensusParams);
1082 if (!send) {
1083 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1087 // disconnect node in case we have reached the outbound limit for serving historical blocks
1088 // never disconnect whitelisted nodes
1089 if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1091 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1093 //disconnect node
1094 pfrom->fDisconnect = true;
1095 send = false;
1097 // Pruned nodes may have deleted the block, so check whether
1098 // it's available before trying to send.
1099 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1101 std::shared_ptr<const CBlock> pblock;
1102 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1103 pblock = a_recent_block;
1104 } else {
1105 // Send block from disk
1106 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1107 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1108 assert(!"cannot load block from disk");
1109 pblock = pblockRead;
1111 if (inv.type == MSG_BLOCK)
1112 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1113 else if (inv.type == MSG_WITNESS_BLOCK)
1114 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1115 else if (inv.type == MSG_FILTERED_BLOCK)
1117 bool sendMerkleBlock = false;
1118 CMerkleBlock merkleBlock;
1120 LOCK(pfrom->cs_filter);
1121 if (pfrom->pfilter) {
1122 sendMerkleBlock = true;
1123 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1126 if (sendMerkleBlock) {
1127 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1128 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1129 // This avoids hurting performance by pointlessly requiring a round-trip
1130 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1131 // they must either disconnect and retry or request the full block.
1132 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1133 // however we MUST always provide at least what the remote peer needs
1134 typedef std::pair<unsigned int, uint256> PairType;
1135 for (PairType& pair : merkleBlock.vMatchedTxn)
1136 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1138 // else
1139 // no response
1141 else if (inv.type == MSG_CMPCT_BLOCK)
1143 // If a peer is asking for old blocks, we're almost guaranteed
1144 // they won't have a useful mempool to match against a compact block,
1145 // and we don't feel like constructing the object for them, so
1146 // instead we respond with the full, non-compact block.
1147 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1148 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1149 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1150 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1151 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1152 } else {
1153 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1154 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1156 } else {
1157 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1161 // Trigger the peer node to send a getblocks request for the next batch of inventory
1162 if (inv.hash == pfrom->hashContinue)
1164 // Bypass PushInventory, this must send even if redundant,
1165 // and we want it right after the last block so they don't
1166 // wait for other stuff first.
1167 std::vector<CInv> vInv;
1168 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1169 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1170 pfrom->hashContinue.SetNull();
1174 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1176 // Send stream from relay memory
1177 bool push = false;
1178 auto mi = mapRelay.find(inv.hash);
1179 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1180 if (mi != mapRelay.end()) {
1181 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1182 push = true;
1183 } else if (pfrom->timeLastMempoolReq) {
1184 auto txinfo = mempool.info(inv.hash);
1185 // To protect privacy, do not answer getdata using the mempool when
1186 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1187 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1188 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1189 push = true;
1192 if (!push) {
1193 vNotFound.push_back(inv);
1197 // Track requests for our stuff.
1198 GetMainSignals().Inventory(inv.hash);
1200 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1201 break;
1205 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1207 if (!vNotFound.empty()) {
1208 // Let the peer know that we didn't find what it asked for, so it doesn't
1209 // have to wait around forever. Currently only SPV clients actually care
1210 // about this message: it's needed when they are recursively walking the
1211 // dependencies of relevant unconfirmed transactions. SPV clients want to
1212 // do that because they want to know about (and store and rebroadcast and
1213 // risk analyze) the dependencies of transactions relevant to them, without
1214 // having to download the entire memory pool.
1215 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1219 uint32_t GetFetchFlags(CNode* pfrom) {
1220 uint32_t nFetchFlags = 0;
1221 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1222 nFetchFlags |= MSG_WITNESS_FLAG;
1224 return nFetchFlags;
1227 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
1228 BlockTransactions resp(req);
1229 for (size_t i = 0; i < req.indexes.size(); i++) {
1230 if (req.indexes[i] >= block.vtx.size()) {
1231 LOCK(cs_main);
1232 Misbehaving(pfrom->GetId(), 100);
1233 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1234 return;
1236 resp.txn[i] = block.vtx[req.indexes[i]];
1238 LOCK(cs_main);
1239 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1240 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1241 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1244 bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
1246 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1247 size_t nCount = headers.size();
1249 if (nCount == 0) {
1250 // Nothing interesting. Stop asking this peers for more headers.
1251 return true;
1254 bool received_new_header = false;
1255 const CBlockIndex *pindexLast = nullptr;
1257 LOCK(cs_main);
1258 CNodeState *nodestate = State(pfrom->GetId());
1260 // If this looks like it could be a block announcement (nCount <
1261 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1262 // don't connect:
1263 // - Send a getheaders message in response to try to connect the chain.
1264 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1265 // don't connect before giving DoS points
1266 // - Once a headers message is received that is valid and does connect,
1267 // nUnconnectingHeaders gets reset back to 0.
1268 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1269 nodestate->nUnconnectingHeaders++;
1270 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1271 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1272 headers[0].GetHash().ToString(),
1273 headers[0].hashPrevBlock.ToString(),
1274 pindexBestHeader->nHeight,
1275 pfrom->GetId(), nodestate->nUnconnectingHeaders);
1276 // Set hashLastUnknownBlock for this peer, so that if we
1277 // eventually get the headers - even from a different peer -
1278 // we can use this peer to download.
1279 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
1281 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
1282 Misbehaving(pfrom->GetId(), 20);
1284 return true;
1287 uint256 hashLastBlock;
1288 for (const CBlockHeader& header : headers) {
1289 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
1290 Misbehaving(pfrom->GetId(), 20);
1291 return error("non-continuous headers sequence");
1293 hashLastBlock = header.GetHash();
1296 // If we don't have the last header, then they'll have given us
1297 // something new (if these headers are valid).
1298 if (mapBlockIndex.find(hashLastBlock) == mapBlockIndex.end()) {
1299 received_new_header = true;
1303 CValidationState state;
1304 CBlockHeader first_invalid_header;
1305 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) {
1306 int nDoS;
1307 if (state.IsInvalid(nDoS)) {
1308 LOCK(cs_main);
1309 if (nDoS > 0) {
1310 Misbehaving(pfrom->GetId(), nDoS);
1312 if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
1313 // Goal: don't allow outbound peers to use up our outbound
1314 // connection slots if they are on incompatible chains.
1316 // We ask the caller to set punish_invalid appropriately based
1317 // on the peer and the method of header delivery (compact
1318 // blocks are allowed to be invalid in some circumstances,
1319 // under BIP 152).
1320 // Here, we try to detect the narrow situation that we have a
1321 // valid block header (ie it was valid at the time the header
1322 // was received, and hence stored in mapBlockIndex) but know the
1323 // block is invalid, and that a peer has announced that same
1324 // block as being on its active chain.
1325 // Disconnect the peer in such a situation.
1327 // Note: if the header that is invalid was not accepted to our
1328 // mapBlockIndex at all, that may also be grounds for
1329 // disconnecting the peer, as the chain they are on is likely
1330 // to be incompatible. However, there is a circumstance where
1331 // that does not hold: if the header's timestamp is more than
1332 // 2 hours ahead of our current time. In that case, the header
1333 // may become valid in the future, and we don't want to
1334 // disconnect a peer merely for serving us one too-far-ahead
1335 // block header, to prevent an attacker from splitting the
1336 // network by mining a block right at the 2 hour boundary.
1338 // TODO: update the DoS logic (or, rather, rewrite the
1339 // DoS-interface between validation and net_processing) so that
1340 // the interface is cleaner, and so that we disconnect on all the
1341 // reasons that a peer's headers chain is incompatible
1342 // with ours (eg block->nVersion softforks, MTP violations,
1343 // etc), and not just the duplicate-invalid case.
1344 pfrom->fDisconnect = true;
1346 return error("invalid header received");
1351 LOCK(cs_main);
1352 CNodeState *nodestate = State(pfrom->GetId());
1353 if (nodestate->nUnconnectingHeaders > 0) {
1354 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
1356 nodestate->nUnconnectingHeaders = 0;
1358 assert(pindexLast);
1359 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1361 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1362 // because it is set in UpdateBlockAvailability. Some nullptr checks
1363 // are still present, however, as belt-and-suspenders.
1365 if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) {
1366 nodestate->m_last_block_announcement = GetTime();
1369 if (nCount == MAX_HEADERS_RESULTS) {
1370 // Headers message had its maximum size; the peer may have more headers.
1371 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1372 // from there instead.
1373 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1374 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
1377 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
1378 // If this set of headers is valid and ends in a block with at least as
1379 // much work as our tip, download as much as possible.
1380 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
1381 std::vector<const CBlockIndex*> vToFetch;
1382 const CBlockIndex *pindexWalk = pindexLast;
1383 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1384 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1385 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
1386 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
1387 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
1388 // We don't have this block, and it's not yet in flight.
1389 vToFetch.push_back(pindexWalk);
1391 pindexWalk = pindexWalk->pprev;
1393 // If pindexWalk still isn't on our main chain, we're looking at a
1394 // very large reorg at a time we think we're close to caught up to
1395 // the main chain -- this shouldn't really happen. Bail out on the
1396 // direct fetch and rely on parallel download instead.
1397 if (!chainActive.Contains(pindexWalk)) {
1398 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
1399 pindexLast->GetBlockHash().ToString(),
1400 pindexLast->nHeight);
1401 } else {
1402 std::vector<CInv> vGetData;
1403 // Download as much as possible, from earliest to latest.
1404 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
1405 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1406 // Can't download any more from this peer
1407 break;
1409 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1410 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
1411 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
1412 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1413 pindex->GetBlockHash().ToString(), pfrom->GetId());
1415 if (vGetData.size() > 1) {
1416 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1417 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
1419 if (vGetData.size() > 0) {
1420 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1421 // In any case, we want to download using a compact block, not a regular one
1422 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
1424 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
1428 // If we're in IBD, we want outbound peers that will serve us a useful
1429 // chain. Disconnect peers that are on chains with insufficient work.
1430 if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
1431 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1432 // headers to fetch from this peer.
1433 if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1434 // This peer has too little work on their headers chain to help
1435 // us sync -- disconnect if using an outbound slot (unless
1436 // whitelisted or addnode).
1437 // Note: We compare their tip to nMinimumChainWork (rather than
1438 // chainActive.Tip()) because we won't start block download
1439 // until we have a headers chain that has at least
1440 // nMinimumChainWork, even if a peer has a chain past our tip,
1441 // as an anti-DoS measure.
1442 if (IsOutboundDisconnectionCandidate(pfrom)) {
1443 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
1444 pfrom->fDisconnect = true;
1449 if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
1450 // If this is an outbound peer, check to see if we should protect
1451 // it from the bad/lagging chain logic.
1452 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) {
1453 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId());
1454 nodestate->m_chain_sync.m_protect = true;
1455 ++g_outbound_peers_with_protect_from_disconnect;
1460 return true;
1463 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1465 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1466 if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
1468 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1469 return true;
1473 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1474 (strCommand == NetMsgType::FILTERLOAD ||
1475 strCommand == NetMsgType::FILTERADD))
1477 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1478 LOCK(cs_main);
1479 Misbehaving(pfrom->GetId(), 100);
1480 return false;
1481 } else {
1482 pfrom->fDisconnect = true;
1483 return false;
1487 if (strCommand == NetMsgType::REJECT)
1489 if (LogAcceptCategory(BCLog::NET)) {
1490 try {
1491 std::string strMsg; unsigned char ccode; std::string strReason;
1492 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1494 std::ostringstream ss;
1495 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1497 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1499 uint256 hash;
1500 vRecv >> hash;
1501 ss << ": hash " << hash.ToString();
1503 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1504 } catch (const std::ios_base::failure&) {
1505 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1506 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1511 else if (strCommand == NetMsgType::VERSION)
1513 // Each connection can only send one version message
1514 if (pfrom->nVersion != 0)
1516 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1517 LOCK(cs_main);
1518 Misbehaving(pfrom->GetId(), 1);
1519 return false;
1522 int64_t nTime;
1523 CAddress addrMe;
1524 CAddress addrFrom;
1525 uint64_t nNonce = 1;
1526 uint64_t nServiceInt;
1527 ServiceFlags nServices;
1528 int nVersion;
1529 int nSendVersion;
1530 std::string strSubVer;
1531 std::string cleanSubVer;
1532 int nStartingHeight = -1;
1533 bool fRelay = true;
1535 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1536 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1537 nServices = ServiceFlags(nServiceInt);
1538 if (!pfrom->fInbound)
1540 connman->SetServices(pfrom->addr, nServices);
1542 if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
1544 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
1545 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1546 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
1547 pfrom->fDisconnect = true;
1548 return false;
1551 if (nServices & ((1 << 7) | (1 << 5))) {
1552 if (GetTime() < 1533096000) {
1553 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1554 // These bits have been used as a flag to indicate that a node is running incompatible
1555 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1556 // based on these service bits, at least for a while.
1557 pfrom->fDisconnect = true;
1558 return false;
1562 if (nVersion < MIN_PEER_PROTO_VERSION)
1564 // disconnect from peers older than this proto version
1565 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1566 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1567 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1568 pfrom->fDisconnect = true;
1569 return false;
1572 if (nVersion == 10300)
1573 nVersion = 300;
1574 if (!vRecv.empty())
1575 vRecv >> addrFrom >> nNonce;
1576 if (!vRecv.empty()) {
1577 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1578 cleanSubVer = SanitizeString(strSubVer);
1580 if (!vRecv.empty()) {
1581 vRecv >> nStartingHeight;
1583 if (!vRecv.empty())
1584 vRecv >> fRelay;
1585 // Disconnect if we connected to ourself
1586 if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
1588 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1589 pfrom->fDisconnect = true;
1590 return true;
1593 if (pfrom->fInbound && addrMe.IsRoutable())
1595 SeenLocal(addrMe);
1598 // Be shy and don't send version until we hear
1599 if (pfrom->fInbound)
1600 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1602 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1604 pfrom->nServices = nServices;
1605 pfrom->SetAddrLocal(addrMe);
1607 LOCK(pfrom->cs_SubVer);
1608 pfrom->strSubVer = strSubVer;
1609 pfrom->cleanSubVer = cleanSubVer;
1611 pfrom->nStartingHeight = nStartingHeight;
1612 pfrom->fClient = !(nServices & NODE_NETWORK);
1614 LOCK(pfrom->cs_filter);
1615 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1618 // Change version
1619 pfrom->SetSendVersion(nSendVersion);
1620 pfrom->nVersion = nVersion;
1622 if((nServices & NODE_WITNESS))
1624 LOCK(cs_main);
1625 State(pfrom->GetId())->fHaveWitness = true;
1628 // Potentially mark this peer as a preferred download peer.
1630 LOCK(cs_main);
1631 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1634 if (!pfrom->fInbound)
1636 // Advertise our address
1637 if (fListen && !IsInitialBlockDownload())
1639 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1640 FastRandomContext insecure_rand;
1641 if (addr.IsRoutable())
1643 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1644 pfrom->PushAddress(addr, insecure_rand);
1645 } else if (IsPeerAddrLocalGood(pfrom)) {
1646 addr.SetIP(addrMe);
1647 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1648 pfrom->PushAddress(addr, insecure_rand);
1652 // Get recent addresses
1653 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
1655 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1656 pfrom->fGetAddr = true;
1658 connman->MarkAddressGood(pfrom->addr);
1661 std::string remoteAddr;
1662 if (fLogIPs)
1663 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1665 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1666 cleanSubVer, pfrom->nVersion,
1667 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1668 remoteAddr);
1670 int64_t nTimeOffset = nTime - GetTime();
1671 pfrom->nTimeOffset = nTimeOffset;
1672 AddTimeData(pfrom->addr, nTimeOffset);
1674 // If the peer is old enough to have the old alert system, send it the final alert.
1675 if (pfrom->nVersion <= 70012) {
1676 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1677 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1680 // Feeler connections exist only to verify if address is online.
1681 if (pfrom->fFeeler) {
1682 assert(pfrom->fInbound == false);
1683 pfrom->fDisconnect = true;
1685 return true;
1689 else if (pfrom->nVersion == 0)
1691 // Must have a version message before anything else
1692 LOCK(cs_main);
1693 Misbehaving(pfrom->GetId(), 1);
1694 return false;
1697 // At this point, the outgoing message serialization version can't change.
1698 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1700 if (strCommand == NetMsgType::VERACK)
1702 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1704 if (!pfrom->fInbound) {
1705 // Mark this node as currently connected, so we update its timestamp later.
1706 LOCK(cs_main);
1707 State(pfrom->GetId())->fCurrentlyConnected = true;
1710 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1711 // Tell our peer we prefer to receive headers rather than inv's
1712 // We send this to non-NODE NETWORK peers as well, because even
1713 // non-NODE NETWORK peers can announce blocks (such as pruning
1714 // nodes)
1715 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1717 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1718 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1719 // However, we do not request new block announcements using
1720 // cmpctblock messages.
1721 // We send this to non-NODE NETWORK peers as well, because
1722 // they may wish to request compact blocks from us
1723 bool fAnnounceUsingCMPCTBLOCK = false;
1724 uint64_t nCMPCTBLOCKVersion = 2;
1725 if (pfrom->GetLocalServices() & NODE_WITNESS)
1726 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1727 nCMPCTBLOCKVersion = 1;
1728 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1730 pfrom->fSuccessfullyConnected = true;
1733 else if (!pfrom->fSuccessfullyConnected)
1735 // Must have a verack message before anything else
1736 LOCK(cs_main);
1737 Misbehaving(pfrom->GetId(), 1);
1738 return false;
1741 else if (strCommand == NetMsgType::ADDR)
1743 std::vector<CAddress> vAddr;
1744 vRecv >> vAddr;
1746 // Don't want addr from older versions unless seeding
1747 if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
1748 return true;
1749 if (vAddr.size() > 1000)
1751 LOCK(cs_main);
1752 Misbehaving(pfrom->GetId(), 20);
1753 return error("message addr size() = %u", vAddr.size());
1756 // Store the new addresses
1757 std::vector<CAddress> vAddrOk;
1758 int64_t nNow = GetAdjustedTime();
1759 int64_t nSince = nNow - 10 * 60;
1760 for (CAddress& addr : vAddr)
1762 if (interruptMsgProc)
1763 return true;
1765 // We only bother storing full nodes, though this may include
1766 // things which we would not make an outbound connection to, in
1767 // part because we may make feeler connections to them.
1768 if (!MayHaveUsefulAddressDB(addr.nServices))
1769 continue;
1771 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1772 addr.nTime = nNow - 5 * 24 * 60 * 60;
1773 pfrom->AddAddressKnown(addr);
1774 bool fReachable = IsReachable(addr);
1775 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1777 // Relay to a limited number of other nodes
1778 RelayAddress(addr, fReachable, connman);
1780 // Do not store addresses outside our network
1781 if (fReachable)
1782 vAddrOk.push_back(addr);
1784 connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1785 if (vAddr.size() < 1000)
1786 pfrom->fGetAddr = false;
1787 if (pfrom->fOneShot)
1788 pfrom->fDisconnect = true;
1791 else if (strCommand == NetMsgType::SENDHEADERS)
1793 LOCK(cs_main);
1794 State(pfrom->GetId())->fPreferHeaders = true;
1797 else if (strCommand == NetMsgType::SENDCMPCT)
1799 bool fAnnounceUsingCMPCTBLOCK = false;
1800 uint64_t nCMPCTBLOCKVersion = 0;
1801 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1802 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1803 LOCK(cs_main);
1804 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1805 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1806 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1807 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1809 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1810 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1811 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1812 if (pfrom->GetLocalServices() & NODE_WITNESS)
1813 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1814 else
1815 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1821 else if (strCommand == NetMsgType::INV)
1823 std::vector<CInv> vInv;
1824 vRecv >> vInv;
1825 if (vInv.size() > MAX_INV_SZ)
1827 LOCK(cs_main);
1828 Misbehaving(pfrom->GetId(), 20);
1829 return error("message inv size() = %u", vInv.size());
1832 bool fBlocksOnly = !fRelayTxes;
1834 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1835 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1836 fBlocksOnly = false;
1838 LOCK(cs_main);
1840 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1842 for (CInv &inv : vInv)
1844 if (interruptMsgProc)
1845 return true;
1847 bool fAlreadyHave = AlreadyHave(inv);
1848 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1850 if (inv.type == MSG_TX) {
1851 inv.type |= nFetchFlags;
1854 if (inv.type == MSG_BLOCK) {
1855 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1856 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1857 // We used to request the full block here, but since headers-announcements are now the
1858 // primary method of announcement on the network, and since, in the case that a node
1859 // fell back to inv we probably have a reorg which we should get the headers for first,
1860 // we now only provide a getheaders response here. When we receive the headers, we will
1861 // then ask for the blocks we need.
1862 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1863 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1866 else
1868 pfrom->AddInventoryKnown(inv);
1869 if (fBlocksOnly) {
1870 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1871 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1872 pfrom->AskFor(inv);
1876 // Track requests for our stuff
1877 GetMainSignals().Inventory(inv.hash);
1882 else if (strCommand == NetMsgType::GETDATA)
1884 std::vector<CInv> vInv;
1885 vRecv >> vInv;
1886 if (vInv.size() > MAX_INV_SZ)
1888 LOCK(cs_main);
1889 Misbehaving(pfrom->GetId(), 20);
1890 return error("message getdata size() = %u", vInv.size());
1893 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1895 if (vInv.size() > 0) {
1896 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1899 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1900 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1904 else if (strCommand == NetMsgType::GETBLOCKS)
1906 CBlockLocator locator;
1907 uint256 hashStop;
1908 vRecv >> locator >> hashStop;
1910 // We might have announced the currently-being-connected tip using a
1911 // compact block, which resulted in the peer sending a getblocks
1912 // request, which we would otherwise respond to without the new block.
1913 // To avoid this situation we simply verify that we are on our best
1914 // known chain now. This is super overkill, but we handle it better
1915 // for getheaders requests, and there are no known nodes which support
1916 // compact blocks but still use getblocks to request blocks.
1918 std::shared_ptr<const CBlock> a_recent_block;
1920 LOCK(cs_most_recent_block);
1921 a_recent_block = most_recent_block;
1923 CValidationState dummy;
1924 ActivateBestChain(dummy, Params(), a_recent_block);
1927 LOCK(cs_main);
1929 // Find the last block the caller has in the main chain
1930 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1932 // Send the rest of the chain
1933 if (pindex)
1934 pindex = chainActive.Next(pindex);
1935 int nLimit = 500;
1936 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());
1937 for (; pindex; pindex = chainActive.Next(pindex))
1939 if (pindex->GetBlockHash() == hashStop)
1941 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1942 break;
1944 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1945 // for some reasonable time window (1 hour) that block relay might require.
1946 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1947 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1949 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1950 break;
1952 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1953 if (--nLimit <= 0)
1955 // When this block is requested, we'll send an inv that'll
1956 // trigger the peer to getblocks the next batch of inventory.
1957 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1958 pfrom->hashContinue = pindex->GetBlockHash();
1959 break;
1965 else if (strCommand == NetMsgType::GETBLOCKTXN)
1967 BlockTransactionsRequest req;
1968 vRecv >> req;
1970 std::shared_ptr<const CBlock> recent_block;
1972 LOCK(cs_most_recent_block);
1973 if (most_recent_block_hash == req.blockhash)
1974 recent_block = most_recent_block;
1975 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1977 if (recent_block) {
1978 SendBlockTransactions(*recent_block, req, pfrom, connman);
1979 return true;
1982 LOCK(cs_main);
1984 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1985 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1986 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
1987 return true;
1990 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1991 // If an older block is requested (should never happen in practice,
1992 // but can happen in tests) send a block response instead of a
1993 // blocktxn response. Sending a full block response instead of a
1994 // small blocktxn response is preferable in the case where a peer
1995 // might maliciously send lots of getblocktxn requests to trigger
1996 // expensive disk reads, because it will require the peer to
1997 // actually receive all the data read from disk over the network.
1998 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
1999 CInv inv;
2000 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
2001 inv.hash = req.blockhash;
2002 pfrom->vRecvGetData.push_back(inv);
2003 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2004 return true;
2007 CBlock block;
2008 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
2009 assert(ret);
2011 SendBlockTransactions(block, req, pfrom, connman);
2015 else if (strCommand == NetMsgType::GETHEADERS)
2017 CBlockLocator locator;
2018 uint256 hashStop;
2019 vRecv >> locator >> hashStop;
2021 LOCK(cs_main);
2022 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
2023 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
2024 return true;
2027 CNodeState *nodestate = State(pfrom->GetId());
2028 const CBlockIndex* pindex = nullptr;
2029 if (locator.IsNull())
2031 // If locator is null, return the hashStop block
2032 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
2033 if (mi == mapBlockIndex.end())
2034 return true;
2035 pindex = (*mi).second;
2037 if (!chainActive.Contains(pindex) &&
2038 !StaleBlockRequestAllowed(pindex, chainparams.GetConsensus())) {
2039 LogPrintf("%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
2040 return true;
2043 else
2045 // Find the last block the caller has in the main chain
2046 pindex = FindForkInGlobalIndex(chainActive, locator);
2047 if (pindex)
2048 pindex = chainActive.Next(pindex);
2051 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2052 std::vector<CBlock> vHeaders;
2053 int nLimit = MAX_HEADERS_RESULTS;
2054 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
2055 for (; pindex; pindex = chainActive.Next(pindex))
2057 vHeaders.push_back(pindex->GetBlockHeader());
2058 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2059 break;
2061 // pindex can be nullptr either if we sent chainActive.Tip() OR
2062 // if our peer has chainActive.Tip() (and thus we are sending an empty
2063 // headers message). In both cases it's safe to update
2064 // pindexBestHeaderSent to be our tip.
2066 // It is important that we simply reset the BestHeaderSent value here,
2067 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2068 // the currently-being-connected tip using a compact block, which
2069 // resulted in the peer sending a headers request, which we respond to
2070 // without the new block. By resetting the BestHeaderSent, we ensure we
2071 // will re-announce the new block via headers (or compact blocks again)
2072 // in the SendMessages logic.
2073 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
2074 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2078 else if (strCommand == NetMsgType::TX)
2080 // Stop processing the transaction early if
2081 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2082 if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
2084 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
2085 return true;
2088 std::deque<COutPoint> vWorkQueue;
2089 std::vector<uint256> vEraseQueue;
2090 CTransactionRef ptx;
2091 vRecv >> ptx;
2092 const CTransaction& tx = *ptx;
2094 CInv inv(MSG_TX, tx.GetHash());
2095 pfrom->AddInventoryKnown(inv);
2097 LOCK(cs_main);
2099 bool fMissingInputs = false;
2100 CValidationState state;
2102 pfrom->setAskFor.erase(inv.hash);
2103 mapAlreadyAskedFor.erase(inv.hash);
2105 std::list<CTransactionRef> lRemovedTxn;
2107 if (!AlreadyHave(inv) &&
2108 AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2109 mempool.check(pcoinsTip.get());
2110 RelayTransaction(tx, connman);
2111 for (unsigned int i = 0; i < tx.vout.size(); i++) {
2112 vWorkQueue.emplace_back(inv.hash, i);
2115 pfrom->nLastTXTime = GetTime();
2117 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2118 pfrom->GetId(),
2119 tx.GetHash().ToString(),
2120 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
2122 // Recursively process any orphan transactions that depended on this one
2123 std::set<NodeId> setMisbehaving;
2124 while (!vWorkQueue.empty()) {
2125 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
2126 vWorkQueue.pop_front();
2127 if (itByPrev == mapOrphanTransactionsByPrev.end())
2128 continue;
2129 for (auto mi = itByPrev->second.begin();
2130 mi != itByPrev->second.end();
2131 ++mi)
2133 const CTransactionRef& porphanTx = (*mi)->second.tx;
2134 const CTransaction& orphanTx = *porphanTx;
2135 const uint256& orphanHash = orphanTx.GetHash();
2136 NodeId fromPeer = (*mi)->second.fromPeer;
2137 bool fMissingInputs2 = false;
2138 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2139 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2140 // anyone relaying LegitTxX banned)
2141 CValidationState stateDummy;
2144 if (setMisbehaving.count(fromPeer))
2145 continue;
2146 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2147 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2148 RelayTransaction(orphanTx, connman);
2149 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
2150 vWorkQueue.emplace_back(orphanHash, i);
2152 vEraseQueue.push_back(orphanHash);
2154 else if (!fMissingInputs2)
2156 int nDos = 0;
2157 if (stateDummy.IsInvalid(nDos) && nDos > 0)
2159 // Punish peer that gave us an invalid orphan tx
2160 Misbehaving(fromPeer, nDos);
2161 setMisbehaving.insert(fromPeer);
2162 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
2164 // Has inputs but not accepted to mempool
2165 // Probably non-standard or insufficient fee
2166 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2167 vEraseQueue.push_back(orphanHash);
2168 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
2169 // Do not use rejection cache for witness transactions or
2170 // witness-stripped transactions, as they can have been malleated.
2171 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2172 assert(recentRejects);
2173 recentRejects->insert(orphanHash);
2176 mempool.check(pcoinsTip.get());
2180 for (uint256 hash : vEraseQueue)
2181 EraseOrphanTx(hash);
2183 else if (fMissingInputs)
2185 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
2186 for (const CTxIn& txin : tx.vin) {
2187 if (recentRejects->contains(txin.prevout.hash)) {
2188 fRejectedParents = true;
2189 break;
2192 if (!fRejectedParents) {
2193 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2194 for (const CTxIn& txin : tx.vin) {
2195 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
2196 pfrom->AddInventoryKnown(_inv);
2197 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
2199 AddOrphanTx(ptx, pfrom->GetId());
2201 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2202 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
2203 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
2204 if (nEvicted > 0) {
2205 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
2207 } else {
2208 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
2209 // We will continue to reject this tx since it has rejected
2210 // parents so avoid re-requesting it from other peers.
2211 recentRejects->insert(tx.GetHash());
2213 } else {
2214 if (!tx.HasWitness() && !state.CorruptionPossible()) {
2215 // Do not use rejection cache for witness transactions or
2216 // witness-stripped transactions, as they can have been malleated.
2217 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2218 assert(recentRejects);
2219 recentRejects->insert(tx.GetHash());
2220 if (RecursiveDynamicUsage(*ptx) < 100000) {
2221 AddToCompactExtraTransactions(ptx);
2223 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
2224 AddToCompactExtraTransactions(ptx);
2227 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
2228 // Always relay transactions received from whitelisted peers, even
2229 // if they were already in the mempool or rejected from it due
2230 // to policy, allowing the node to function as a gateway for
2231 // nodes hidden behind it.
2233 // Never relay transactions that we would assign a non-zero DoS
2234 // score for, as we expect peers to do the same with us in that
2235 // case.
2236 int nDoS = 0;
2237 if (!state.IsInvalid(nDoS) || nDoS == 0) {
2238 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
2239 RelayTransaction(tx, connman);
2240 } else {
2241 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
2246 for (const CTransactionRef& removedTx : lRemovedTxn)
2247 AddToCompactExtraTransactions(removedTx);
2249 int nDoS = 0;
2250 if (state.IsInvalid(nDoS))
2252 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
2253 pfrom->GetId(),
2254 FormatStateMessage(state));
2255 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
2256 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
2257 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
2258 if (nDoS > 0) {
2259 Misbehaving(pfrom->GetId(), nDoS);
2265 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2267 CBlockHeaderAndShortTxIDs cmpctblock;
2268 vRecv >> cmpctblock;
2270 bool received_new_header = false;
2273 LOCK(cs_main);
2275 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
2276 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2277 if (!IsInitialBlockDownload())
2278 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2279 return true;
2282 if (mapBlockIndex.find(cmpctblock.header.GetHash()) == mapBlockIndex.end()) {
2283 received_new_header = true;
2287 const CBlockIndex *pindex = nullptr;
2288 CValidationState state;
2289 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
2290 int nDoS;
2291 if (state.IsInvalid(nDoS)) {
2292 if (nDoS > 0) {
2293 LOCK(cs_main);
2294 Misbehaving(pfrom->GetId(), nDoS);
2296 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2297 return true;
2301 // When we succeed in decoding a block's txids from a cmpctblock
2302 // message we typically jump to the BLOCKTXN handling code, with a
2303 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2304 // completing processing of the putative block (without cs_main).
2305 bool fProcessBLOCKTXN = false;
2306 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2308 // If we end up treating this as a plain headers message, call that as well
2309 // without cs_main.
2310 bool fRevertToHeaderProcessing = false;
2312 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2313 // below)
2314 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2315 bool fBlockReconstructed = false;
2318 LOCK(cs_main);
2319 // If AcceptBlockHeader returned true, it set pindex
2320 assert(pindex);
2321 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2323 CNodeState *nodestate = State(pfrom->GetId());
2325 // If this was a new header with more work than our tip, update the
2326 // peer's last block announcement time
2327 if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) {
2328 nodestate->m_last_block_announcement = GetTime();
2331 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2332 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2334 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2335 return true;
2337 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2338 pindex->nTx != 0) { // We had this block at some point, but pruned it
2339 if (fAlreadyInFlight) {
2340 // We requested this block for some reason, but our mempool will probably be useless
2341 // so we just grab the block via normal getdata
2342 std::vector<CInv> vInv(1);
2343 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2344 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2346 return true;
2349 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2350 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2351 return true;
2353 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2354 // Don't bother trying to process compact blocks from v1 peers
2355 // after segwit activates.
2356 return true;
2359 // We want to be a bit conservative just to be extra careful about DoS
2360 // possibilities in compact block processing...
2361 if (pindex->nHeight <= chainActive.Height() + 2) {
2362 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2363 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2364 std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
2365 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2366 if (!(*queuedBlockIt)->partialBlock)
2367 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2368 else {
2369 // The block was already in flight using compact blocks from the same peer
2370 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2371 return true;
2375 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2376 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2377 if (status == READ_STATUS_INVALID) {
2378 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2379 Misbehaving(pfrom->GetId(), 100);
2380 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2381 return true;
2382 } else if (status == READ_STATUS_FAILED) {
2383 // Duplicate txindexes, the block is now in-flight, so just request it
2384 std::vector<CInv> vInv(1);
2385 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2386 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2387 return true;
2390 BlockTransactionsRequest req;
2391 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2392 if (!partialBlock.IsTxAvailable(i))
2393 req.indexes.push_back(i);
2395 if (req.indexes.empty()) {
2396 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2397 BlockTransactions txn;
2398 txn.blockhash = cmpctblock.header.GetHash();
2399 blockTxnMsg << txn;
2400 fProcessBLOCKTXN = true;
2401 } else {
2402 req.blockhash = pindex->GetBlockHash();
2403 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2405 } else {
2406 // This block is either already in flight from a different
2407 // peer, or this peer has too many blocks outstanding to
2408 // download from.
2409 // Optimistically try to reconstruct anyway since we might be
2410 // able to without any round trips.
2411 PartiallyDownloadedBlock tempBlock(&mempool);
2412 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2413 if (status != READ_STATUS_OK) {
2414 // TODO: don't ignore failures
2415 return true;
2417 std::vector<CTransactionRef> dummy;
2418 status = tempBlock.FillBlock(*pblock, dummy);
2419 if (status == READ_STATUS_OK) {
2420 fBlockReconstructed = true;
2423 } else {
2424 if (fAlreadyInFlight) {
2425 // We requested this block, but its far into the future, so our
2426 // mempool will probably be useless - request the block normally
2427 std::vector<CInv> vInv(1);
2428 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2429 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2430 return true;
2431 } else {
2432 // If this was an announce-cmpctblock, we want the same treatment as a header message
2433 fRevertToHeaderProcessing = true;
2436 } // cs_main
2438 if (fProcessBLOCKTXN)
2439 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2441 if (fRevertToHeaderProcessing) {
2442 // Headers received from HB compact block peers are permitted to be
2443 // relayed before full validation (see BIP 152), so we don't want to disconnect
2444 // the peer if the header turns out to be for an invalid block.
2445 // Note that if a peer tries to build on an invalid chain, that
2446 // will be detected and the peer will be banned.
2447 return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
2450 if (fBlockReconstructed) {
2451 // If we got here, we were able to optimistically reconstruct a
2452 // block that is in flight from some other peer.
2454 LOCK(cs_main);
2455 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2457 bool fNewBlock = false;
2458 // Setting fForceProcessing to true means that we bypass some of
2459 // our anti-DoS protections in AcceptBlock, which filters
2460 // unrequested blocks that might be trying to waste our resources
2461 // (eg disk space). Because we only try to reconstruct blocks when
2462 // we're close to caught up (via the CanDirectFetch() requirement
2463 // above, combined with the behavior of not requesting blocks until
2464 // we have a chain with at least nMinimumChainWork), and we ignore
2465 // compact blocks with less work than our tip, it is safe to treat
2466 // reconstructed compact blocks as having been requested.
2467 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2468 if (fNewBlock) {
2469 pfrom->nLastBlockTime = GetTime();
2470 } else {
2471 LOCK(cs_main);
2472 mapBlockSource.erase(pblock->GetHash());
2474 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2475 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2476 // Clear download state for this block, which is in
2477 // process from some other peer. We do this after calling
2478 // ProcessNewBlock so that a malleated cmpctblock announcement
2479 // can't be used to interfere with block relay.
2480 MarkBlockAsReceived(pblock->GetHash());
2486 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2488 BlockTransactions resp;
2489 vRecv >> resp;
2491 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2492 bool fBlockRead = false;
2494 LOCK(cs_main);
2496 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2497 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2498 it->second.first != pfrom->GetId()) {
2499 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2500 return true;
2503 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2504 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2505 if (status == READ_STATUS_INVALID) {
2506 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2507 Misbehaving(pfrom->GetId(), 100);
2508 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2509 return true;
2510 } else if (status == READ_STATUS_FAILED) {
2511 // Might have collided, fall back to getdata now :(
2512 std::vector<CInv> invs;
2513 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2514 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2515 } else {
2516 // Block is either okay, or possibly we received
2517 // READ_STATUS_CHECKBLOCK_FAILED.
2518 // Note that CheckBlock can only fail for one of a few reasons:
2519 // 1. bad-proof-of-work (impossible here, because we've already
2520 // accepted the header)
2521 // 2. merkleroot doesn't match the transactions given (already
2522 // caught in FillBlock with READ_STATUS_FAILED, so
2523 // impossible here)
2524 // 3. the block is otherwise invalid (eg invalid coinbase,
2525 // block is too big, too many legacy sigops, etc).
2526 // So if CheckBlock failed, #3 is the only possibility.
2527 // Under BIP 152, we don't DoS-ban unless proof of work is
2528 // invalid (we don't require all the stateless checks to have
2529 // been run). This is handled below, so just treat this as
2530 // though the block was successfully read, and rely on the
2531 // handling in ProcessNewBlock to ensure the block index is
2532 // updated, reject messages go out, etc.
2533 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2534 fBlockRead = true;
2535 // mapBlockSource is only used for sending reject messages and DoS scores,
2536 // so the race between here and cs_main in ProcessNewBlock is fine.
2537 // BIP 152 permits peers to relay compact blocks after validating
2538 // the header only; we should not punish peers if the block turns
2539 // out to be invalid.
2540 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2542 } // Don't hold cs_main when we call into ProcessNewBlock
2543 if (fBlockRead) {
2544 bool fNewBlock = false;
2545 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2546 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2547 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2548 // disk-space attacks), but this should be safe due to the
2549 // protections in the compact block handler -- see related comment
2550 // in compact block optimistic reconstruction handling.
2551 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2552 if (fNewBlock) {
2553 pfrom->nLastBlockTime = GetTime();
2554 } else {
2555 LOCK(cs_main);
2556 mapBlockSource.erase(pblock->GetHash());
2562 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2564 std::vector<CBlockHeader> headers;
2566 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2567 unsigned int nCount = ReadCompactSize(vRecv);
2568 if (nCount > MAX_HEADERS_RESULTS) {
2569 LOCK(cs_main);
2570 Misbehaving(pfrom->GetId(), 20);
2571 return error("headers message size = %u", nCount);
2573 headers.resize(nCount);
2574 for (unsigned int n = 0; n < nCount; n++) {
2575 vRecv >> headers[n];
2576 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2579 // Headers received via a HEADERS message should be valid, and reflect
2580 // the chain the peer is on. If we receive a known-invalid header,
2581 // disconnect the peer if it is using one of our outbound connection
2582 // slots.
2583 bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
2584 return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
2587 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2589 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2590 vRecv >> *pblock;
2592 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2594 bool forceProcessing = false;
2595 const uint256 hash(pblock->GetHash());
2597 LOCK(cs_main);
2598 // Also always process if we requested the block explicitly, as we may
2599 // need it even though it is not a candidate for a new best tip.
2600 forceProcessing |= MarkBlockAsReceived(hash);
2601 // mapBlockSource is only used for sending reject messages and DoS scores,
2602 // so the race between here and cs_main in ProcessNewBlock is fine.
2603 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2605 bool fNewBlock = false;
2606 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2607 if (fNewBlock) {
2608 pfrom->nLastBlockTime = GetTime();
2609 } else {
2610 LOCK(cs_main);
2611 mapBlockSource.erase(pblock->GetHash());
2616 else if (strCommand == NetMsgType::GETADDR)
2618 // This asymmetric behavior for inbound and outbound connections was introduced
2619 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2620 // to users' AddrMan and later request them by sending getaddr messages.
2621 // Making nodes which are behind NAT and can only make outgoing connections ignore
2622 // the getaddr message mitigates the attack.
2623 if (!pfrom->fInbound) {
2624 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2625 return true;
2628 // Only send one GetAddr response per connection to reduce resource waste
2629 // and discourage addr stamping of INV announcements.
2630 if (pfrom->fSentAddr) {
2631 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2632 return true;
2634 pfrom->fSentAddr = true;
2636 pfrom->vAddrToSend.clear();
2637 std::vector<CAddress> vAddr = connman->GetAddresses();
2638 FastRandomContext insecure_rand;
2639 for (const CAddress &addr : vAddr)
2640 pfrom->PushAddress(addr, insecure_rand);
2644 else if (strCommand == NetMsgType::MEMPOOL)
2646 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2648 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2649 pfrom->fDisconnect = true;
2650 return true;
2653 if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
2655 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2656 pfrom->fDisconnect = true;
2657 return true;
2660 LOCK(pfrom->cs_inventory);
2661 pfrom->fSendMempool = true;
2665 else if (strCommand == NetMsgType::PING)
2667 if (pfrom->nVersion > BIP0031_VERSION)
2669 uint64_t nonce = 0;
2670 vRecv >> nonce;
2671 // Echo the message back with the nonce. This allows for two useful features:
2673 // 1) A remote node can quickly check if the connection is operational
2674 // 2) Remote nodes can measure the latency of the network thread. If this node
2675 // is overloaded it won't respond to pings quickly and the remote node can
2676 // avoid sending us more work, like chain download requests.
2678 // The nonce stops the remote getting confused between different pings: without
2679 // it, if the remote node sends a ping once per second and this node takes 5
2680 // seconds to respond to each, the 5th ping the remote sends would appear to
2681 // return very quickly.
2682 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2687 else if (strCommand == NetMsgType::PONG)
2689 int64_t pingUsecEnd = nTimeReceived;
2690 uint64_t nonce = 0;
2691 size_t nAvail = vRecv.in_avail();
2692 bool bPingFinished = false;
2693 std::string sProblem;
2695 if (nAvail >= sizeof(nonce)) {
2696 vRecv >> nonce;
2698 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2699 if (pfrom->nPingNonceSent != 0) {
2700 if (nonce == pfrom->nPingNonceSent) {
2701 // Matching pong received, this ping is no longer outstanding
2702 bPingFinished = true;
2703 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2704 if (pingUsecTime > 0) {
2705 // Successful ping time measurement, replace previous
2706 pfrom->nPingUsecTime = pingUsecTime;
2707 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2708 } else {
2709 // This should never happen
2710 sProblem = "Timing mishap";
2712 } else {
2713 // Nonce mismatches are normal when pings are overlapping
2714 sProblem = "Nonce mismatch";
2715 if (nonce == 0) {
2716 // This is most likely a bug in another implementation somewhere; cancel this ping
2717 bPingFinished = true;
2718 sProblem = "Nonce zero";
2721 } else {
2722 sProblem = "Unsolicited pong without ping";
2724 } else {
2725 // This is most likely a bug in another implementation somewhere; cancel this ping
2726 bPingFinished = true;
2727 sProblem = "Short payload";
2730 if (!(sProblem.empty())) {
2731 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2732 pfrom->GetId(),
2733 sProblem,
2734 pfrom->nPingNonceSent,
2735 nonce,
2736 nAvail);
2738 if (bPingFinished) {
2739 pfrom->nPingNonceSent = 0;
2744 else if (strCommand == NetMsgType::FILTERLOAD)
2746 CBloomFilter filter;
2747 vRecv >> filter;
2749 if (!filter.IsWithinSizeConstraints())
2751 // There is no excuse for sending a too-large filter
2752 LOCK(cs_main);
2753 Misbehaving(pfrom->GetId(), 100);
2755 else
2757 LOCK(pfrom->cs_filter);
2758 pfrom->pfilter.reset(new CBloomFilter(filter));
2759 pfrom->pfilter->UpdateEmptyFull();
2760 pfrom->fRelayTxes = true;
2765 else if (strCommand == NetMsgType::FILTERADD)
2767 std::vector<unsigned char> vData;
2768 vRecv >> vData;
2770 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2771 // and thus, the maximum size any matched object can have) in a filteradd message
2772 bool bad = false;
2773 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2774 bad = true;
2775 } else {
2776 LOCK(pfrom->cs_filter);
2777 if (pfrom->pfilter) {
2778 pfrom->pfilter->insert(vData);
2779 } else {
2780 bad = true;
2783 if (bad) {
2784 LOCK(cs_main);
2785 Misbehaving(pfrom->GetId(), 100);
2790 else if (strCommand == NetMsgType::FILTERCLEAR)
2792 LOCK(pfrom->cs_filter);
2793 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2794 pfrom->pfilter.reset(new CBloomFilter());
2796 pfrom->fRelayTxes = true;
2799 else if (strCommand == NetMsgType::FEEFILTER) {
2800 CAmount newFeeFilter = 0;
2801 vRecv >> newFeeFilter;
2802 if (MoneyRange(newFeeFilter)) {
2804 LOCK(pfrom->cs_feeFilter);
2805 pfrom->minFeeFilter = newFeeFilter;
2807 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2811 else if (strCommand == NetMsgType::NOTFOUND) {
2812 // We do not care about the NOTFOUND message, but logging an Unknown Command
2813 // message would be undesirable as we transmit it ourselves.
2816 else {
2817 // Ignore unknown commands for extensibility
2818 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2823 return true;
2826 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
2828 AssertLockHeld(cs_main);
2829 CNodeState &state = *State(pnode->GetId());
2831 for (const CBlockReject& reject : state.rejects) {
2832 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2834 state.rejects.clear();
2836 if (state.fShouldBan) {
2837 state.fShouldBan = false;
2838 if (pnode->fWhitelisted)
2839 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2840 else if (pnode->m_manual_connection)
2841 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
2842 else {
2843 pnode->fDisconnect = true;
2844 if (pnode->addr.IsLocal())
2845 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2846 else
2848 connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2851 return true;
2853 return false;
2856 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2858 const CChainParams& chainparams = Params();
2860 // Message format
2861 // (4) message start
2862 // (12) command
2863 // (4) size
2864 // (4) checksum
2865 // (x) data
2867 bool fMoreWork = false;
2869 if (!pfrom->vRecvGetData.empty())
2870 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2872 if (pfrom->fDisconnect)
2873 return false;
2875 // this maintains the order of responses
2876 if (!pfrom->vRecvGetData.empty()) return true;
2878 // Don't bother if send buffer is too full to respond anyway
2879 if (pfrom->fPauseSend)
2880 return false;
2882 std::list<CNetMessage> msgs;
2884 LOCK(pfrom->cs_vProcessMsg);
2885 if (pfrom->vProcessMsg.empty())
2886 return false;
2887 // Just take one message
2888 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2889 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2890 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize();
2891 fMoreWork = !pfrom->vProcessMsg.empty();
2893 CNetMessage& msg(msgs.front());
2895 msg.SetVersion(pfrom->GetRecvVersion());
2896 // Scan for message start
2897 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2898 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2899 pfrom->fDisconnect = true;
2900 return false;
2903 // Read header
2904 CMessageHeader& hdr = msg.hdr;
2905 if (!hdr.IsValid(chainparams.MessageStart()))
2907 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2908 return fMoreWork;
2910 std::string strCommand = hdr.GetCommand();
2912 // Message size
2913 unsigned int nMessageSize = hdr.nMessageSize;
2915 // Checksum
2916 CDataStream& vRecv = msg.vRecv;
2917 const uint256& hash = msg.GetMessageHash();
2918 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2920 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2921 SanitizeString(strCommand), nMessageSize,
2922 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2923 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2924 return fMoreWork;
2927 // Process message
2928 bool fRet = false;
2931 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2932 if (interruptMsgProc)
2933 return false;
2934 if (!pfrom->vRecvGetData.empty())
2935 fMoreWork = true;
2937 catch (const std::ios_base::failure& e)
2939 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2940 if (strstr(e.what(), "end of data"))
2942 // Allow exceptions from under-length message on vRecv
2943 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());
2945 else if (strstr(e.what(), "size too large"))
2947 // Allow exceptions from over-long size
2948 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2950 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2952 // Allow exceptions from non-canonical encoding
2953 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2955 else
2957 PrintExceptionContinue(&e, "ProcessMessages()");
2960 catch (const std::exception& e) {
2961 PrintExceptionContinue(&e, "ProcessMessages()");
2962 } catch (...) {
2963 PrintExceptionContinue(nullptr, "ProcessMessages()");
2966 if (!fRet) {
2967 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
2970 LOCK(cs_main);
2971 SendRejectsAndCheckIfBanned(pfrom, connman);
2973 return fMoreWork;
2976 void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
2978 AssertLockHeld(cs_main);
2980 CNodeState &state = *State(pto->GetId());
2981 const CNetMsgMaker msgMaker(pto->GetSendVersion());
2983 if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
2984 // This is an outbound peer subject to disconnection if they don't
2985 // announce a block with as much work as the current tip within
2986 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
2987 // their chain has more work than ours, we should sync to it,
2988 // unless it's invalid, in which case we should find that out and
2989 // disconnect from them elsewhere).
2990 if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
2991 if (state.m_chain_sync.m_timeout != 0) {
2992 state.m_chain_sync.m_timeout = 0;
2993 state.m_chain_sync.m_work_header = nullptr;
2994 state.m_chain_sync.m_sent_getheaders = false;
2996 } 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)) {
2997 // Our best block known by this peer is behind our tip, and we're either noticing
2998 // that for the first time, OR this peer was able to catch up to some earlier point
2999 // where we checked against our tip.
3000 // Either way, set a new timeout based on current tip.
3001 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
3002 state.m_chain_sync.m_work_header = chainActive.Tip();
3003 state.m_chain_sync.m_sent_getheaders = false;
3004 } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
3005 // No evidence yet that our peer has synced to a chain with work equal to that
3006 // of our tip, when we first detected it was behind. Send a single getheaders
3007 // message to give the peer a chance to update us.
3008 if (state.m_chain_sync.m_sent_getheaders) {
3009 // They've run out of time to catch up!
3010 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
3011 pto->fDisconnect = true;
3012 } else {
3013 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());
3014 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
3015 state.m_chain_sync.m_sent_getheaders = true;
3016 constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
3017 // Bump the timeout to allow a response, which could clear the timeout
3018 // (if the response shows the peer has synced), reset the timeout (if
3019 // the peer syncs to the required work but not to our tip), or result
3020 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3021 // has not sufficiently progressed)
3022 state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
3028 void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
3030 // Check whether we have too many outbound peers
3031 int extra_peers = connman->GetExtraOutboundCount();
3032 if (extra_peers > 0) {
3033 // If we have more outbound peers than we target, disconnect one.
3034 // Pick the outbound peer that least recently announced
3035 // us a new block, with ties broken by choosing the more recent
3036 // connection (higher node id)
3037 NodeId worst_peer = -1;
3038 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
3040 LOCK(cs_main);
3042 connman->ForEachNode([&](CNode* pnode) {
3043 // Ignore non-outbound peers, or nodes marked for disconnect already
3044 if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
3045 CNodeState *state = State(pnode->GetId());
3046 if (state == nullptr) return; // shouldn't be possible, but just in case
3047 // Don't evict our protected peers
3048 if (state->m_chain_sync.m_protect) return;
3049 if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
3050 worst_peer = pnode->GetId();
3051 oldest_block_announcement = state->m_last_block_announcement;
3054 if (worst_peer != -1) {
3055 bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
3056 // Only disconnect a peer that has been connected to us for
3057 // some reasonable fraction of our check-frequency, to give
3058 // it time for new information to have arrived.
3059 // Also don't disconnect any peer we're trying to download a
3060 // block from.
3061 CNodeState &state = *State(pnode->GetId());
3062 if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
3063 LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
3064 pnode->fDisconnect = true;
3065 return true;
3066 } else {
3067 LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
3068 return false;
3071 if (disconnected) {
3072 // If we disconnected an extra peer, that means we successfully
3073 // connected to at least one peer after the last time we
3074 // detected a stale tip. Don't try any more extra peers until
3075 // we next detect a stale tip, to limit the load we put on the
3076 // network from these extra connections.
3077 connman->SetTryNewOutboundPeer(false);
3083 void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
3085 if (connman == nullptr) return;
3087 int64_t time_in_seconds = GetTime();
3089 EvictExtraOutboundPeers(time_in_seconds);
3091 if (time_in_seconds > m_stale_tip_check_time) {
3092 LOCK(cs_main);
3093 // Check whether our tip is stale, and if so, allow using an extra
3094 // outbound peer
3095 if (TipMayBeStale(consensusParams)) {
3096 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);
3097 connman->SetTryNewOutboundPeer(true);
3098 } else if (connman->GetTryNewOutboundPeer()) {
3099 connman->SetTryNewOutboundPeer(false);
3101 m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
3105 class CompareInvMempoolOrder
3107 CTxMemPool *mp;
3108 public:
3109 explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
3111 mp = _mempool;
3114 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
3116 /* As std::make_heap produces a max-heap, we want the entries with the
3117 * fewest ancestors/highest fee to sort later. */
3118 return mp->CompareDepthAndScore(*b, *a);
3122 bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
3124 const Consensus::Params& consensusParams = Params().GetConsensus();
3126 // Don't send anything until the version handshake is complete
3127 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
3128 return true;
3130 // If we get here, the outgoing message serialization version is set and can't change.
3131 const CNetMsgMaker msgMaker(pto->GetSendVersion());
3134 // Message: ping
3136 bool pingSend = false;
3137 if (pto->fPingQueued) {
3138 // RPC ping request by user
3139 pingSend = true;
3141 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
3142 // Ping automatically sent as a latency probe & keepalive.
3143 pingSend = true;
3145 if (pingSend) {
3146 uint64_t nonce = 0;
3147 while (nonce == 0) {
3148 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
3150 pto->fPingQueued = false;
3151 pto->nPingUsecStart = GetTimeMicros();
3152 if (pto->nVersion > BIP0031_VERSION) {
3153 pto->nPingNonceSent = nonce;
3154 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
3155 } else {
3156 // Peer is too old to support ping command with nonce, pong will never arrive.
3157 pto->nPingNonceSent = 0;
3158 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
3162 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3163 if (!lockMain)
3164 return true;
3166 if (SendRejectsAndCheckIfBanned(pto, connman))
3167 return true;
3168 CNodeState &state = *State(pto->GetId());
3170 // Address refresh broadcast
3171 int64_t nNow = GetTimeMicros();
3172 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3173 AdvertiseLocal(pto);
3174 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
3178 // Message: addr
3180 if (pto->nNextAddrSend < nNow) {
3181 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
3182 std::vector<CAddress> vAddr;
3183 vAddr.reserve(pto->vAddrToSend.size());
3184 for (const CAddress& addr : pto->vAddrToSend)
3186 if (!pto->addrKnown.contains(addr.GetKey()))
3188 pto->addrKnown.insert(addr.GetKey());
3189 vAddr.push_back(addr);
3190 // receiver rejects addr messages larger than 1000
3191 if (vAddr.size() >= 1000)
3193 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3194 vAddr.clear();
3198 pto->vAddrToSend.clear();
3199 if (!vAddr.empty())
3200 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3201 // we only send the big addr message once
3202 if (pto->vAddrToSend.capacity() > 40)
3203 pto->vAddrToSend.shrink_to_fit();
3206 // Start block sync
3207 if (pindexBestHeader == nullptr)
3208 pindexBestHeader = chainActive.Tip();
3209 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.
3210 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
3211 // Only actively request headers from a single peer, unless we're close to today.
3212 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3213 state.fSyncStarted = true;
3214 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
3215 nSyncStarted++;
3216 const CBlockIndex *pindexStart = pindexBestHeader;
3217 /* If possible, start at the block preceding the currently
3218 best known header. This ensures that we always get a
3219 non-empty list of headers back as long as the peer
3220 is up-to-date. With a non-empty response, we can initialise
3221 the peer's known best block. This wouldn't be possible
3222 if we requested starting at pindexBestHeader and
3223 got back an empty response. */
3224 if (pindexStart->pprev)
3225 pindexStart = pindexStart->pprev;
3226 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
3227 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
3231 // Resend wallet transactions that haven't gotten in a block yet
3232 // Except during reindex, importing and IBD, when old wallet
3233 // transactions become unconfirmed and spams other nodes.
3234 if (!fReindex && !fImporting && !IsInitialBlockDownload())
3236 GetMainSignals().Broadcast(nTimeBestReceived, connman);
3240 // Try sending block announcements via headers
3243 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3244 // list of block hashes we're relaying, and our peer wants
3245 // headers announcements, then find the first header
3246 // not yet known to our peer but would connect, and send.
3247 // If no header would connect, or if we have too many
3248 // blocks, or if the peer doesn't want headers, just
3249 // add all to the inv queue.
3250 LOCK(pto->cs_inventory);
3251 std::vector<CBlock> vHeaders;
3252 bool fRevertToInv = ((!state.fPreferHeaders &&
3253 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
3254 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
3255 const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
3256 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
3258 if (!fRevertToInv) {
3259 bool fFoundStartingHeader = false;
3260 // Try to find first header that our peer doesn't have, and
3261 // then send all headers past that one. If we come across any
3262 // headers that aren't on chainActive, give up.
3263 for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3264 BlockMap::iterator mi = mapBlockIndex.find(hash);
3265 assert(mi != mapBlockIndex.end());
3266 const CBlockIndex *pindex = mi->second;
3267 if (chainActive[pindex->nHeight] != pindex) {
3268 // Bail out if we reorged away from this block
3269 fRevertToInv = true;
3270 break;
3272 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
3273 // This means that the list of blocks to announce don't
3274 // connect to each other.
3275 // This shouldn't really be possible to hit during
3276 // regular operation (because reorgs should take us to
3277 // a chain that has some block not on the prior chain,
3278 // which should be caught by the prior check), but one
3279 // way this could happen is by using invalidateblock /
3280 // reconsiderblock repeatedly on the tip, causing it to
3281 // be added multiple times to vBlockHashesToAnnounce.
3282 // Robustly deal with this rare situation by reverting
3283 // to an inv.
3284 fRevertToInv = true;
3285 break;
3287 pBestIndex = pindex;
3288 if (fFoundStartingHeader) {
3289 // add this to the headers message
3290 vHeaders.push_back(pindex->GetBlockHeader());
3291 } else if (PeerHasHeader(&state, pindex)) {
3292 continue; // keep looking for the first new block
3293 } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
3294 // Peer doesn't have this header but they do have the prior one.
3295 // Start sending headers.
3296 fFoundStartingHeader = true;
3297 vHeaders.push_back(pindex->GetBlockHeader());
3298 } else {
3299 // Peer doesn't have this header or the prior one -- nothing will
3300 // connect, so bail out.
3301 fRevertToInv = true;
3302 break;
3306 if (!fRevertToInv && !vHeaders.empty()) {
3307 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
3308 // We only send up to 1 block as header-and-ids, as otherwise
3309 // probably means we're doing an initial-ish-sync or they're slow
3310 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
3311 vHeaders.front().GetHash().ToString(), pto->GetId());
3313 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
3315 bool fGotBlockFromCache = false;
3317 LOCK(cs_most_recent_block);
3318 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
3319 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
3320 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
3321 else {
3322 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
3323 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3325 fGotBlockFromCache = true;
3328 if (!fGotBlockFromCache) {
3329 CBlock block;
3330 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3331 assert(ret);
3332 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3333 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3335 state.pindexBestHeaderSent = pBestIndex;
3336 } else if (state.fPreferHeaders) {
3337 if (vHeaders.size() > 1) {
3338 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3339 vHeaders.size(),
3340 vHeaders.front().GetHash().ToString(),
3341 vHeaders.back().GetHash().ToString(), pto->GetId());
3342 } else {
3343 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3344 vHeaders.front().GetHash().ToString(), pto->GetId());
3346 connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3347 state.pindexBestHeaderSent = pBestIndex;
3348 } else
3349 fRevertToInv = true;
3351 if (fRevertToInv) {
3352 // If falling back to using an inv, just try to inv the tip.
3353 // The last entry in vBlockHashesToAnnounce was our tip at some point
3354 // in the past.
3355 if (!pto->vBlockHashesToAnnounce.empty()) {
3356 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3357 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3358 assert(mi != mapBlockIndex.end());
3359 const CBlockIndex *pindex = mi->second;
3361 // Warn if we're announcing a block that is not on the main chain.
3362 // This should be very rare and could be optimized out.
3363 // Just log for now.
3364 if (chainActive[pindex->nHeight] != pindex) {
3365 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3366 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3369 // If the peer's chain has this block, don't inv it back.
3370 if (!PeerHasHeader(&state, pindex)) {
3371 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3372 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3373 pto->GetId(), hashToAnnounce.ToString());
3377 pto->vBlockHashesToAnnounce.clear();
3381 // Message: inventory
3383 std::vector<CInv> vInv;
3385 LOCK(pto->cs_inventory);
3386 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3388 // Add blocks
3389 for (const uint256& hash : pto->vInventoryBlockToSend) {
3390 vInv.push_back(CInv(MSG_BLOCK, hash));
3391 if (vInv.size() == MAX_INV_SZ) {
3392 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3393 vInv.clear();
3396 pto->vInventoryBlockToSend.clear();
3398 // Check whether periodic sends should happen
3399 bool fSendTrickle = pto->fWhitelisted;
3400 if (pto->nNextInvSend < nNow) {
3401 fSendTrickle = true;
3402 // Use half the delay for outbound peers, as there is less privacy concern for them.
3403 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3406 // Time to send but the peer has requested we not relay transactions.
3407 if (fSendTrickle) {
3408 LOCK(pto->cs_filter);
3409 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3412 // Respond to BIP35 mempool requests
3413 if (fSendTrickle && pto->fSendMempool) {
3414 auto vtxinfo = mempool.infoAll();
3415 pto->fSendMempool = false;
3416 CAmount filterrate = 0;
3418 LOCK(pto->cs_feeFilter);
3419 filterrate = pto->minFeeFilter;
3422 LOCK(pto->cs_filter);
3424 for (const auto& txinfo : vtxinfo) {
3425 const uint256& hash = txinfo.tx->GetHash();
3426 CInv inv(MSG_TX, hash);
3427 pto->setInventoryTxToSend.erase(hash);
3428 if (filterrate) {
3429 if (txinfo.feeRate.GetFeePerK() < filterrate)
3430 continue;
3432 if (pto->pfilter) {
3433 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3435 pto->filterInventoryKnown.insert(hash);
3436 vInv.push_back(inv);
3437 if (vInv.size() == MAX_INV_SZ) {
3438 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3439 vInv.clear();
3442 pto->timeLastMempoolReq = GetTime();
3445 // Determine transactions to relay
3446 if (fSendTrickle) {
3447 // Produce a vector with all candidates for sending
3448 std::vector<std::set<uint256>::iterator> vInvTx;
3449 vInvTx.reserve(pto->setInventoryTxToSend.size());
3450 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3451 vInvTx.push_back(it);
3453 CAmount filterrate = 0;
3455 LOCK(pto->cs_feeFilter);
3456 filterrate = pto->minFeeFilter;
3458 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3459 // A heap is used so that not all items need sorting if only a few are being sent.
3460 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3461 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3462 // No reason to drain out at many times the network's capacity,
3463 // especially since we have many peers and some will draw much shorter delays.
3464 unsigned int nRelayedTransactions = 0;
3465 LOCK(pto->cs_filter);
3466 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3467 // Fetch the top element from the heap
3468 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3469 std::set<uint256>::iterator it = vInvTx.back();
3470 vInvTx.pop_back();
3471 uint256 hash = *it;
3472 // Remove it from the to-be-sent set
3473 pto->setInventoryTxToSend.erase(it);
3474 // Check if not in the filter already
3475 if (pto->filterInventoryKnown.contains(hash)) {
3476 continue;
3478 // Not in the mempool anymore? don't bother sending it.
3479 auto txinfo = mempool.info(hash);
3480 if (!txinfo.tx) {
3481 continue;
3483 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3484 continue;
3486 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3487 // Send
3488 vInv.push_back(CInv(MSG_TX, hash));
3489 nRelayedTransactions++;
3491 // Expire old relay messages
3492 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3494 mapRelay.erase(vRelayExpiration.front().second);
3495 vRelayExpiration.pop_front();
3498 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3499 if (ret.second) {
3500 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3503 if (vInv.size() == MAX_INV_SZ) {
3504 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3505 vInv.clear();
3507 pto->filterInventoryKnown.insert(hash);
3511 if (!vInv.empty())
3512 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3514 // Detect whether we're stalling
3515 nNow = GetTimeMicros();
3516 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3517 // Stalling only triggers when the block download window cannot move. During normal steady state,
3518 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3519 // should only happen during initial block download.
3520 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3521 pto->fDisconnect = true;
3522 return true;
3524 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3525 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3526 // We compensate for other peers to prevent killing off peers due to our own downstream link
3527 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3528 // to unreasonably increase our timeout.
3529 if (state.vBlocksInFlight.size() > 0) {
3530 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3531 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3532 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3533 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3534 pto->fDisconnect = true;
3535 return true;
3538 // Check for headers sync timeouts
3539 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3540 // Detect whether this is a stalling initial-headers-sync peer
3541 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3542 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3543 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3544 // and we have others we could be using instead.
3545 // Note: If all our peers are inbound, then we won't
3546 // disconnect our sync peer for stalling; we have bigger
3547 // problems if we can't get any outbound peers.
3548 if (!pto->fWhitelisted) {
3549 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3550 pto->fDisconnect = true;
3551 return true;
3552 } else {
3553 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3554 // Reset the headers sync state so that we have a
3555 // chance to try downloading from a different peer.
3556 // Note: this will also result in at least one more
3557 // getheaders message to be sent to
3558 // this peer (eventually).
3559 state.fSyncStarted = false;
3560 nSyncStarted--;
3561 state.nHeadersSyncTimeout = 0;
3564 } else {
3565 // After we've caught up once, reset the timeout so we can't trigger
3566 // disconnect later.
3567 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3571 // Check that outbound peers have reasonable chains
3572 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3573 ConsiderEviction(pto, GetTime());
3576 // Message: getdata (blocks)
3578 std::vector<CInv> vGetData;
3579 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3580 std::vector<const CBlockIndex*> vToDownload;
3581 NodeId staller = -1;
3582 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3583 for (const CBlockIndex *pindex : vToDownload) {
3584 uint32_t nFetchFlags = GetFetchFlags(pto);
3585 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3586 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3587 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3588 pindex->nHeight, pto->GetId());
3590 if (state.nBlocksInFlight == 0 && staller != -1) {
3591 if (State(staller)->nStallingSince == 0) {
3592 State(staller)->nStallingSince = nNow;
3593 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3599 // Message: getdata (non-blocks)
3601 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3603 const CInv& inv = (*pto->mapAskFor.begin()).second;
3604 if (!AlreadyHave(inv))
3606 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3607 vGetData.push_back(inv);
3608 if (vGetData.size() >= 1000)
3610 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3611 vGetData.clear();
3613 } else {
3614 //If we're not going to ask, don't expect a response.
3615 pto->setAskFor.erase(inv.hash);
3617 pto->mapAskFor.erase(pto->mapAskFor.begin());
3619 if (!vGetData.empty())
3620 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3623 // Message: feefilter
3625 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3626 if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3627 !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3628 CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3629 int64_t timeNow = GetTimeMicros();
3630 if (timeNow > pto->nextSendTimeFeeFilter) {
3631 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3632 static FeeFilterRounder filterRounder(default_feerate);
3633 CAmount filterToSend = filterRounder.round(currentFilter);
3634 // We always have a fee filter of at least minRelayTxFee
3635 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3636 if (filterToSend != pto->lastSentFeeFilter) {
3637 connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3638 pto->lastSentFeeFilter = filterToSend;
3640 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3642 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3643 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3644 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3645 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3646 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3650 return true;
3653 class CNetProcessingCleanup
3655 public:
3656 CNetProcessingCleanup() {}
3657 ~CNetProcessingCleanup() {
3658 // orphan transactions
3659 mapOrphanTransactions.clear();
3660 mapOrphanTransactionsByPrev.clear();
3662 } instance_of_cnetprocessingcleanup;