Merge #12001: [RPC] Adding ::minRelayTxFee amount to getmempoolinfo and updating...
[bitcoinplatinum.git] / src / net_processing.cpp
blob3cf96be61accf349d2c4c197506d9baf96656139
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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 <netmessagemaker.h>
18 #include <netbase.h>
19 #include <policy/fees.h>
20 #include <policy/policy.h>
21 #include <primitives/block.h>
22 #include <primitives/transaction.h>
23 #include <random.h>
24 #include <reverse_iterator.h>
25 #include <scheduler.h>
26 #include <tinyformat.h>
27 #include <txmempool.h>
28 #include <ui_interface.h>
29 #include <util.h>
30 #include <utilmoneystr.h>
31 #include <utilstrencodings.h>
33 #if defined(NDEBUG)
34 # error "Bitcoin cannot be compiled without assertions."
35 #endif
37 std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
39 struct IteratorComparator
41 template<typename I>
42 bool operator()(const I& a, const I& b) const
44 return &(*a) < &(*b);
48 struct COrphanTx {
49 // When modifying, adapt the copy of this definition in tests/DoS_tests.
50 CTransactionRef tx;
51 NodeId fromPeer;
52 int64_t nTimeExpire;
54 static CCriticalSection g_cs_orphans;
55 std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans);
56 std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(g_cs_orphans);
57 void EraseOrphansFor(NodeId peer);
59 static size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0;
60 static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans);
62 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
64 /// Age after which a stale block will no longer be served if requested as
65 /// protection against fingerprinting. Set to one month, denominated in seconds.
66 static const int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
68 /// Age after which a block is considered historical for purposes of rate
69 /// limiting block relay. Set to one week, denominated in seconds.
70 static const int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
72 // Internal stuff
73 namespace {
74 /** Number of nodes with fSyncStarted. */
75 int nSyncStarted = 0;
77 /**
78 * Sources of received blocks, saved to be able to send them reject
79 * messages or ban them when processing happens afterwards. Protected by
80 * cs_main.
81 * Set mapBlockSource[hash].second to false if the node should not be
82 * punished if the block is invalid.
84 std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
86 /**
87 * Filter for transactions that were recently rejected by
88 * AcceptToMemoryPool. These are not rerequested until the chain tip
89 * changes, at which point the entire filter is reset. Protected by
90 * cs_main.
92 * Without this filter we'd be re-requesting txs from each of our peers,
93 * increasing bandwidth consumption considerably. For instance, with 100
94 * peers, half of which relay a tx we don't accept, that might be a 50x
95 * bandwidth increase. A flooding attacker attempting to roll-over the
96 * filter using minimum-sized, 60byte, transactions might manage to send
97 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
98 * two minute window to send invs to us.
100 * Decreasing the false positive rate is fairly cheap, so we pick one in a
101 * million to make it highly unlikely for users to have issues with this
102 * filter.
104 * Memory used: 1.3 MB
106 std::unique_ptr<CRollingBloomFilter> recentRejects;
107 uint256 hashRecentRejectsChainTip;
109 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
110 struct QueuedBlock {
111 uint256 hash;
112 const CBlockIndex* pindex; //!< Optional.
113 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
114 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
116 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
118 /** Stack of nodes which we have set to announce using compact blocks */
119 std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
121 /** Number of preferable block download peers. */
122 int nPreferredDownload = 0;
124 /** Number of peers from which we're downloading blocks. */
125 int nPeersWithValidatedDownloads = 0;
127 /** Number of outbound peers with m_chain_sync.m_protect. */
128 int g_outbound_peers_with_protect_from_disconnect = 0;
130 /** When our tip was last updated. */
131 std::atomic<int64_t> g_last_tip_update(0);
133 /** Relay map, protected by cs_main. */
134 typedef std::map<uint256, CTransactionRef> MapRelay;
135 MapRelay mapRelay;
136 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
137 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
138 } // namespace
140 namespace {
142 struct CBlockReject {
143 unsigned char chRejectCode;
144 std::string strRejectReason;
145 uint256 hashBlock;
149 * Maintain validation-specific state about nodes, protected by cs_main, instead
150 * by CNode's own locks. This simplifies asynchronous operation, where
151 * processing of incoming data is done after the ProcessMessage call returns,
152 * and we're no longer holding the node's locks.
154 struct CNodeState {
155 //! The peer's address
156 const CService address;
157 //! Whether we have a fully established connection.
158 bool fCurrentlyConnected;
159 //! Accumulated misbehaviour score for this peer.
160 int nMisbehavior;
161 //! Whether this peer should be disconnected and banned (unless whitelisted).
162 bool fShouldBan;
163 //! String name of this peer (debugging/logging purposes).
164 const std::string name;
165 //! List of asynchronously-determined block rejections to notify this peer about.
166 std::vector<CBlockReject> rejects;
167 //! The best known block we know this peer has announced.
168 const CBlockIndex *pindexBestKnownBlock;
169 //! The hash of the last unknown block this peer has announced.
170 uint256 hashLastUnknownBlock;
171 //! The last full block we both have.
172 const CBlockIndex *pindexLastCommonBlock;
173 //! The best header we have sent our peer.
174 const CBlockIndex *pindexBestHeaderSent;
175 //! Length of current-streak of unconnecting headers announcements
176 int nUnconnectingHeaders;
177 //! Whether we've started headers synchronization with this peer.
178 bool fSyncStarted;
179 //! When to potentially disconnect peer for stalling headers download
180 int64_t nHeadersSyncTimeout;
181 //! Since when we're stalling block download progress (in microseconds), or 0.
182 int64_t nStallingSince;
183 std::list<QueuedBlock> vBlocksInFlight;
184 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
185 int64_t nDownloadingSince;
186 int nBlocksInFlight;
187 int nBlocksInFlightValidHeaders;
188 //! Whether we consider this a preferred download peer.
189 bool fPreferredDownload;
190 //! Whether this peer wants invs or headers (when possible) for block announcements.
191 bool fPreferHeaders;
192 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
193 bool fPreferHeaderAndIDs;
195 * Whether this peer will send us cmpctblocks if we request them.
196 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
197 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
199 bool fProvidesHeaderAndIDs;
200 //! Whether this peer can give us witnesses
201 bool fHaveWitness;
202 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
203 bool fWantsCmpctWitness;
205 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
206 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
208 bool fSupportsDesiredCmpctVersion;
210 /** State used to enforce CHAIN_SYNC_TIMEOUT
211 * Only in effect for outbound, non-manual connections, with
212 * m_protect == false
213 * Algorithm: if a peer's best known block has less work than our tip,
214 * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
215 * - If at timeout their best known block now has more work than our tip
216 * when the timeout was set, then either reset the timeout or clear it
217 * (after comparing against our current tip's work)
218 * - If at timeout their best known block still has less work than our
219 * tip did when the timeout was set, then send a getheaders message,
220 * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
221 * If their best known block is still behind when that new timeout is
222 * reached, disconnect.
224 struct ChainSyncTimeoutState {
225 //! A timeout used for checking whether our peer has sufficiently synced
226 int64_t m_timeout;
227 //! A header with the work we require on our peer's chain
228 const CBlockIndex * m_work_header;
229 //! After timeout is reached, set to true after sending getheaders
230 bool m_sent_getheaders;
231 //! Whether this peer is protected from disconnection due to a bad/slow chain
232 bool m_protect;
235 ChainSyncTimeoutState m_chain_sync;
237 //! Time of last new block announcement
238 int64_t m_last_block_announcement;
240 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
241 fCurrentlyConnected = false;
242 nMisbehavior = 0;
243 fShouldBan = false;
244 pindexBestKnownBlock = nullptr;
245 hashLastUnknownBlock.SetNull();
246 pindexLastCommonBlock = nullptr;
247 pindexBestHeaderSent = nullptr;
248 nUnconnectingHeaders = 0;
249 fSyncStarted = false;
250 nHeadersSyncTimeout = 0;
251 nStallingSince = 0;
252 nDownloadingSince = 0;
253 nBlocksInFlight = 0;
254 nBlocksInFlightValidHeaders = 0;
255 fPreferredDownload = false;
256 fPreferHeaders = false;
257 fPreferHeaderAndIDs = false;
258 fProvidesHeaderAndIDs = false;
259 fHaveWitness = false;
260 fWantsCmpctWitness = false;
261 fSupportsDesiredCmpctVersion = false;
262 m_chain_sync = { 0, nullptr, false, false };
263 m_last_block_announcement = 0;
267 /** Map maintaining per-node state. Requires cs_main. */
268 std::map<NodeId, CNodeState> mapNodeState;
270 // Requires cs_main.
271 CNodeState *State(NodeId pnode) {
272 std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
273 if (it == mapNodeState.end())
274 return nullptr;
275 return &it->second;
278 void UpdatePreferredDownload(CNode* node, CNodeState* state)
280 nPreferredDownload -= state->fPreferredDownload;
282 // Whether this node should be marked as a preferred download node.
283 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
285 nPreferredDownload += state->fPreferredDownload;
288 void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime)
290 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
291 uint64_t nonce = pnode->GetLocalNonce();
292 int nNodeStartingHeight = pnode->GetMyStartingHeight();
293 NodeId nodeid = pnode->GetId();
294 CAddress addr = pnode->addr;
296 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
297 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
299 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
300 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
302 if (fLogIPs) {
303 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);
304 } else {
305 LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
309 // Requires cs_main.
310 // Returns a bool indicating whether we requested this block.
311 // Also used if a block was /not/ received and timed out or started with another peer
312 bool MarkBlockAsReceived(const uint256& hash) {
313 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
314 if (itInFlight != mapBlocksInFlight.end()) {
315 CNodeState *state = State(itInFlight->second.first);
316 assert(state != nullptr);
317 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
318 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
319 // Last validated block on the queue was received.
320 nPeersWithValidatedDownloads--;
322 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
323 // First block on the queue was received, update the start download time for the next one
324 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
326 state->vBlocksInFlight.erase(itInFlight->second.second);
327 state->nBlocksInFlight--;
328 state->nStallingSince = 0;
329 mapBlocksInFlight.erase(itInFlight);
330 return true;
332 return false;
335 // Requires cs_main.
336 // returns false, still setting pit, if the block was already in flight from the same peer
337 // pit will only be valid as long as the same cs_main lock is being held
338 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex* pindex = nullptr, std::list<QueuedBlock>::iterator** pit = nullptr) {
339 CNodeState *state = State(nodeid);
340 assert(state != nullptr);
342 // Short-circuit most stuff in case its from the same node
343 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
344 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
345 if (pit) {
346 *pit = &itInFlight->second.second;
348 return false;
351 // Make sure it's not listed somewhere already.
352 MarkBlockAsReceived(hash);
354 std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
355 {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)});
356 state->nBlocksInFlight++;
357 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
358 if (state->nBlocksInFlight == 1) {
359 // We're starting a block download (batch) from this peer.
360 state->nDownloadingSince = GetTimeMicros();
362 if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
363 nPeersWithValidatedDownloads++;
365 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
366 if (pit)
367 *pit = &itInFlight->second.second;
368 return true;
371 /** Check whether the last unknown block a peer advertised is not yet known. */
372 void ProcessBlockAvailability(NodeId nodeid) {
373 CNodeState *state = State(nodeid);
374 assert(state != nullptr);
376 if (!state->hashLastUnknownBlock.IsNull()) {
377 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
378 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
379 if (state->pindexBestKnownBlock == nullptr || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
380 state->pindexBestKnownBlock = itOld->second;
381 state->hashLastUnknownBlock.SetNull();
386 /** Update tracking information about which blocks a peer is assumed to have. */
387 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
388 CNodeState *state = State(nodeid);
389 assert(state != nullptr);
391 ProcessBlockAvailability(nodeid);
393 BlockMap::iterator it = mapBlockIndex.find(hash);
394 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
395 // An actually better block was announced.
396 if (state->pindexBestKnownBlock == nullptr || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
397 state->pindexBestKnownBlock = it->second;
398 } else {
399 // An unknown block was announced; just assume that the latest one is the best one.
400 state->hashLastUnknownBlock = hash;
404 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) {
405 AssertLockHeld(cs_main);
406 CNodeState* nodestate = State(nodeid);
407 if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
408 // Never ask from peers who can't provide witnesses.
409 return;
411 if (nodestate->fProvidesHeaderAndIDs) {
412 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
413 if (*it == nodeid) {
414 lNodesAnnouncingHeaderAndIDs.erase(it);
415 lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
416 return;
419 connman->ForNode(nodeid, [connman](CNode* pfrom){
420 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
421 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
422 // As per BIP152, we only get 3 of our peers to announce
423 // blocks using compact encodings.
424 connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){
425 connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion));
426 return true;
428 lNodesAnnouncingHeaderAndIDs.pop_front();
430 connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion));
431 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
432 return true;
437 bool TipMayBeStale(const Consensus::Params &consensusParams)
439 AssertLockHeld(cs_main);
440 if (g_last_tip_update == 0) {
441 g_last_tip_update = GetTime();
443 return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
446 // Requires cs_main
447 bool CanDirectFetch(const Consensus::Params &consensusParams)
449 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
452 // Requires cs_main
453 bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
455 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
456 return true;
457 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
458 return true;
459 return false;
462 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
463 * at most count entries. */
464 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
465 if (count == 0)
466 return;
468 vBlocks.reserve(vBlocks.size() + count);
469 CNodeState *state = State(nodeid);
470 assert(state != nullptr);
472 // Make sure pindexBestKnownBlock is up to date, we'll need it.
473 ProcessBlockAvailability(nodeid);
475 if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
476 // This peer has nothing interesting.
477 return;
480 if (state->pindexLastCommonBlock == nullptr) {
481 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
482 // Guessing wrong in either direction is not a problem.
483 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
486 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
487 // of its current tip anymore. Go back enough to fix that.
488 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
489 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
490 return;
492 std::vector<const CBlockIndex*> vToFetch;
493 const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
494 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
495 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
496 // download that next block if the window were 1 larger.
497 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
498 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
499 NodeId waitingfor = -1;
500 while (pindexWalk->nHeight < nMaxHeight) {
501 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
502 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
503 // as iterating over ~100 CBlockIndex* entries anyway.
504 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
505 vToFetch.resize(nToFetch);
506 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
507 vToFetch[nToFetch - 1] = pindexWalk;
508 for (unsigned int i = nToFetch - 1; i > 0; i--) {
509 vToFetch[i - 1] = vToFetch[i]->pprev;
512 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
513 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
514 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
515 // already part of our chain (and therefore don't need it even if pruned).
516 for (const CBlockIndex* pindex : vToFetch) {
517 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
518 // We consider the chain that this peer is on invalid.
519 return;
521 if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
522 // We wouldn't download this block or its descendants from this peer.
523 return;
525 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
526 if (pindex->nChainTx)
527 state->pindexLastCommonBlock = pindex;
528 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
529 // The block is not already downloaded, and not yet in flight.
530 if (pindex->nHeight > nWindowEnd) {
531 // We reached the end of the window.
532 if (vBlocks.size() == 0 && waitingfor != nodeid) {
533 // We aren't able to fetch anything, but we would be if the download window was one larger.
534 nodeStaller = waitingfor;
536 return;
538 vBlocks.push_back(pindex);
539 if (vBlocks.size() == count) {
540 return;
542 } else if (waitingfor == -1) {
543 // This is the first already-in-flight block.
544 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
550 } // namespace
552 // This function is used for testing the stale tip eviction logic, see
553 // DoS_tests.cpp
554 void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds)
556 LOCK(cs_main);
557 CNodeState *state = State(node);
558 if (state) state->m_last_block_announcement = time_in_seconds;
561 // Returns true for outbound peers, excluding manual connections, feelers, and
562 // one-shots
563 bool IsOutboundDisconnectionCandidate(const CNode *node)
565 return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot);
568 void PeerLogicValidation::InitializeNode(CNode *pnode) {
569 CAddress addr = pnode->addr;
570 std::string addrName = pnode->GetAddrName();
571 NodeId nodeid = pnode->GetId();
573 LOCK(cs_main);
574 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
576 if(!pnode->fInbound)
577 PushNodeVersion(pnode, connman, GetTime());
580 void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
581 fUpdateConnectionTime = false;
582 LOCK(cs_main);
583 CNodeState *state = State(nodeid);
584 assert(state != nullptr);
586 if (state->fSyncStarted)
587 nSyncStarted--;
589 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
590 fUpdateConnectionTime = true;
593 for (const QueuedBlock& entry : state->vBlocksInFlight) {
594 mapBlocksInFlight.erase(entry.hash);
596 EraseOrphansFor(nodeid);
597 nPreferredDownload -= state->fPreferredDownload;
598 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
599 assert(nPeersWithValidatedDownloads >= 0);
600 g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect;
601 assert(g_outbound_peers_with_protect_from_disconnect >= 0);
603 mapNodeState.erase(nodeid);
605 if (mapNodeState.empty()) {
606 // Do a consistency check after the last peer is removed.
607 assert(mapBlocksInFlight.empty());
608 assert(nPreferredDownload == 0);
609 assert(nPeersWithValidatedDownloads == 0);
610 assert(g_outbound_peers_with_protect_from_disconnect == 0);
612 LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid);
615 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
616 LOCK(cs_main);
617 CNodeState *state = State(nodeid);
618 if (state == nullptr)
619 return false;
620 stats.nMisbehavior = state->nMisbehavior;
621 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
622 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
623 for (const QueuedBlock& queue : state->vBlocksInFlight) {
624 if (queue.pindex)
625 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
627 return true;
630 //////////////////////////////////////////////////////////////////////////////
632 // mapOrphanTransactions
635 void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
637 size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
638 if (max_extra_txn <= 0)
639 return;
640 if (!vExtraTxnForCompact.size())
641 vExtraTxnForCompact.resize(max_extra_txn);
642 vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
643 vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
646 bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
648 const uint256& hash = tx->GetHash();
649 if (mapOrphanTransactions.count(hash))
650 return false;
652 // Ignore big transactions, to avoid a
653 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
654 // large transaction with a missing parent then we assume
655 // it will rebroadcast it later, after the parent transaction(s)
656 // have been mined or received.
657 // 100 orphans, each of which is at most 99,999 bytes big is
658 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
659 unsigned int sz = GetTransactionWeight(*tx);
660 if (sz >= MAX_STANDARD_TX_WEIGHT)
662 LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
663 return false;
666 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
667 assert(ret.second);
668 for (const CTxIn& txin : tx->vin) {
669 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
672 AddToCompactExtraTransactions(tx);
674 LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
675 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
676 return true;
679 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans)
681 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
682 if (it == mapOrphanTransactions.end())
683 return 0;
684 for (const CTxIn& txin : it->second.tx->vin)
686 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
687 if (itPrev == mapOrphanTransactionsByPrev.end())
688 continue;
689 itPrev->second.erase(it);
690 if (itPrev->second.empty())
691 mapOrphanTransactionsByPrev.erase(itPrev);
693 mapOrphanTransactions.erase(it);
694 return 1;
697 void EraseOrphansFor(NodeId peer)
699 LOCK(g_cs_orphans);
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)
716 LOCK(g_cs_orphans);
718 unsigned int nEvicted = 0;
719 static int64_t nNextSweep;
720 int64_t nNow = GetTime();
721 if (nNextSweep <= nNow) {
722 // Sweep out expired orphan pool entries:
723 int nErased = 0;
724 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
725 std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
726 while (iter != mapOrphanTransactions.end())
728 std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
729 if (maybeErase->second.nTimeExpire <= nNow) {
730 nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
731 } else {
732 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
735 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
736 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
737 if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
739 while (mapOrphanTransactions.size() > nMaxOrphans)
741 // Evict a random orphan:
742 uint256 randomhash = GetRandHash();
743 std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
744 if (it == mapOrphanTransactions.end())
745 it = mapOrphanTransactions.begin();
746 EraseOrphanTx(it->first);
747 ++nEvicted;
749 return nEvicted;
752 // Requires cs_main.
753 void Misbehaving(NodeId pnode, int howmuch)
755 if (howmuch == 0)
756 return;
758 CNodeState *state = State(pnode);
759 if (state == nullptr)
760 return;
762 state->nMisbehavior += howmuch;
763 int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
764 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
766 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
767 state->fShouldBan = true;
768 } else
769 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
779 //////////////////////////////////////////////////////////////////////////////
781 // blockchain -> download logic notification
784 // To prevent fingerprinting attacks, only send blocks/headers outside of the
785 // active chain if they are no more than a month older (both in time, and in
786 // best equivalent proof of work) than the best header chain we know about and
787 // we fully-validated them at some point.
788 static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams)
790 AssertLockHeld(cs_main);
791 if (chainActive.Contains(pindex)) return true;
792 return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) &&
793 (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) &&
794 (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
797 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler) : connman(connmanIn), m_stale_tip_check_time(0) {
798 // Initialize global variables that cannot be constructed at startup.
799 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
801 const Consensus::Params& consensusParams = Params().GetConsensus();
802 // Stale tip checking and peer eviction are on two different timers, but we
803 // don't want them to get out of sync due to drift in the scheduler, so we
804 // combine them in one function and schedule at the quicker (peer-eviction)
805 // timer.
806 static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer");
807 scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000);
810 void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
811 LOCK(g_cs_orphans);
813 std::vector<uint256> vOrphanErase;
815 for (const CTransactionRef& ptx : pblock->vtx) {
816 const CTransaction& tx = *ptx;
818 // Which orphan pool entries must we evict?
819 for (const auto& txin : tx.vin) {
820 auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
821 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
822 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
823 const CTransaction& orphanTx = *(*mi)->second.tx;
824 const uint256& orphanHash = orphanTx.GetHash();
825 vOrphanErase.push_back(orphanHash);
830 // Erase orphan transactions include or precluded by this block
831 if (vOrphanErase.size()) {
832 int nErased = 0;
833 for (uint256 &orphanHash : vOrphanErase) {
834 nErased += EraseOrphanTx(orphanHash);
836 LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
839 g_last_tip_update = GetTime();
842 // All of the following cache a recent block, and are protected by cs_most_recent_block
843 static CCriticalSection cs_most_recent_block;
844 static std::shared_ptr<const CBlock> most_recent_block;
845 static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
846 static uint256 most_recent_block_hash;
847 static bool fWitnessesPresentInMostRecentCompactBlock;
849 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
850 std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
851 const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
853 LOCK(cs_main);
855 static int nHighestFastAnnounce = 0;
856 if (pindex->nHeight <= nHighestFastAnnounce)
857 return;
858 nHighestFastAnnounce = pindex->nHeight;
860 bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
861 uint256 hashBlock(pblock->GetHash());
864 LOCK(cs_most_recent_block);
865 most_recent_block_hash = hashBlock;
866 most_recent_block = pblock;
867 most_recent_compact_block = pcmpctblock;
868 fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
871 connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
872 // TODO: Avoid the repeated-serialization here
873 if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
874 return;
875 ProcessBlockAvailability(pnode->GetId());
876 CNodeState &state = *State(pnode->GetId());
877 // If the peer has, or we announced to them the previous block already,
878 // but we don't think they have this one, go ahead and announce it
879 if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
880 !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
882 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
883 hashBlock.ToString(), pnode->GetId());
884 connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
885 state.pindexBestHeaderSent = pindex;
890 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
891 const int nNewHeight = pindexNew->nHeight;
892 connman->SetBestHeight(nNewHeight);
894 if (!fInitialDownload) {
895 // Find the hashes of all blocks that weren't previously in the best chain.
896 std::vector<uint256> vHashes;
897 const CBlockIndex *pindexToAnnounce = pindexNew;
898 while (pindexToAnnounce != pindexFork) {
899 vHashes.push_back(pindexToAnnounce->GetBlockHash());
900 pindexToAnnounce = pindexToAnnounce->pprev;
901 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
902 // Limit announcements in case of a huge reorganization.
903 // Rely on the peer's synchronization mechanism in that case.
904 break;
907 // Relay inventory, but don't relay old inventory during initial block download.
908 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
909 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
910 for (const uint256& hash : reverse_iterate(vHashes)) {
911 pnode->PushBlockHash(hash);
915 connman->WakeMessageHandler();
918 nTimeBestReceived = GetTime();
921 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
922 LOCK(cs_main);
924 const uint256 hash(block.GetHash());
925 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
927 int nDoS = 0;
928 if (state.IsInvalid(nDoS)) {
929 // Don't send reject message with code 0 or an internal reject code.
930 if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
931 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
932 State(it->second.first)->rejects.push_back(reject);
933 if (nDoS > 0 && it->second.second)
934 Misbehaving(it->second.first, nDoS);
937 // Check that:
938 // 1. The block is valid
939 // 2. We're not in initial block download
940 // 3. This is currently the best block we're aware of. We haven't updated
941 // the tip yet so we have no way to check this directly here. Instead we
942 // just check that there are currently no other blocks in flight.
943 else if (state.IsValid() &&
944 !IsInitialBlockDownload() &&
945 mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
946 if (it != mapBlockSource.end()) {
947 MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman);
950 if (it != mapBlockSource.end())
951 mapBlockSource.erase(it);
954 //////////////////////////////////////////////////////////////////////////////
956 // Messages
960 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
962 switch (inv.type)
964 case MSG_TX:
965 case MSG_WITNESS_TX:
967 assert(recentRejects);
968 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
970 // If the chain tip has changed previously rejected transactions
971 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
972 // or a double-spend. Reset the rejects filter and give those
973 // txs a second chance.
974 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
975 recentRejects->reset();
979 LOCK(g_cs_orphans);
980 if (mapOrphanTransactions.count(inv.hash)) return true;
983 return recentRejects->contains(inv.hash) ||
984 mempool.exists(inv.hash) ||
985 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1
986 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1));
988 case MSG_BLOCK:
989 case MSG_WITNESS_BLOCK:
990 return mapBlockIndex.count(inv.hash);
992 // Don't know what it is, just say we already got one
993 return true;
996 static void RelayTransaction(const CTransaction& tx, CConnman* connman)
998 CInv inv(MSG_TX, tx.GetHash());
999 connman->ForEachNode([&inv](CNode* pnode)
1001 pnode->PushInventory(inv);
1005 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman)
1007 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
1009 // Relay to a limited number of other nodes
1010 // Use deterministic randomness to send to the same nodes for 24 hours
1011 // at a time so the addrKnowns of the chosen nodes prevent repeats
1012 uint64_t hashAddr = addr.GetHash();
1013 const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
1014 FastRandomContext insecure_rand;
1016 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
1017 assert(nRelayNodes <= best.size());
1019 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
1020 if (pnode->nVersion >= CADDR_TIME_VERSION) {
1021 uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize();
1022 for (unsigned int i = 0; i < nRelayNodes; i++) {
1023 if (hashKey > best[i].first) {
1024 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
1025 best[i] = std::make_pair(hashKey, pnode);
1026 break;
1032 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
1033 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
1034 best[i].second->PushAddress(addr, insecure_rand);
1038 connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
1041 void static ProcessGetBlockData(CNode* pfrom, const Consensus::Params& consensusParams, const CInv& inv, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1043 bool send = false;
1044 std::shared_ptr<const CBlock> a_recent_block;
1045 std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
1046 bool fWitnessesPresentInARecentCompactBlock;
1048 LOCK(cs_most_recent_block);
1049 a_recent_block = most_recent_block;
1050 a_recent_compact_block = most_recent_compact_block;
1051 fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
1054 bool need_activate_chain = false;
1056 LOCK(cs_main);
1057 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1058 if (mi != mapBlockIndex.end())
1060 if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
1061 mi->second->IsValid(BLOCK_VALID_TREE)) {
1062 // If we have the block and all of its parents, but have not yet validated it,
1063 // we might be in the middle of connecting it (ie in the unlock of cs_main
1064 // before ActivateBestChain but after AcceptBlock).
1065 // In this case, we need to run ActivateBestChain prior to checking the relay
1066 // conditions below.
1067 need_activate_chain = true;
1070 } // release cs_main before calling ActivateBestChain
1071 if (need_activate_chain) {
1072 CValidationState dummy;
1073 ActivateBestChain(dummy, Params(), a_recent_block);
1076 LOCK(cs_main);
1077 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
1078 if (mi != mapBlockIndex.end()) {
1079 send = BlockRequestAllowed(mi->second, consensusParams);
1080 if (!send) {
1081 LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
1084 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1085 // disconnect node in case we have reached the outbound limit for serving historical blocks
1086 // never disconnect whitelisted nodes
1087 if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
1089 LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
1091 //disconnect node
1092 pfrom->fDisconnect = true;
1093 send = false;
1095 // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
1096 if (send && !pfrom->fWhitelisted && (
1097 (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - mi->second->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) )
1098 )) {
1099 LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId());
1101 //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
1102 pfrom->fDisconnect = true;
1103 send = false;
1105 // Pruned nodes may have deleted the block, so check whether
1106 // it's available before trying to send.
1107 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
1109 std::shared_ptr<const CBlock> pblock;
1110 if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
1111 pblock = a_recent_block;
1112 } else {
1113 // Send block from disk
1114 std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
1115 if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
1116 assert(!"cannot load block from disk");
1117 pblock = pblockRead;
1119 if (inv.type == MSG_BLOCK)
1120 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
1121 else if (inv.type == MSG_WITNESS_BLOCK)
1122 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
1123 else if (inv.type == MSG_FILTERED_BLOCK)
1125 bool sendMerkleBlock = false;
1126 CMerkleBlock merkleBlock;
1128 LOCK(pfrom->cs_filter);
1129 if (pfrom->pfilter) {
1130 sendMerkleBlock = true;
1131 merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
1134 if (sendMerkleBlock) {
1135 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
1136 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1137 // This avoids hurting performance by pointlessly requiring a round-trip
1138 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1139 // they must either disconnect and retry or request the full block.
1140 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1141 // however we MUST always provide at least what the remote peer needs
1142 typedef std::pair<unsigned int, uint256> PairType;
1143 for (PairType& pair : merkleBlock.vMatchedTxn)
1144 connman->PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
1146 // else
1147 // no response
1149 else if (inv.type == MSG_CMPCT_BLOCK)
1151 // If a peer is asking for old blocks, we're almost guaranteed
1152 // they won't have a useful mempool to match against a compact block,
1153 // and we don't feel like constructing the object for them, so
1154 // instead we respond with the full, non-compact block.
1155 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
1156 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1157 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
1158 if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
1159 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
1160 } else {
1161 CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
1162 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
1164 } else {
1165 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
1169 // Trigger the peer node to send a getblocks request for the next batch of inventory
1170 if (inv.hash == pfrom->hashContinue)
1172 // Bypass PushInventory, this must send even if redundant,
1173 // and we want it right after the last block so they don't
1174 // wait for other stuff first.
1175 std::vector<CInv> vInv;
1176 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
1177 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1178 pfrom->hashContinue.SetNull();
1183 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1185 AssertLockNotHeld(cs_main);
1187 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
1188 std::vector<CInv> vNotFound;
1189 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1191 LOCK(cs_main);
1193 while (it != pfrom->vRecvGetData.end() && (it->type == MSG_TX || it->type == MSG_WITNESS_TX)) {
1194 if (interruptMsgProc)
1195 return;
1196 // Don't bother if send buffer is too full to respond anyway
1197 if (pfrom->fPauseSend)
1198 break;
1200 const CInv &inv = *it;
1201 it++;
1203 // Send stream from relay memory
1204 bool push = false;
1205 auto mi = mapRelay.find(inv.hash);
1206 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1207 if (mi != mapRelay.end()) {
1208 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1209 push = true;
1210 } else if (pfrom->timeLastMempoolReq) {
1211 auto txinfo = mempool.info(inv.hash);
1212 // To protect privacy, do not answer getdata using the mempool when
1213 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1214 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1215 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1216 push = true;
1219 if (!push) {
1220 vNotFound.push_back(inv);
1223 // Track requests for our stuff.
1224 GetMainSignals().Inventory(inv.hash);
1226 } // release cs_main
1228 if (it != pfrom->vRecvGetData.end()) {
1229 const CInv &inv = *it;
1230 it++;
1231 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK) {
1232 ProcessGetBlockData(pfrom, consensusParams, inv, connman, interruptMsgProc);
1236 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1238 if (!vNotFound.empty()) {
1239 // Let the peer know that we didn't find what it asked for, so it doesn't
1240 // have to wait around forever. Currently only SPV clients actually care
1241 // about this message: it's needed when they are recursively walking the
1242 // dependencies of relevant unconfirmed transactions. SPV clients want to
1243 // do that because they want to know about (and store and rebroadcast and
1244 // risk analyze) the dependencies of transactions relevant to them, without
1245 // having to download the entire memory pool.
1246 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1250 uint32_t GetFetchFlags(CNode* pfrom) {
1251 uint32_t nFetchFlags = 0;
1252 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1253 nFetchFlags |= MSG_WITNESS_FLAG;
1255 return nFetchFlags;
1258 inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) {
1259 BlockTransactions resp(req);
1260 for (size_t i = 0; i < req.indexes.size(); i++) {
1261 if (req.indexes[i] >= block.vtx.size()) {
1262 LOCK(cs_main);
1263 Misbehaving(pfrom->GetId(), 100);
1264 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId());
1265 return;
1267 resp.txn[i] = block.vtx[req.indexes[i]];
1269 LOCK(cs_main);
1270 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1271 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1272 connman->PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1275 bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid)
1277 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1278 size_t nCount = headers.size();
1280 if (nCount == 0) {
1281 // Nothing interesting. Stop asking this peers for more headers.
1282 return true;
1285 bool received_new_header = false;
1286 const CBlockIndex *pindexLast = nullptr;
1288 LOCK(cs_main);
1289 CNodeState *nodestate = State(pfrom->GetId());
1291 // If this looks like it could be a block announcement (nCount <
1292 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1293 // don't connect:
1294 // - Send a getheaders message in response to try to connect the chain.
1295 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1296 // don't connect before giving DoS points
1297 // - Once a headers message is received that is valid and does connect,
1298 // nUnconnectingHeaders gets reset back to 0.
1299 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1300 nodestate->nUnconnectingHeaders++;
1301 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1302 LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1303 headers[0].GetHash().ToString(),
1304 headers[0].hashPrevBlock.ToString(),
1305 pindexBestHeader->nHeight,
1306 pfrom->GetId(), nodestate->nUnconnectingHeaders);
1307 // Set hashLastUnknownBlock for this peer, so that if we
1308 // eventually get the headers - even from a different peer -
1309 // we can use this peer to download.
1310 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
1312 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
1313 Misbehaving(pfrom->GetId(), 20);
1315 return true;
1318 uint256 hashLastBlock;
1319 for (const CBlockHeader& header : headers) {
1320 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
1321 Misbehaving(pfrom->GetId(), 20);
1322 return error("non-continuous headers sequence");
1324 hashLastBlock = header.GetHash();
1327 // If we don't have the last header, then they'll have given us
1328 // something new (if these headers are valid).
1329 if (mapBlockIndex.find(hashLastBlock) == mapBlockIndex.end()) {
1330 received_new_header = true;
1334 CValidationState state;
1335 CBlockHeader first_invalid_header;
1336 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) {
1337 int nDoS;
1338 if (state.IsInvalid(nDoS)) {
1339 LOCK(cs_main);
1340 if (nDoS > 0) {
1341 Misbehaving(pfrom->GetId(), nDoS);
1343 if (punish_duplicate_invalid && mapBlockIndex.find(first_invalid_header.GetHash()) != mapBlockIndex.end()) {
1344 // Goal: don't allow outbound peers to use up our outbound
1345 // connection slots if they are on incompatible chains.
1347 // We ask the caller to set punish_invalid appropriately based
1348 // on the peer and the method of header delivery (compact
1349 // blocks are allowed to be invalid in some circumstances,
1350 // under BIP 152).
1351 // Here, we try to detect the narrow situation that we have a
1352 // valid block header (ie it was valid at the time the header
1353 // was received, and hence stored in mapBlockIndex) but know the
1354 // block is invalid, and that a peer has announced that same
1355 // block as being on its active chain.
1356 // Disconnect the peer in such a situation.
1358 // Note: if the header that is invalid was not accepted to our
1359 // mapBlockIndex at all, that may also be grounds for
1360 // disconnecting the peer, as the chain they are on is likely
1361 // to be incompatible. However, there is a circumstance where
1362 // that does not hold: if the header's timestamp is more than
1363 // 2 hours ahead of our current time. In that case, the header
1364 // may become valid in the future, and we don't want to
1365 // disconnect a peer merely for serving us one too-far-ahead
1366 // block header, to prevent an attacker from splitting the
1367 // network by mining a block right at the 2 hour boundary.
1369 // TODO: update the DoS logic (or, rather, rewrite the
1370 // DoS-interface between validation and net_processing) so that
1371 // the interface is cleaner, and so that we disconnect on all the
1372 // reasons that a peer's headers chain is incompatible
1373 // with ours (eg block->nVersion softforks, MTP violations,
1374 // etc), and not just the duplicate-invalid case.
1375 pfrom->fDisconnect = true;
1377 return error("invalid header received");
1382 LOCK(cs_main);
1383 CNodeState *nodestate = State(pfrom->GetId());
1384 if (nodestate->nUnconnectingHeaders > 0) {
1385 LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders);
1387 nodestate->nUnconnectingHeaders = 0;
1389 assert(pindexLast);
1390 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
1392 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1393 // because it is set in UpdateBlockAvailability. Some nullptr checks
1394 // are still present, however, as belt-and-suspenders.
1396 if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) {
1397 nodestate->m_last_block_announcement = GetTime();
1400 if (nCount == MAX_HEADERS_RESULTS) {
1401 // Headers message had its maximum size; the peer may have more headers.
1402 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1403 // from there instead.
1404 LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight);
1405 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
1408 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
1409 // If this set of headers is valid and ends in a block with at least as
1410 // much work as our tip, download as much as possible.
1411 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
1412 std::vector<const CBlockIndex*> vToFetch;
1413 const CBlockIndex *pindexWalk = pindexLast;
1414 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1415 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1416 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
1417 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
1418 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
1419 // We don't have this block, and it's not yet in flight.
1420 vToFetch.push_back(pindexWalk);
1422 pindexWalk = pindexWalk->pprev;
1424 // If pindexWalk still isn't on our main chain, we're looking at a
1425 // very large reorg at a time we think we're close to caught up to
1426 // the main chain -- this shouldn't really happen. Bail out on the
1427 // direct fetch and rely on parallel download instead.
1428 if (!chainActive.Contains(pindexWalk)) {
1429 LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
1430 pindexLast->GetBlockHash().ToString(),
1431 pindexLast->nHeight);
1432 } else {
1433 std::vector<CInv> vGetData;
1434 // Download as much as possible, from earliest to latest.
1435 for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) {
1436 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
1437 // Can't download any more from this peer
1438 break;
1440 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1441 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
1442 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex);
1443 LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
1444 pindex->GetBlockHash().ToString(), pfrom->GetId());
1446 if (vGetData.size() > 1) {
1447 LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1448 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
1450 if (vGetData.size() > 0) {
1451 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1452 // In any case, we want to download using a compact block, not a regular one
1453 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
1455 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
1459 // If we're in IBD, we want outbound peers that will serve us a useful
1460 // chain. Disconnect peers that are on chains with insufficient work.
1461 if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) {
1462 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1463 // headers to fetch from this peer.
1464 if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) {
1465 // This peer has too little work on their headers chain to help
1466 // us sync -- disconnect if using an outbound slot (unless
1467 // whitelisted or addnode).
1468 // Note: We compare their tip to nMinimumChainWork (rather than
1469 // chainActive.Tip()) because we won't start block download
1470 // until we have a headers chain that has at least
1471 // nMinimumChainWork, even if a peer has a chain past our tip,
1472 // as an anti-DoS measure.
1473 if (IsOutboundDisconnectionCandidate(pfrom)) {
1474 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId());
1475 pfrom->fDisconnect = true;
1480 if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) {
1481 // If this is an outbound peer, check to see if we should protect
1482 // it from the bad/lagging chain logic.
1483 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) {
1484 LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId());
1485 nodestate->m_chain_sync.m_protect = true;
1486 ++g_outbound_peers_with_protect_from_disconnect;
1491 return true;
1494 bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc)
1496 LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
1497 if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
1499 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1500 return true;
1504 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1505 (strCommand == NetMsgType::FILTERLOAD ||
1506 strCommand == NetMsgType::FILTERADD))
1508 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1509 LOCK(cs_main);
1510 Misbehaving(pfrom->GetId(), 100);
1511 return false;
1512 } else {
1513 pfrom->fDisconnect = true;
1514 return false;
1518 if (strCommand == NetMsgType::REJECT)
1520 if (LogAcceptCategory(BCLog::NET)) {
1521 try {
1522 std::string strMsg; unsigned char ccode; std::string strReason;
1523 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
1525 std::ostringstream ss;
1526 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
1528 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
1530 uint256 hash;
1531 vRecv >> hash;
1532 ss << ": hash " << hash.ToString();
1534 LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
1535 } catch (const std::ios_base::failure&) {
1536 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1537 LogPrint(BCLog::NET, "Unparseable reject message received\n");
1542 else if (strCommand == NetMsgType::VERSION)
1544 // Each connection can only send one version message
1545 if (pfrom->nVersion != 0)
1547 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
1548 LOCK(cs_main);
1549 Misbehaving(pfrom->GetId(), 1);
1550 return false;
1553 int64_t nTime;
1554 CAddress addrMe;
1555 CAddress addrFrom;
1556 uint64_t nNonce = 1;
1557 uint64_t nServiceInt;
1558 ServiceFlags nServices;
1559 int nVersion;
1560 int nSendVersion;
1561 std::string strSubVer;
1562 std::string cleanSubVer;
1563 int nStartingHeight = -1;
1564 bool fRelay = true;
1566 vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
1567 nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
1568 nServices = ServiceFlags(nServiceInt);
1569 if (!pfrom->fInbound)
1571 connman->SetServices(pfrom->addr, nServices);
1573 if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices))
1575 LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices));
1576 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1577 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices))));
1578 pfrom->fDisconnect = true;
1579 return false;
1582 if (nServices & ((1 << 7) | (1 << 5))) {
1583 if (GetTime() < 1533096000) {
1584 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1585 // These bits have been used as a flag to indicate that a node is running incompatible
1586 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1587 // based on these service bits, at least for a while.
1588 pfrom->fDisconnect = true;
1589 return false;
1593 if (nVersion < MIN_PEER_PROTO_VERSION)
1595 // disconnect from peers older than this proto version
1596 LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion);
1597 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1598 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1599 pfrom->fDisconnect = true;
1600 return false;
1603 if (nVersion == 10300)
1604 nVersion = 300;
1605 if (!vRecv.empty())
1606 vRecv >> addrFrom >> nNonce;
1607 if (!vRecv.empty()) {
1608 vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
1609 cleanSubVer = SanitizeString(strSubVer);
1611 if (!vRecv.empty()) {
1612 vRecv >> nStartingHeight;
1614 if (!vRecv.empty())
1615 vRecv >> fRelay;
1616 // Disconnect if we connected to ourself
1617 if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce))
1619 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1620 pfrom->fDisconnect = true;
1621 return true;
1624 if (pfrom->fInbound && addrMe.IsRoutable())
1626 SeenLocal(addrMe);
1629 // Be shy and don't send version until we hear
1630 if (pfrom->fInbound)
1631 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1633 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1635 pfrom->nServices = nServices;
1636 pfrom->SetAddrLocal(addrMe);
1638 LOCK(pfrom->cs_SubVer);
1639 pfrom->strSubVer = strSubVer;
1640 pfrom->cleanSubVer = cleanSubVer;
1642 pfrom->nStartingHeight = nStartingHeight;
1643 pfrom->fClient = !(nServices & NODE_NETWORK);
1645 LOCK(pfrom->cs_filter);
1646 pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
1649 // Change version
1650 pfrom->SetSendVersion(nSendVersion);
1651 pfrom->nVersion = nVersion;
1653 if((nServices & NODE_WITNESS))
1655 LOCK(cs_main);
1656 State(pfrom->GetId())->fHaveWitness = true;
1659 // Potentially mark this peer as a preferred download peer.
1661 LOCK(cs_main);
1662 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1665 if (!pfrom->fInbound)
1667 // Advertise our address
1668 if (fListen && !IsInitialBlockDownload())
1670 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1671 FastRandomContext insecure_rand;
1672 if (addr.IsRoutable())
1674 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1675 pfrom->PushAddress(addr, insecure_rand);
1676 } else if (IsPeerAddrLocalGood(pfrom)) {
1677 addr.SetIP(addrMe);
1678 LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
1679 pfrom->PushAddress(addr, insecure_rand);
1683 // Get recent addresses
1684 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000)
1686 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1687 pfrom->fGetAddr = true;
1689 connman->MarkAddressGood(pfrom->addr);
1692 std::string remoteAddr;
1693 if (fLogIPs)
1694 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1696 LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1697 cleanSubVer, pfrom->nVersion,
1698 pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(),
1699 remoteAddr);
1701 int64_t nTimeOffset = nTime - GetTime();
1702 pfrom->nTimeOffset = nTimeOffset;
1703 AddTimeData(pfrom->addr, nTimeOffset);
1705 // If the peer is old enough to have the old alert system, send it the final alert.
1706 if (pfrom->nVersion <= 70012) {
1707 CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
1708 connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
1711 // Feeler connections exist only to verify if address is online.
1712 if (pfrom->fFeeler) {
1713 assert(pfrom->fInbound == false);
1714 pfrom->fDisconnect = true;
1716 return true;
1720 else if (pfrom->nVersion == 0)
1722 // Must have a version message before anything else
1723 LOCK(cs_main);
1724 Misbehaving(pfrom->GetId(), 1);
1725 return false;
1728 // At this point, the outgoing message serialization version can't change.
1729 const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1731 if (strCommand == NetMsgType::VERACK)
1733 pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
1735 if (!pfrom->fInbound) {
1736 // Mark this node as currently connected, so we update its timestamp later.
1737 LOCK(cs_main);
1738 State(pfrom->GetId())->fCurrentlyConnected = true;
1739 LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n",
1740 pfrom->nVersion.load(), pfrom->nStartingHeight, pfrom->GetId(),
1741 (fLogIPs ? strprintf(", peeraddr=%s", pfrom->addr.ToString()) : ""));
1744 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1745 // Tell our peer we prefer to receive headers rather than inv's
1746 // We send this to non-NODE NETWORK peers as well, because even
1747 // non-NODE NETWORK peers can announce blocks (such as pruning
1748 // nodes)
1749 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1751 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1752 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1753 // However, we do not request new block announcements using
1754 // cmpctblock messages.
1755 // We send this to non-NODE NETWORK peers as well, because
1756 // they may wish to request compact blocks from us
1757 bool fAnnounceUsingCMPCTBLOCK = false;
1758 uint64_t nCMPCTBLOCKVersion = 2;
1759 if (pfrom->GetLocalServices() & NODE_WITNESS)
1760 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1761 nCMPCTBLOCKVersion = 1;
1762 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1764 pfrom->fSuccessfullyConnected = true;
1767 else if (!pfrom->fSuccessfullyConnected)
1769 // Must have a verack message before anything else
1770 LOCK(cs_main);
1771 Misbehaving(pfrom->GetId(), 1);
1772 return false;
1775 else if (strCommand == NetMsgType::ADDR)
1777 std::vector<CAddress> vAddr;
1778 vRecv >> vAddr;
1780 // Don't want addr from older versions unless seeding
1781 if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000)
1782 return true;
1783 if (vAddr.size() > 1000)
1785 LOCK(cs_main);
1786 Misbehaving(pfrom->GetId(), 20);
1787 return error("message addr size() = %u", vAddr.size());
1790 // Store the new addresses
1791 std::vector<CAddress> vAddrOk;
1792 int64_t nNow = GetAdjustedTime();
1793 int64_t nSince = nNow - 10 * 60;
1794 for (CAddress& addr : vAddr)
1796 if (interruptMsgProc)
1797 return true;
1799 // We only bother storing full nodes, though this may include
1800 // things which we would not make an outbound connection to, in
1801 // part because we may make feeler connections to them.
1802 if (!MayHaveUsefulAddressDB(addr.nServices))
1803 continue;
1805 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1806 addr.nTime = nNow - 5 * 24 * 60 * 60;
1807 pfrom->AddAddressKnown(addr);
1808 bool fReachable = IsReachable(addr);
1809 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1811 // Relay to a limited number of other nodes
1812 RelayAddress(addr, fReachable, connman);
1814 // Do not store addresses outside our network
1815 if (fReachable)
1816 vAddrOk.push_back(addr);
1818 connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1819 if (vAddr.size() < 1000)
1820 pfrom->fGetAddr = false;
1821 if (pfrom->fOneShot)
1822 pfrom->fDisconnect = true;
1825 else if (strCommand == NetMsgType::SENDHEADERS)
1827 LOCK(cs_main);
1828 State(pfrom->GetId())->fPreferHeaders = true;
1831 else if (strCommand == NetMsgType::SENDCMPCT)
1833 bool fAnnounceUsingCMPCTBLOCK = false;
1834 uint64_t nCMPCTBLOCKVersion = 0;
1835 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1836 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1837 LOCK(cs_main);
1838 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1839 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1840 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1841 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1843 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1844 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1845 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1846 if (pfrom->GetLocalServices() & NODE_WITNESS)
1847 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1848 else
1849 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1855 else if (strCommand == NetMsgType::INV)
1857 std::vector<CInv> vInv;
1858 vRecv >> vInv;
1859 if (vInv.size() > MAX_INV_SZ)
1861 LOCK(cs_main);
1862 Misbehaving(pfrom->GetId(), 20);
1863 return error("message inv size() = %u", vInv.size());
1866 bool fBlocksOnly = !fRelayTxes;
1868 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1869 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1870 fBlocksOnly = false;
1872 LOCK(cs_main);
1874 uint32_t nFetchFlags = GetFetchFlags(pfrom);
1876 for (CInv &inv : vInv)
1878 if (interruptMsgProc)
1879 return true;
1881 bool fAlreadyHave = AlreadyHave(inv);
1882 LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId());
1884 if (inv.type == MSG_TX) {
1885 inv.type |= nFetchFlags;
1888 if (inv.type == MSG_BLOCK) {
1889 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1890 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1891 // We used to request the full block here, but since headers-announcements are now the
1892 // primary method of announcement on the network, and since, in the case that a node
1893 // fell back to inv we probably have a reorg which we should get the headers for first,
1894 // we now only provide a getheaders response here. When we receive the headers, we will
1895 // then ask for the blocks we need.
1896 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1897 LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId());
1900 else
1902 pfrom->AddInventoryKnown(inv);
1903 if (fBlocksOnly) {
1904 LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
1905 } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
1906 pfrom->AskFor(inv);
1910 // Track requests for our stuff
1911 GetMainSignals().Inventory(inv.hash);
1916 else if (strCommand == NetMsgType::GETDATA)
1918 std::vector<CInv> vInv;
1919 vRecv >> vInv;
1920 if (vInv.size() > MAX_INV_SZ)
1922 LOCK(cs_main);
1923 Misbehaving(pfrom->GetId(), 20);
1924 return error("message getdata size() = %u", vInv.size());
1927 LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId());
1929 if (vInv.size() > 0) {
1930 LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId());
1933 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1934 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
1938 else if (strCommand == NetMsgType::GETBLOCKS)
1940 CBlockLocator locator;
1941 uint256 hashStop;
1942 vRecv >> locator >> hashStop;
1944 // We might have announced the currently-being-connected tip using a
1945 // compact block, which resulted in the peer sending a getblocks
1946 // request, which we would otherwise respond to without the new block.
1947 // To avoid this situation we simply verify that we are on our best
1948 // known chain now. This is super overkill, but we handle it better
1949 // for getheaders requests, and there are no known nodes which support
1950 // compact blocks but still use getblocks to request blocks.
1952 std::shared_ptr<const CBlock> a_recent_block;
1954 LOCK(cs_most_recent_block);
1955 a_recent_block = most_recent_block;
1957 CValidationState dummy;
1958 ActivateBestChain(dummy, Params(), a_recent_block);
1961 LOCK(cs_main);
1963 // Find the last block the caller has in the main chain
1964 const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1966 // Send the rest of the chain
1967 if (pindex)
1968 pindex = chainActive.Next(pindex);
1969 int nLimit = 500;
1970 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());
1971 for (; pindex; pindex = chainActive.Next(pindex))
1973 if (pindex->GetBlockHash() == hashStop)
1975 LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1976 break;
1978 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1979 // for some reasonable time window (1 hour) that block relay might require.
1980 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1981 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1983 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1984 break;
1986 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1987 if (--nLimit <= 0)
1989 // When this block is requested, we'll send an inv that'll
1990 // trigger the peer to getblocks the next batch of inventory.
1991 LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1992 pfrom->hashContinue = pindex->GetBlockHash();
1993 break;
1999 else if (strCommand == NetMsgType::GETBLOCKTXN)
2001 BlockTransactionsRequest req;
2002 vRecv >> req;
2004 std::shared_ptr<const CBlock> recent_block;
2006 LOCK(cs_most_recent_block);
2007 if (most_recent_block_hash == req.blockhash)
2008 recent_block = most_recent_block;
2009 // Unlock cs_most_recent_block to avoid cs_main lock inversion
2011 if (recent_block) {
2012 SendBlockTransactions(*recent_block, req, pfrom, connman);
2013 return true;
2016 LOCK(cs_main);
2018 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
2019 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
2020 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have", pfrom->GetId());
2021 return true;
2024 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
2025 // If an older block is requested (should never happen in practice,
2026 // but can happen in tests) send a block response instead of a
2027 // blocktxn response. Sending a full block response instead of a
2028 // small blocktxn response is preferable in the case where a peer
2029 // might maliciously send lots of getblocktxn requests to trigger
2030 // expensive disk reads, because it will require the peer to
2031 // actually receive all the data read from disk over the network.
2032 LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->GetId(), MAX_BLOCKTXN_DEPTH);
2033 CInv inv;
2034 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
2035 inv.hash = req.blockhash;
2036 pfrom->vRecvGetData.push_back(inv);
2037 // The message processing loop will go around again (without pausing) and we'll respond then (without cs_main)
2038 return true;
2041 CBlock block;
2042 bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
2043 assert(ret);
2045 SendBlockTransactions(block, req, pfrom, connman);
2049 else if (strCommand == NetMsgType::GETHEADERS)
2051 CBlockLocator locator;
2052 uint256 hashStop;
2053 vRecv >> locator >> hashStop;
2055 LOCK(cs_main);
2056 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
2057 LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId());
2058 return true;
2061 CNodeState *nodestate = State(pfrom->GetId());
2062 const CBlockIndex* pindex = nullptr;
2063 if (locator.IsNull())
2065 // If locator is null, return the hashStop block
2066 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
2067 if (mi == mapBlockIndex.end())
2068 return true;
2069 pindex = (*mi).second;
2071 if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) {
2072 LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId());
2073 return true;
2076 else
2078 // Find the last block the caller has in the main chain
2079 pindex = FindForkInGlobalIndex(chainActive, locator);
2080 if (pindex)
2081 pindex = chainActive.Next(pindex);
2084 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2085 std::vector<CBlock> vHeaders;
2086 int nLimit = MAX_HEADERS_RESULTS;
2087 LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId());
2088 for (; pindex; pindex = chainActive.Next(pindex))
2090 vHeaders.push_back(pindex->GetBlockHeader());
2091 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2092 break;
2094 // pindex can be nullptr either if we sent chainActive.Tip() OR
2095 // if our peer has chainActive.Tip() (and thus we are sending an empty
2096 // headers message). In both cases it's safe to update
2097 // pindexBestHeaderSent to be our tip.
2099 // It is important that we simply reset the BestHeaderSent value here,
2100 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2101 // the currently-being-connected tip using a compact block, which
2102 // resulted in the peer sending a headers request, which we respond to
2103 // without the new block. By resetting the BestHeaderSent, we ensure we
2104 // will re-announce the new block via headers (or compact blocks again)
2105 // in the SendMessages logic.
2106 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
2107 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2111 else if (strCommand == NetMsgType::TX)
2113 // Stop processing the transaction early if
2114 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2115 if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
2117 LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId());
2118 return true;
2121 std::deque<COutPoint> vWorkQueue;
2122 std::vector<uint256> vEraseQueue;
2123 CTransactionRef ptx;
2124 vRecv >> ptx;
2125 const CTransaction& tx = *ptx;
2127 CInv inv(MSG_TX, tx.GetHash());
2128 pfrom->AddInventoryKnown(inv);
2130 LOCK2(cs_main, g_cs_orphans);
2132 bool fMissingInputs = false;
2133 CValidationState state;
2135 pfrom->setAskFor.erase(inv.hash);
2136 mapAlreadyAskedFor.erase(inv.hash);
2138 std::list<CTransactionRef> lRemovedTxn;
2140 if (!AlreadyHave(inv) &&
2141 AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2142 mempool.check(pcoinsTip.get());
2143 RelayTransaction(tx, connman);
2144 for (unsigned int i = 0; i < tx.vout.size(); i++) {
2145 vWorkQueue.emplace_back(inv.hash, i);
2148 pfrom->nLastTXTime = GetTime();
2150 LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2151 pfrom->GetId(),
2152 tx.GetHash().ToString(),
2153 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
2155 // Recursively process any orphan transactions that depended on this one
2156 std::set<NodeId> setMisbehaving;
2157 while (!vWorkQueue.empty()) {
2158 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
2159 vWorkQueue.pop_front();
2160 if (itByPrev == mapOrphanTransactionsByPrev.end())
2161 continue;
2162 for (auto mi = itByPrev->second.begin();
2163 mi != itByPrev->second.end();
2164 ++mi)
2166 const CTransactionRef& porphanTx = (*mi)->second.tx;
2167 const CTransaction& orphanTx = *porphanTx;
2168 const uint256& orphanHash = orphanTx.GetHash();
2169 NodeId fromPeer = (*mi)->second.fromPeer;
2170 bool fMissingInputs2 = false;
2171 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2172 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2173 // anyone relaying LegitTxX banned)
2174 CValidationState stateDummy;
2177 if (setMisbehaving.count(fromPeer))
2178 continue;
2179 if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2180 LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
2181 RelayTransaction(orphanTx, connman);
2182 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
2183 vWorkQueue.emplace_back(orphanHash, i);
2185 vEraseQueue.push_back(orphanHash);
2187 else if (!fMissingInputs2)
2189 int nDos = 0;
2190 if (stateDummy.IsInvalid(nDos) && nDos > 0)
2192 // Punish peer that gave us an invalid orphan tx
2193 Misbehaving(fromPeer, nDos);
2194 setMisbehaving.insert(fromPeer);
2195 LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
2197 // Has inputs but not accepted to mempool
2198 // Probably non-standard or insufficient fee
2199 LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
2200 vEraseQueue.push_back(orphanHash);
2201 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
2202 // Do not use rejection cache for witness transactions or
2203 // witness-stripped transactions, as they can have been malleated.
2204 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2205 assert(recentRejects);
2206 recentRejects->insert(orphanHash);
2209 mempool.check(pcoinsTip.get());
2213 for (uint256 hash : vEraseQueue)
2214 EraseOrphanTx(hash);
2216 else if (fMissingInputs)
2218 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
2219 for (const CTxIn& txin : tx.vin) {
2220 if (recentRejects->contains(txin.prevout.hash)) {
2221 fRejectedParents = true;
2222 break;
2225 if (!fRejectedParents) {
2226 uint32_t nFetchFlags = GetFetchFlags(pfrom);
2227 for (const CTxIn& txin : tx.vin) {
2228 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
2229 pfrom->AddInventoryKnown(_inv);
2230 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
2232 AddOrphanTx(ptx, pfrom->GetId());
2234 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2235 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
2236 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
2237 if (nEvicted > 0) {
2238 LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
2240 } else {
2241 LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
2242 // We will continue to reject this tx since it has rejected
2243 // parents so avoid re-requesting it from other peers.
2244 recentRejects->insert(tx.GetHash());
2246 } else {
2247 if (!tx.HasWitness() && !state.CorruptionPossible()) {
2248 // Do not use rejection cache for witness transactions or
2249 // witness-stripped transactions, as they can have been malleated.
2250 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2251 assert(recentRejects);
2252 recentRejects->insert(tx.GetHash());
2253 if (RecursiveDynamicUsage(*ptx) < 100000) {
2254 AddToCompactExtraTransactions(ptx);
2256 } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
2257 AddToCompactExtraTransactions(ptx);
2260 if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
2261 // Always relay transactions received from whitelisted peers, even
2262 // if they were already in the mempool or rejected from it due
2263 // to policy, allowing the node to function as a gateway for
2264 // nodes hidden behind it.
2266 // Never relay transactions that we would assign a non-zero DoS
2267 // score for, as we expect peers to do the same with us in that
2268 // case.
2269 int nDoS = 0;
2270 if (!state.IsInvalid(nDoS) || nDoS == 0) {
2271 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId());
2272 RelayTransaction(tx, connman);
2273 } else {
2274 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state));
2279 for (const CTransactionRef& removedTx : lRemovedTxn)
2280 AddToCompactExtraTransactions(removedTx);
2282 int nDoS = 0;
2283 if (state.IsInvalid(nDoS))
2285 LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
2286 pfrom->GetId(),
2287 FormatStateMessage(state));
2288 if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
2289 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
2290 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
2291 if (nDoS > 0) {
2292 Misbehaving(pfrom->GetId(), nDoS);
2298 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2300 CBlockHeaderAndShortTxIDs cmpctblock;
2301 vRecv >> cmpctblock;
2303 bool received_new_header = false;
2306 LOCK(cs_main);
2308 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
2309 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2310 if (!IsInitialBlockDownload())
2311 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
2312 return true;
2315 if (mapBlockIndex.find(cmpctblock.header.GetHash()) == mapBlockIndex.end()) {
2316 received_new_header = true;
2320 const CBlockIndex *pindex = nullptr;
2321 CValidationState state;
2322 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
2323 int nDoS;
2324 if (state.IsInvalid(nDoS)) {
2325 if (nDoS > 0) {
2326 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2327 LOCK(cs_main);
2328 Misbehaving(pfrom->GetId(), nDoS);
2329 } else {
2330 LogPrint(BCLog::NET, "Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId());
2332 return true;
2336 // When we succeed in decoding a block's txids from a cmpctblock
2337 // message we typically jump to the BLOCKTXN handling code, with a
2338 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2339 // completing processing of the putative block (without cs_main).
2340 bool fProcessBLOCKTXN = false;
2341 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
2343 // If we end up treating this as a plain headers message, call that as well
2344 // without cs_main.
2345 bool fRevertToHeaderProcessing = false;
2347 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2348 // below)
2349 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2350 bool fBlockReconstructed = false;
2353 LOCK2(cs_main, g_cs_orphans);
2354 // If AcceptBlockHeader returned true, it set pindex
2355 assert(pindex);
2356 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
2358 CNodeState *nodestate = State(pfrom->GetId());
2360 // If this was a new header with more work than our tip, update the
2361 // peer's last block announcement time
2362 if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) {
2363 nodestate->m_last_block_announcement = GetTime();
2366 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
2367 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
2369 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
2370 return true;
2372 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
2373 pindex->nTx != 0) { // We had this block at some point, but pruned it
2374 if (fAlreadyInFlight) {
2375 // We requested this block for some reason, but our mempool will probably be useless
2376 // so we just grab the block via normal getdata
2377 std::vector<CInv> vInv(1);
2378 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2379 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2381 return true;
2384 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2385 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
2386 return true;
2388 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
2389 // Don't bother trying to process compact blocks from v1 peers
2390 // after segwit activates.
2391 return true;
2394 // We want to be a bit conservative just to be extra careful about DoS
2395 // possibilities in compact block processing...
2396 if (pindex->nHeight <= chainActive.Height() + 2) {
2397 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
2398 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
2399 std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
2400 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
2401 if (!(*queuedBlockIt)->partialBlock)
2402 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
2403 else {
2404 // The block was already in flight using compact blocks from the same peer
2405 LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
2406 return true;
2410 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
2411 ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
2412 if (status == READ_STATUS_INVALID) {
2413 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
2414 Misbehaving(pfrom->GetId(), 100);
2415 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->GetId());
2416 return true;
2417 } else if (status == READ_STATUS_FAILED) {
2418 // Duplicate txindexes, the block is now in-flight, so just request it
2419 std::vector<CInv> vInv(1);
2420 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2421 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2422 return true;
2425 BlockTransactionsRequest req;
2426 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
2427 if (!partialBlock.IsTxAvailable(i))
2428 req.indexes.push_back(i);
2430 if (req.indexes.empty()) {
2431 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2432 BlockTransactions txn;
2433 txn.blockhash = cmpctblock.header.GetHash();
2434 blockTxnMsg << txn;
2435 fProcessBLOCKTXN = true;
2436 } else {
2437 req.blockhash = pindex->GetBlockHash();
2438 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
2440 } else {
2441 // This block is either already in flight from a different
2442 // peer, or this peer has too many blocks outstanding to
2443 // download from.
2444 // Optimistically try to reconstruct anyway since we might be
2445 // able to without any round trips.
2446 PartiallyDownloadedBlock tempBlock(&mempool);
2447 ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
2448 if (status != READ_STATUS_OK) {
2449 // TODO: don't ignore failures
2450 return true;
2452 std::vector<CTransactionRef> dummy;
2453 status = tempBlock.FillBlock(*pblock, dummy);
2454 if (status == READ_STATUS_OK) {
2455 fBlockReconstructed = true;
2458 } else {
2459 if (fAlreadyInFlight) {
2460 // We requested this block, but its far into the future, so our
2461 // mempool will probably be useless - request the block normally
2462 std::vector<CInv> vInv(1);
2463 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
2464 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
2465 return true;
2466 } else {
2467 // If this was an announce-cmpctblock, we want the same treatment as a header message
2468 fRevertToHeaderProcessing = true;
2471 } // cs_main
2473 if (fProcessBLOCKTXN)
2474 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
2476 if (fRevertToHeaderProcessing) {
2477 // Headers received from HB compact block peers are permitted to be
2478 // relayed before full validation (see BIP 152), so we don't want to disconnect
2479 // the peer if the header turns out to be for an invalid block.
2480 // Note that if a peer tries to build on an invalid chain, that
2481 // will be detected and the peer will be banned.
2482 return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false);
2485 if (fBlockReconstructed) {
2486 // If we got here, we were able to optimistically reconstruct a
2487 // block that is in flight from some other peer.
2489 LOCK(cs_main);
2490 mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
2492 bool fNewBlock = false;
2493 // Setting fForceProcessing to true means that we bypass some of
2494 // our anti-DoS protections in AcceptBlock, which filters
2495 // unrequested blocks that might be trying to waste our resources
2496 // (eg disk space). Because we only try to reconstruct blocks when
2497 // we're close to caught up (via the CanDirectFetch() requirement
2498 // above, combined with the behavior of not requesting blocks until
2499 // we have a chain with at least nMinimumChainWork), and we ignore
2500 // compact blocks with less work than our tip, it is safe to treat
2501 // reconstructed compact blocks as having been requested.
2502 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2503 if (fNewBlock) {
2504 pfrom->nLastBlockTime = GetTime();
2505 } else {
2506 LOCK(cs_main);
2507 mapBlockSource.erase(pblock->GetHash());
2509 LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
2510 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
2511 // Clear download state for this block, which is in
2512 // process from some other peer. We do this after calling
2513 // ProcessNewBlock so that a malleated cmpctblock announcement
2514 // can't be used to interfere with block relay.
2515 MarkBlockAsReceived(pblock->GetHash());
2521 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
2523 BlockTransactions resp;
2524 vRecv >> resp;
2526 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2527 bool fBlockRead = false;
2529 LOCK(cs_main);
2531 std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
2532 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
2533 it->second.first != pfrom->GetId()) {
2534 LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId());
2535 return true;
2538 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
2539 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
2540 if (status == READ_STATUS_INVALID) {
2541 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
2542 Misbehaving(pfrom->GetId(), 100);
2543 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->GetId());
2544 return true;
2545 } else if (status == READ_STATUS_FAILED) {
2546 // Might have collided, fall back to getdata now :(
2547 std::vector<CInv> invs;
2548 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
2549 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
2550 } else {
2551 // Block is either okay, or possibly we received
2552 // READ_STATUS_CHECKBLOCK_FAILED.
2553 // Note that CheckBlock can only fail for one of a few reasons:
2554 // 1. bad-proof-of-work (impossible here, because we've already
2555 // accepted the header)
2556 // 2. merkleroot doesn't match the transactions given (already
2557 // caught in FillBlock with READ_STATUS_FAILED, so
2558 // impossible here)
2559 // 3. the block is otherwise invalid (eg invalid coinbase,
2560 // block is too big, too many legacy sigops, etc).
2561 // So if CheckBlock failed, #3 is the only possibility.
2562 // Under BIP 152, we don't DoS-ban unless proof of work is
2563 // invalid (we don't require all the stateless checks to have
2564 // been run). This is handled below, so just treat this as
2565 // though the block was successfully read, and rely on the
2566 // handling in ProcessNewBlock to ensure the block index is
2567 // updated, reject messages go out, etc.
2568 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
2569 fBlockRead = true;
2570 // mapBlockSource is only used for sending reject messages and DoS scores,
2571 // so the race between here and cs_main in ProcessNewBlock is fine.
2572 // BIP 152 permits peers to relay compact blocks after validating
2573 // the header only; we should not punish peers if the block turns
2574 // out to be invalid.
2575 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
2577 } // Don't hold cs_main when we call into ProcessNewBlock
2578 if (fBlockRead) {
2579 bool fNewBlock = false;
2580 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2581 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2582 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2583 // disk-space attacks), but this should be safe due to the
2584 // protections in the compact block handler -- see related comment
2585 // in compact block optimistic reconstruction handling.
2586 ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
2587 if (fNewBlock) {
2588 pfrom->nLastBlockTime = GetTime();
2589 } else {
2590 LOCK(cs_main);
2591 mapBlockSource.erase(pblock->GetHash());
2597 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
2599 std::vector<CBlockHeader> headers;
2601 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2602 unsigned int nCount = ReadCompactSize(vRecv);
2603 if (nCount > MAX_HEADERS_RESULTS) {
2604 LOCK(cs_main);
2605 Misbehaving(pfrom->GetId(), 20);
2606 return error("headers message size = %u", nCount);
2608 headers.resize(nCount);
2609 for (unsigned int n = 0; n < nCount; n++) {
2610 vRecv >> headers[n];
2611 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
2614 // Headers received via a HEADERS message should be valid, and reflect
2615 // the chain the peer is on. If we receive a known-invalid header,
2616 // disconnect the peer if it is using one of our outbound connection
2617 // slots.
2618 bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection;
2619 return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish);
2622 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2624 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2625 vRecv >> *pblock;
2627 LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId());
2629 bool forceProcessing = false;
2630 const uint256 hash(pblock->GetHash());
2632 LOCK(cs_main);
2633 // Also always process if we requested the block explicitly, as we may
2634 // need it even though it is not a candidate for a new best tip.
2635 forceProcessing |= MarkBlockAsReceived(hash);
2636 // mapBlockSource is only used for sending reject messages and DoS scores,
2637 // so the race between here and cs_main in ProcessNewBlock is fine.
2638 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2640 bool fNewBlock = false;
2641 ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
2642 if (fNewBlock) {
2643 pfrom->nLastBlockTime = GetTime();
2644 } else {
2645 LOCK(cs_main);
2646 mapBlockSource.erase(pblock->GetHash());
2651 else if (strCommand == NetMsgType::GETADDR)
2653 // This asymmetric behavior for inbound and outbound connections was introduced
2654 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2655 // to users' AddrMan and later request them by sending getaddr messages.
2656 // Making nodes which are behind NAT and can only make outgoing connections ignore
2657 // the getaddr message mitigates the attack.
2658 if (!pfrom->fInbound) {
2659 LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId());
2660 return true;
2663 // Only send one GetAddr response per connection to reduce resource waste
2664 // and discourage addr stamping of INV announcements.
2665 if (pfrom->fSentAddr) {
2666 LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId());
2667 return true;
2669 pfrom->fSentAddr = true;
2671 pfrom->vAddrToSend.clear();
2672 std::vector<CAddress> vAddr = connman->GetAddresses();
2673 FastRandomContext insecure_rand;
2674 for (const CAddress &addr : vAddr)
2675 pfrom->PushAddress(addr, insecure_rand);
2679 else if (strCommand == NetMsgType::MEMPOOL)
2681 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2683 LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2684 pfrom->fDisconnect = true;
2685 return true;
2688 if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted)
2690 LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2691 pfrom->fDisconnect = true;
2692 return true;
2695 LOCK(pfrom->cs_inventory);
2696 pfrom->fSendMempool = true;
2700 else if (strCommand == NetMsgType::PING)
2702 if (pfrom->nVersion > BIP0031_VERSION)
2704 uint64_t nonce = 0;
2705 vRecv >> nonce;
2706 // Echo the message back with the nonce. This allows for two useful features:
2708 // 1) A remote node can quickly check if the connection is operational
2709 // 2) Remote nodes can measure the latency of the network thread. If this node
2710 // is overloaded it won't respond to pings quickly and the remote node can
2711 // avoid sending us more work, like chain download requests.
2713 // The nonce stops the remote getting confused between different pings: without
2714 // it, if the remote node sends a ping once per second and this node takes 5
2715 // seconds to respond to each, the 5th ping the remote sends would appear to
2716 // return very quickly.
2717 connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2722 else if (strCommand == NetMsgType::PONG)
2724 int64_t pingUsecEnd = nTimeReceived;
2725 uint64_t nonce = 0;
2726 size_t nAvail = vRecv.in_avail();
2727 bool bPingFinished = false;
2728 std::string sProblem;
2730 if (nAvail >= sizeof(nonce)) {
2731 vRecv >> nonce;
2733 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2734 if (pfrom->nPingNonceSent != 0) {
2735 if (nonce == pfrom->nPingNonceSent) {
2736 // Matching pong received, this ping is no longer outstanding
2737 bPingFinished = true;
2738 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2739 if (pingUsecTime > 0) {
2740 // Successful ping time measurement, replace previous
2741 pfrom->nPingUsecTime = pingUsecTime;
2742 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
2743 } else {
2744 // This should never happen
2745 sProblem = "Timing mishap";
2747 } else {
2748 // Nonce mismatches are normal when pings are overlapping
2749 sProblem = "Nonce mismatch";
2750 if (nonce == 0) {
2751 // This is most likely a bug in another implementation somewhere; cancel this ping
2752 bPingFinished = true;
2753 sProblem = "Nonce zero";
2756 } else {
2757 sProblem = "Unsolicited pong without ping";
2759 } else {
2760 // This is most likely a bug in another implementation somewhere; cancel this ping
2761 bPingFinished = true;
2762 sProblem = "Short payload";
2765 if (!(sProblem.empty())) {
2766 LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2767 pfrom->GetId(),
2768 sProblem,
2769 pfrom->nPingNonceSent,
2770 nonce,
2771 nAvail);
2773 if (bPingFinished) {
2774 pfrom->nPingNonceSent = 0;
2779 else if (strCommand == NetMsgType::FILTERLOAD)
2781 CBloomFilter filter;
2782 vRecv >> filter;
2784 if (!filter.IsWithinSizeConstraints())
2786 // There is no excuse for sending a too-large filter
2787 LOCK(cs_main);
2788 Misbehaving(pfrom->GetId(), 100);
2790 else
2792 LOCK(pfrom->cs_filter);
2793 pfrom->pfilter.reset(new CBloomFilter(filter));
2794 pfrom->pfilter->UpdateEmptyFull();
2795 pfrom->fRelayTxes = true;
2800 else if (strCommand == NetMsgType::FILTERADD)
2802 std::vector<unsigned char> vData;
2803 vRecv >> vData;
2805 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2806 // and thus, the maximum size any matched object can have) in a filteradd message
2807 bool bad = false;
2808 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2809 bad = true;
2810 } else {
2811 LOCK(pfrom->cs_filter);
2812 if (pfrom->pfilter) {
2813 pfrom->pfilter->insert(vData);
2814 } else {
2815 bad = true;
2818 if (bad) {
2819 LOCK(cs_main);
2820 Misbehaving(pfrom->GetId(), 100);
2825 else if (strCommand == NetMsgType::FILTERCLEAR)
2827 LOCK(pfrom->cs_filter);
2828 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2829 pfrom->pfilter.reset(new CBloomFilter());
2831 pfrom->fRelayTxes = true;
2834 else if (strCommand == NetMsgType::FEEFILTER) {
2835 CAmount newFeeFilter = 0;
2836 vRecv >> newFeeFilter;
2837 if (MoneyRange(newFeeFilter)) {
2839 LOCK(pfrom->cs_feeFilter);
2840 pfrom->minFeeFilter = newFeeFilter;
2842 LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->GetId());
2846 else if (strCommand == NetMsgType::NOTFOUND) {
2847 // We do not care about the NOTFOUND message, but logging an Unknown Command
2848 // message would be undesirable as we transmit it ourselves.
2851 else {
2852 // Ignore unknown commands for extensibility
2853 LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId());
2858 return true;
2861 static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
2863 AssertLockHeld(cs_main);
2864 CNodeState &state = *State(pnode->GetId());
2866 for (const CBlockReject& reject : state.rejects) {
2867 connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2869 state.rejects.clear();
2871 if (state.fShouldBan) {
2872 state.fShouldBan = false;
2873 if (pnode->fWhitelisted)
2874 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
2875 else if (pnode->m_manual_connection)
2876 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->addr.ToString());
2877 else {
2878 pnode->fDisconnect = true;
2879 if (pnode->addr.IsLocal())
2880 LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
2881 else
2883 connman->Ban(pnode->addr, BanReasonNodeMisbehaving);
2886 return true;
2888 return false;
2891 bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc)
2893 const CChainParams& chainparams = Params();
2895 // Message format
2896 // (4) message start
2897 // (12) command
2898 // (4) size
2899 // (4) checksum
2900 // (x) data
2902 bool fMoreWork = false;
2904 if (!pfrom->vRecvGetData.empty())
2905 ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
2907 if (pfrom->fDisconnect)
2908 return false;
2910 // this maintains the order of responses
2911 if (!pfrom->vRecvGetData.empty()) return true;
2913 // Don't bother if send buffer is too full to respond anyway
2914 if (pfrom->fPauseSend)
2915 return false;
2917 std::list<CNetMessage> msgs;
2919 LOCK(pfrom->cs_vProcessMsg);
2920 if (pfrom->vProcessMsg.empty())
2921 return false;
2922 // Just take one message
2923 msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
2924 pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
2925 pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize();
2926 fMoreWork = !pfrom->vProcessMsg.empty();
2928 CNetMessage& msg(msgs.front());
2930 msg.SetVersion(pfrom->GetRecvVersion());
2931 // Scan for message start
2932 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2933 LogPrint(BCLog::NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId());
2934 pfrom->fDisconnect = true;
2935 return false;
2938 // Read header
2939 CMessageHeader& hdr = msg.hdr;
2940 if (!hdr.IsValid(chainparams.MessageStart()))
2942 LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId());
2943 return fMoreWork;
2945 std::string strCommand = hdr.GetCommand();
2947 // Message size
2948 unsigned int nMessageSize = hdr.nMessageSize;
2950 // Checksum
2951 CDataStream& vRecv = msg.vRecv;
2952 const uint256& hash = msg.GetMessageHash();
2953 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2955 LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2956 SanitizeString(strCommand), nMessageSize,
2957 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2958 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2959 return fMoreWork;
2962 // Process message
2963 bool fRet = false;
2966 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
2967 if (interruptMsgProc)
2968 return false;
2969 if (!pfrom->vRecvGetData.empty())
2970 fMoreWork = true;
2972 catch (const std::ios_base::failure& e)
2974 connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
2975 if (strstr(e.what(), "end of data"))
2977 // Allow exceptions from under-length message on vRecv
2978 LogPrint(BCLog::NET, "%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());
2980 else if (strstr(e.what(), "size too large"))
2982 // Allow exceptions from over-long size
2983 LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2985 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2987 // Allow exceptions from non-canonical encoding
2988 LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2990 else
2992 PrintExceptionContinue(&e, "ProcessMessages()");
2995 catch (const std::exception& e) {
2996 PrintExceptionContinue(&e, "ProcessMessages()");
2997 } catch (...) {
2998 PrintExceptionContinue(nullptr, "ProcessMessages()");
3001 if (!fRet) {
3002 LogPrint(BCLog::NET, "%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId());
3005 LOCK(cs_main);
3006 SendRejectsAndCheckIfBanned(pfrom, connman);
3008 return fMoreWork;
3011 void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds)
3013 AssertLockHeld(cs_main);
3015 CNodeState &state = *State(pto->GetId());
3016 const CNetMsgMaker msgMaker(pto->GetSendVersion());
3018 if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) {
3019 // This is an outbound peer subject to disconnection if they don't
3020 // announce a block with as much work as the current tip within
3021 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
3022 // their chain has more work than ours, we should sync to it,
3023 // unless it's invalid, in which case we should find that out and
3024 // disconnect from them elsewhere).
3025 if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) {
3026 if (state.m_chain_sync.m_timeout != 0) {
3027 state.m_chain_sync.m_timeout = 0;
3028 state.m_chain_sync.m_work_header = nullptr;
3029 state.m_chain_sync.m_sent_getheaders = false;
3031 } 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)) {
3032 // Our best block known by this peer is behind our tip, and we're either noticing
3033 // that for the first time, OR this peer was able to catch up to some earlier point
3034 // where we checked against our tip.
3035 // Either way, set a new timeout based on current tip.
3036 state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
3037 state.m_chain_sync.m_work_header = chainActive.Tip();
3038 state.m_chain_sync.m_sent_getheaders = false;
3039 } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
3040 // No evidence yet that our peer has synced to a chain with work equal to that
3041 // of our tip, when we first detected it was behind. Send a single getheaders
3042 // message to give the peer a chance to update us.
3043 if (state.m_chain_sync.m_sent_getheaders) {
3044 // They've run out of time to catch up!
3045 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>");
3046 pto->fDisconnect = true;
3047 } else {
3048 assert(state.m_chain_sync.m_work_header);
3049 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());
3050 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
3051 state.m_chain_sync.m_sent_getheaders = true;
3052 constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
3053 // Bump the timeout to allow a response, which could clear the timeout
3054 // (if the response shows the peer has synced), reset the timeout (if
3055 // the peer syncs to the required work but not to our tip), or result
3056 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3057 // has not sufficiently progressed)
3058 state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME;
3064 void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
3066 // Check whether we have too many outbound peers
3067 int extra_peers = connman->GetExtraOutboundCount();
3068 if (extra_peers > 0) {
3069 // If we have more outbound peers than we target, disconnect one.
3070 // Pick the outbound peer that least recently announced
3071 // us a new block, with ties broken by choosing the more recent
3072 // connection (higher node id)
3073 NodeId worst_peer = -1;
3074 int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
3076 LOCK(cs_main);
3078 connman->ForEachNode([&](CNode* pnode) {
3079 // Ignore non-outbound peers, or nodes marked for disconnect already
3080 if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return;
3081 CNodeState *state = State(pnode->GetId());
3082 if (state == nullptr) return; // shouldn't be possible, but just in case
3083 // Don't evict our protected peers
3084 if (state->m_chain_sync.m_protect) return;
3085 if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) {
3086 worst_peer = pnode->GetId();
3087 oldest_block_announcement = state->m_last_block_announcement;
3090 if (worst_peer != -1) {
3091 bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) {
3092 // Only disconnect a peer that has been connected to us for
3093 // some reasonable fraction of our check-frequency, to give
3094 // it time for new information to have arrived.
3095 // Also don't disconnect any peer we're trying to download a
3096 // block from.
3097 CNodeState &state = *State(pnode->GetId());
3098 if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) {
3099 LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement);
3100 pnode->fDisconnect = true;
3101 return true;
3102 } else {
3103 LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight);
3104 return false;
3107 if (disconnected) {
3108 // If we disconnected an extra peer, that means we successfully
3109 // connected to at least one peer after the last time we
3110 // detected a stale tip. Don't try any more extra peers until
3111 // we next detect a stale tip, to limit the load we put on the
3112 // network from these extra connections.
3113 connman->SetTryNewOutboundPeer(false);
3119 void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams)
3121 if (connman == nullptr) return;
3123 int64_t time_in_seconds = GetTime();
3125 EvictExtraOutboundPeers(time_in_seconds);
3127 if (time_in_seconds > m_stale_tip_check_time) {
3128 LOCK(cs_main);
3129 // Check whether our tip is stale, and if so, allow using an extra
3130 // outbound peer
3131 if (TipMayBeStale(consensusParams)) {
3132 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);
3133 connman->SetTryNewOutboundPeer(true);
3134 } else if (connman->GetTryNewOutboundPeer()) {
3135 connman->SetTryNewOutboundPeer(false);
3137 m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
3141 class CompareInvMempoolOrder
3143 CTxMemPool *mp;
3144 public:
3145 explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
3147 mp = _mempool;
3150 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
3152 /* As std::make_heap produces a max-heap, we want the entries with the
3153 * fewest ancestors/highest fee to sort later. */
3154 return mp->CompareDepthAndScore(*b, *a);
3158 bool PeerLogicValidation::SendMessages(CNode* pto, std::atomic<bool>& interruptMsgProc)
3160 const Consensus::Params& consensusParams = Params().GetConsensus();
3162 // Don't send anything until the version handshake is complete
3163 if (!pto->fSuccessfullyConnected || pto->fDisconnect)
3164 return true;
3166 // If we get here, the outgoing message serialization version is set and can't change.
3167 const CNetMsgMaker msgMaker(pto->GetSendVersion());
3170 // Message: ping
3172 bool pingSend = false;
3173 if (pto->fPingQueued) {
3174 // RPC ping request by user
3175 pingSend = true;
3177 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
3178 // Ping automatically sent as a latency probe & keepalive.
3179 pingSend = true;
3181 if (pingSend) {
3182 uint64_t nonce = 0;
3183 while (nonce == 0) {
3184 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
3186 pto->fPingQueued = false;
3187 pto->nPingUsecStart = GetTimeMicros();
3188 if (pto->nVersion > BIP0031_VERSION) {
3189 pto->nPingNonceSent = nonce;
3190 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
3191 } else {
3192 // Peer is too old to support ping command with nonce, pong will never arrive.
3193 pto->nPingNonceSent = 0;
3194 connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING));
3198 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3199 if (!lockMain)
3200 return true;
3202 if (SendRejectsAndCheckIfBanned(pto, connman))
3203 return true;
3204 CNodeState &state = *State(pto->GetId());
3206 // Address refresh broadcast
3207 int64_t nNow = GetTimeMicros();
3208 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3209 AdvertiseLocal(pto);
3210 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
3214 // Message: addr
3216 if (pto->nNextAddrSend < nNow) {
3217 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
3218 std::vector<CAddress> vAddr;
3219 vAddr.reserve(pto->vAddrToSend.size());
3220 for (const CAddress& addr : pto->vAddrToSend)
3222 if (!pto->addrKnown.contains(addr.GetKey()))
3224 pto->addrKnown.insert(addr.GetKey());
3225 vAddr.push_back(addr);
3226 // receiver rejects addr messages larger than 1000
3227 if (vAddr.size() >= 1000)
3229 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3230 vAddr.clear();
3234 pto->vAddrToSend.clear();
3235 if (!vAddr.empty())
3236 connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
3237 // we only send the big addr message once
3238 if (pto->vAddrToSend.capacity() > 40)
3239 pto->vAddrToSend.shrink_to_fit();
3242 // Start block sync
3243 if (pindexBestHeader == nullptr)
3244 pindexBestHeader = chainActive.Tip();
3245 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.
3246 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
3247 // Only actively request headers from a single peer, unless we're close to today.
3248 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3249 state.fSyncStarted = true;
3250 state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
3251 nSyncStarted++;
3252 const CBlockIndex *pindexStart = pindexBestHeader;
3253 /* If possible, start at the block preceding the currently
3254 best known header. This ensures that we always get a
3255 non-empty list of headers back as long as the peer
3256 is up-to-date. With a non-empty response, we can initialise
3257 the peer's known best block. This wouldn't be possible
3258 if we requested starting at pindexBestHeader and
3259 got back an empty response. */
3260 if (pindexStart->pprev)
3261 pindexStart = pindexStart->pprev;
3262 LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
3263 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
3267 // Resend wallet transactions that haven't gotten in a block yet
3268 // Except during reindex, importing and IBD, when old wallet
3269 // transactions become unconfirmed and spams other nodes.
3270 if (!fReindex && !fImporting && !IsInitialBlockDownload())
3272 GetMainSignals().Broadcast(nTimeBestReceived, connman);
3276 // Try sending block announcements via headers
3279 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3280 // list of block hashes we're relaying, and our peer wants
3281 // headers announcements, then find the first header
3282 // not yet known to our peer but would connect, and send.
3283 // If no header would connect, or if we have too many
3284 // blocks, or if the peer doesn't want headers, just
3285 // add all to the inv queue.
3286 LOCK(pto->cs_inventory);
3287 std::vector<CBlock> vHeaders;
3288 bool fRevertToInv = ((!state.fPreferHeaders &&
3289 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
3290 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
3291 const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery
3292 ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date
3294 if (!fRevertToInv) {
3295 bool fFoundStartingHeader = false;
3296 // Try to find first header that our peer doesn't have, and
3297 // then send all headers past that one. If we come across any
3298 // headers that aren't on chainActive, give up.
3299 for (const uint256 &hash : pto->vBlockHashesToAnnounce) {
3300 BlockMap::iterator mi = mapBlockIndex.find(hash);
3301 assert(mi != mapBlockIndex.end());
3302 const CBlockIndex *pindex = mi->second;
3303 if (chainActive[pindex->nHeight] != pindex) {
3304 // Bail out if we reorged away from this block
3305 fRevertToInv = true;
3306 break;
3308 if (pBestIndex != nullptr && pindex->pprev != pBestIndex) {
3309 // This means that the list of blocks to announce don't
3310 // connect to each other.
3311 // This shouldn't really be possible to hit during
3312 // regular operation (because reorgs should take us to
3313 // a chain that has some block not on the prior chain,
3314 // which should be caught by the prior check), but one
3315 // way this could happen is by using invalidateblock /
3316 // reconsiderblock repeatedly on the tip, causing it to
3317 // be added multiple times to vBlockHashesToAnnounce.
3318 // Robustly deal with this rare situation by reverting
3319 // to an inv.
3320 fRevertToInv = true;
3321 break;
3323 pBestIndex = pindex;
3324 if (fFoundStartingHeader) {
3325 // add this to the headers message
3326 vHeaders.push_back(pindex->GetBlockHeader());
3327 } else if (PeerHasHeader(&state, pindex)) {
3328 continue; // keep looking for the first new block
3329 } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev)) {
3330 // Peer doesn't have this header but they do have the prior one.
3331 // Start sending headers.
3332 fFoundStartingHeader = true;
3333 vHeaders.push_back(pindex->GetBlockHeader());
3334 } else {
3335 // Peer doesn't have this header or the prior one -- nothing will
3336 // connect, so bail out.
3337 fRevertToInv = true;
3338 break;
3342 if (!fRevertToInv && !vHeaders.empty()) {
3343 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
3344 // We only send up to 1 block as header-and-ids, as otherwise
3345 // probably means we're doing an initial-ish-sync or they're slow
3346 LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
3347 vHeaders.front().GetHash().ToString(), pto->GetId());
3349 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
3351 bool fGotBlockFromCache = false;
3353 LOCK(cs_most_recent_block);
3354 if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
3355 if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
3356 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
3357 else {
3358 CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
3359 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3361 fGotBlockFromCache = true;
3364 if (!fGotBlockFromCache) {
3365 CBlock block;
3366 bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
3367 assert(ret);
3368 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
3369 connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
3371 state.pindexBestHeaderSent = pBestIndex;
3372 } else if (state.fPreferHeaders) {
3373 if (vHeaders.size() > 1) {
3374 LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
3375 vHeaders.size(),
3376 vHeaders.front().GetHash().ToString(),
3377 vHeaders.back().GetHash().ToString(), pto->GetId());
3378 } else {
3379 LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
3380 vHeaders.front().GetHash().ToString(), pto->GetId());
3382 connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
3383 state.pindexBestHeaderSent = pBestIndex;
3384 } else
3385 fRevertToInv = true;
3387 if (fRevertToInv) {
3388 // If falling back to using an inv, just try to inv the tip.
3389 // The last entry in vBlockHashesToAnnounce was our tip at some point
3390 // in the past.
3391 if (!pto->vBlockHashesToAnnounce.empty()) {
3392 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
3393 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
3394 assert(mi != mapBlockIndex.end());
3395 const CBlockIndex *pindex = mi->second;
3397 // Warn if we're announcing a block that is not on the main chain.
3398 // This should be very rare and could be optimized out.
3399 // Just log for now.
3400 if (chainActive[pindex->nHeight] != pindex) {
3401 LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
3402 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
3405 // If the peer's chain has this block, don't inv it back.
3406 if (!PeerHasHeader(&state, pindex)) {
3407 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
3408 LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
3409 pto->GetId(), hashToAnnounce.ToString());
3413 pto->vBlockHashesToAnnounce.clear();
3417 // Message: inventory
3419 std::vector<CInv> vInv;
3421 LOCK(pto->cs_inventory);
3422 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
3424 // Add blocks
3425 for (const uint256& hash : pto->vInventoryBlockToSend) {
3426 vInv.push_back(CInv(MSG_BLOCK, hash));
3427 if (vInv.size() == MAX_INV_SZ) {
3428 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3429 vInv.clear();
3432 pto->vInventoryBlockToSend.clear();
3434 // Check whether periodic sends should happen
3435 bool fSendTrickle = pto->fWhitelisted;
3436 if (pto->nNextInvSend < nNow) {
3437 fSendTrickle = true;
3438 // Use half the delay for outbound peers, as there is less privacy concern for them.
3439 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
3442 // Time to send but the peer has requested we not relay transactions.
3443 if (fSendTrickle) {
3444 LOCK(pto->cs_filter);
3445 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
3448 // Respond to BIP35 mempool requests
3449 if (fSendTrickle && pto->fSendMempool) {
3450 auto vtxinfo = mempool.infoAll();
3451 pto->fSendMempool = false;
3452 CAmount filterrate = 0;
3454 LOCK(pto->cs_feeFilter);
3455 filterrate = pto->minFeeFilter;
3458 LOCK(pto->cs_filter);
3460 for (const auto& txinfo : vtxinfo) {
3461 const uint256& hash = txinfo.tx->GetHash();
3462 CInv inv(MSG_TX, hash);
3463 pto->setInventoryTxToSend.erase(hash);
3464 if (filterrate) {
3465 if (txinfo.feeRate.GetFeePerK() < filterrate)
3466 continue;
3468 if (pto->pfilter) {
3469 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3471 pto->filterInventoryKnown.insert(hash);
3472 vInv.push_back(inv);
3473 if (vInv.size() == MAX_INV_SZ) {
3474 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3475 vInv.clear();
3478 pto->timeLastMempoolReq = GetTime();
3481 // Determine transactions to relay
3482 if (fSendTrickle) {
3483 // Produce a vector with all candidates for sending
3484 std::vector<std::set<uint256>::iterator> vInvTx;
3485 vInvTx.reserve(pto->setInventoryTxToSend.size());
3486 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
3487 vInvTx.push_back(it);
3489 CAmount filterrate = 0;
3491 LOCK(pto->cs_feeFilter);
3492 filterrate = pto->minFeeFilter;
3494 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3495 // A heap is used so that not all items need sorting if only a few are being sent.
3496 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
3497 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3498 // No reason to drain out at many times the network's capacity,
3499 // especially since we have many peers and some will draw much shorter delays.
3500 unsigned int nRelayedTransactions = 0;
3501 LOCK(pto->cs_filter);
3502 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
3503 // Fetch the top element from the heap
3504 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
3505 std::set<uint256>::iterator it = vInvTx.back();
3506 vInvTx.pop_back();
3507 uint256 hash = *it;
3508 // Remove it from the to-be-sent set
3509 pto->setInventoryTxToSend.erase(it);
3510 // Check if not in the filter already
3511 if (pto->filterInventoryKnown.contains(hash)) {
3512 continue;
3514 // Not in the mempool anymore? don't bother sending it.
3515 auto txinfo = mempool.info(hash);
3516 if (!txinfo.tx) {
3517 continue;
3519 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
3520 continue;
3522 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
3523 // Send
3524 vInv.push_back(CInv(MSG_TX, hash));
3525 nRelayedTransactions++;
3527 // Expire old relay messages
3528 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
3530 mapRelay.erase(vRelayExpiration.front().second);
3531 vRelayExpiration.pop_front();
3534 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
3535 if (ret.second) {
3536 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
3539 if (vInv.size() == MAX_INV_SZ) {
3540 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3541 vInv.clear();
3543 pto->filterInventoryKnown.insert(hash);
3547 if (!vInv.empty())
3548 connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
3550 // Detect whether we're stalling
3551 nNow = GetTimeMicros();
3552 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
3553 // Stalling only triggers when the block download window cannot move. During normal steady state,
3554 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3555 // should only happen during initial block download.
3556 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId());
3557 pto->fDisconnect = true;
3558 return true;
3560 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3561 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3562 // We compensate for other peers to prevent killing off peers due to our own downstream link
3563 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3564 // to unreasonably increase our timeout.
3565 if (state.vBlocksInFlight.size() > 0) {
3566 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
3567 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
3568 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
3569 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
3570 pto->fDisconnect = true;
3571 return true;
3574 // Check for headers sync timeouts
3575 if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
3576 // Detect whether this is a stalling initial-headers-sync peer
3577 if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3578 if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
3579 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3580 // and we have others we could be using instead.
3581 // Note: If all our peers are inbound, then we won't
3582 // disconnect our sync peer for stalling; we have bigger
3583 // problems if we can't get any outbound peers.
3584 if (!pto->fWhitelisted) {
3585 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId());
3586 pto->fDisconnect = true;
3587 return true;
3588 } else {
3589 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId());
3590 // Reset the headers sync state so that we have a
3591 // chance to try downloading from a different peer.
3592 // Note: this will also result in at least one more
3593 // getheaders message to be sent to
3594 // this peer (eventually).
3595 state.fSyncStarted = false;
3596 nSyncStarted--;
3597 state.nHeadersSyncTimeout = 0;
3600 } else {
3601 // After we've caught up once, reset the timeout so we can't trigger
3602 // disconnect later.
3603 state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max();
3607 // Check that outbound peers have reasonable chains
3608 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3609 ConsiderEviction(pto, GetTime());
3612 // Message: getdata (blocks)
3614 std::vector<CInv> vGetData;
3615 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3616 std::vector<const CBlockIndex*> vToDownload;
3617 NodeId staller = -1;
3618 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
3619 for (const CBlockIndex *pindex : vToDownload) {
3620 uint32_t nFetchFlags = GetFetchFlags(pto);
3621 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
3622 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
3623 LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
3624 pindex->nHeight, pto->GetId());
3626 if (state.nBlocksInFlight == 0 && staller != -1) {
3627 if (State(staller)->nStallingSince == 0) {
3628 State(staller)->nStallingSince = nNow;
3629 LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
3635 // Message: getdata (non-blocks)
3637 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3639 const CInv& inv = (*pto->mapAskFor.begin()).second;
3640 if (!AlreadyHave(inv))
3642 LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
3643 vGetData.push_back(inv);
3644 if (vGetData.size() >= 1000)
3646 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3647 vGetData.clear();
3649 } else {
3650 //If we're not going to ask, don't expect a response.
3651 pto->setAskFor.erase(inv.hash);
3653 pto->mapAskFor.erase(pto->mapAskFor.begin());
3655 if (!vGetData.empty())
3656 connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
3659 // Message: feefilter
3661 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3662 if (pto->nVersion >= FEEFILTER_VERSION && gArgs.GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
3663 !(pto->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
3664 CAmount currentFilter = mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
3665 int64_t timeNow = GetTimeMicros();
3666 if (timeNow > pto->nextSendTimeFeeFilter) {
3667 static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
3668 static FeeFilterRounder filterRounder(default_feerate);
3669 CAmount filterToSend = filterRounder.round(currentFilter);
3670 // We always have a fee filter of at least minRelayTxFee
3671 filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
3672 if (filterToSend != pto->lastSentFeeFilter) {
3673 connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3674 pto->lastSentFeeFilter = filterToSend;
3676 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3678 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3679 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3680 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3681 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3682 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3686 return true;
3689 class CNetProcessingCleanup
3691 public:
3692 CNetProcessingCleanup() {}
3693 ~CNetProcessingCleanup() {
3694 // orphan transactions
3695 mapOrphanTransactions.clear();
3696 mapOrphanTransactionsByPrev.clear();
3698 } instance_of_cnetprocessingcleanup;