Move CTxInWitness inside CTxIn
[bitcoinplatinum.git] / src / net_processing.cpp
blob3ff5ccc18f0d553e0aa61bb85d0ed3cbd8398fa6
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "net_processing.h"
8 #include "addrman.h"
9 #include "arith_uint256.h"
10 #include "blockencodings.h"
11 #include "chainparams.h"
12 #include "consensus/validation.h"
13 #include "hash.h"
14 #include "init.h"
15 #include "validation.h"
16 #include "merkleblock.h"
17 #include "net.h"
18 #include "netmessagemaker.h"
19 #include "netbase.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "random.h"
25 #include "tinyformat.h"
26 #include "txmempool.h"
27 #include "ui_interface.h"
28 #include "util.h"
29 #include "utilmoneystr.h"
30 #include "utilstrencodings.h"
31 #include "validationinterface.h"
33 #include <boost/thread.hpp>
35 using namespace std;
37 #if defined(NDEBUG)
38 # error "Bitcoin cannot be compiled without assertions."
39 #endif
41 int64_t nTimeBestReceived = 0; // Used only to inform the wallet of when we last received a block
43 struct IteratorComparator
45 template<typename I>
46 bool operator()(const I& a, const I& b)
48 return &(*a) < &(*b);
52 struct COrphanTx {
53 CTransaction tx;
54 NodeId fromPeer;
55 int64_t nTimeExpire;
57 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
58 map<COutPoint, set<map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
59 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
61 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
63 // Internal stuff
64 namespace {
65 /** Number of nodes with fSyncStarted. */
66 int nSyncStarted = 0;
68 /**
69 * Sources of received blocks, saved to be able to send them reject
70 * messages or ban them when processing happens afterwards. Protected by
71 * cs_main.
72 * Set mapBlockSource[hash].second to false if the node should not be
73 * punished if the block is invalid.
75 map<uint256, std::pair<NodeId, bool>> mapBlockSource;
77 /**
78 * Filter for transactions that were recently rejected by
79 * AcceptToMemoryPool. These are not rerequested until the chain tip
80 * changes, at which point the entire filter is reset. Protected by
81 * cs_main.
83 * Without this filter we'd be re-requesting txs from each of our peers,
84 * increasing bandwidth consumption considerably. For instance, with 100
85 * peers, half of which relay a tx we don't accept, that might be a 50x
86 * bandwidth increase. A flooding attacker attempting to roll-over the
87 * filter using minimum-sized, 60byte, transactions might manage to send
88 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
89 * two minute window to send invs to us.
91 * Decreasing the false positive rate is fairly cheap, so we pick one in a
92 * million to make it highly unlikely for users to have issues with this
93 * filter.
95 * Memory used: 1.3 MB
97 std::unique_ptr<CRollingBloomFilter> recentRejects;
98 uint256 hashRecentRejectsChainTip;
100 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
101 struct QueuedBlock {
102 uint256 hash;
103 CBlockIndex* pindex; //!< Optional.
104 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
105 std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
107 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
109 /** Stack of nodes which we have set to announce using compact blocks */
110 list<NodeId> lNodesAnnouncingHeaderAndIDs;
112 /** Number of preferable block download peers. */
113 int nPreferredDownload = 0;
115 /** Number of peers from which we're downloading blocks. */
116 int nPeersWithValidatedDownloads = 0;
118 /** Relay map, protected by cs_main. */
119 typedef std::map<uint256, CTransactionRef> MapRelay;
120 MapRelay mapRelay;
121 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
122 std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
123 } // anon namespace
125 //////////////////////////////////////////////////////////////////////////////
127 // Registration of network node signals.
130 namespace {
132 struct CBlockReject {
133 unsigned char chRejectCode;
134 string strRejectReason;
135 uint256 hashBlock;
139 * Maintain validation-specific state about nodes, protected by cs_main, instead
140 * by CNode's own locks. This simplifies asynchronous operation, where
141 * processing of incoming data is done after the ProcessMessage call returns,
142 * and we're no longer holding the node's locks.
144 struct CNodeState {
145 //! The peer's address
146 const CService address;
147 //! Whether we have a fully established connection.
148 bool fCurrentlyConnected;
149 //! Accumulated misbehaviour score for this peer.
150 int nMisbehavior;
151 //! Whether this peer should be disconnected and banned (unless whitelisted).
152 bool fShouldBan;
153 //! String name of this peer (debugging/logging purposes).
154 const std::string name;
155 //! List of asynchronously-determined block rejections to notify this peer about.
156 std::vector<CBlockReject> rejects;
157 //! The best known block we know this peer has announced.
158 CBlockIndex *pindexBestKnownBlock;
159 //! The hash of the last unknown block this peer has announced.
160 uint256 hashLastUnknownBlock;
161 //! The last full block we both have.
162 CBlockIndex *pindexLastCommonBlock;
163 //! The best header we have sent our peer.
164 CBlockIndex *pindexBestHeaderSent;
165 //! Length of current-streak of unconnecting headers announcements
166 int nUnconnectingHeaders;
167 //! Whether we've started headers synchronization with this peer.
168 bool fSyncStarted;
169 //! Since when we're stalling block download progress (in microseconds), or 0.
170 int64_t nStallingSince;
171 list<QueuedBlock> vBlocksInFlight;
172 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
173 int64_t nDownloadingSince;
174 int nBlocksInFlight;
175 int nBlocksInFlightValidHeaders;
176 //! Whether we consider this a preferred download peer.
177 bool fPreferredDownload;
178 //! Whether this peer wants invs or headers (when possible) for block announcements.
179 bool fPreferHeaders;
180 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
181 bool fPreferHeaderAndIDs;
183 * Whether this peer will send us cmpctblocks if we request them.
184 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
185 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
187 bool fProvidesHeaderAndIDs;
188 //! Whether this peer can give us witnesses
189 bool fHaveWitness;
190 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
191 bool fWantsCmpctWitness;
193 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
194 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
196 bool fSupportsDesiredCmpctVersion;
198 CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
199 fCurrentlyConnected = false;
200 nMisbehavior = 0;
201 fShouldBan = false;
202 pindexBestKnownBlock = NULL;
203 hashLastUnknownBlock.SetNull();
204 pindexLastCommonBlock = NULL;
205 pindexBestHeaderSent = NULL;
206 nUnconnectingHeaders = 0;
207 fSyncStarted = false;
208 nStallingSince = 0;
209 nDownloadingSince = 0;
210 nBlocksInFlight = 0;
211 nBlocksInFlightValidHeaders = 0;
212 fPreferredDownload = false;
213 fPreferHeaders = false;
214 fPreferHeaderAndIDs = false;
215 fProvidesHeaderAndIDs = false;
216 fHaveWitness = false;
217 fWantsCmpctWitness = false;
218 fSupportsDesiredCmpctVersion = false;
222 /** Map maintaining per-node state. Requires cs_main. */
223 map<NodeId, CNodeState> mapNodeState;
225 // Requires cs_main.
226 CNodeState *State(NodeId pnode) {
227 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
228 if (it == mapNodeState.end())
229 return NULL;
230 return &it->second;
233 void UpdatePreferredDownload(CNode* node, CNodeState* state)
235 nPreferredDownload -= state->fPreferredDownload;
237 // Whether this node should be marked as a preferred download node.
238 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
240 nPreferredDownload += state->fPreferredDownload;
243 void PushNodeVersion(CNode *pnode, CConnman& connman, int64_t nTime)
245 ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
246 uint64_t nonce = pnode->GetLocalNonce();
247 int nNodeStartingHeight = pnode->GetMyStartingHeight();
248 NodeId nodeid = pnode->GetId();
249 CAddress addr = pnode->addr;
251 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
252 CAddress addrMe = CAddress(CService(), nLocalNodeServices);
254 connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
255 nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
257 if (fLogIPs)
258 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
259 else
260 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
263 void InitializeNode(CNode *pnode, CConnman& connman) {
264 CAddress addr = pnode->addr;
265 std::string addrName = pnode->addrName;
266 NodeId nodeid = pnode->GetId();
268 LOCK(cs_main);
269 mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
271 if(!pnode->fInbound)
272 PushNodeVersion(pnode, connman, GetTime());
275 void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
276 fUpdateConnectionTime = false;
277 LOCK(cs_main);
278 CNodeState *state = State(nodeid);
280 if (state->fSyncStarted)
281 nSyncStarted--;
283 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
284 fUpdateConnectionTime = true;
287 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
288 mapBlocksInFlight.erase(entry.hash);
290 EraseOrphansFor(nodeid);
291 nPreferredDownload -= state->fPreferredDownload;
292 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
293 assert(nPeersWithValidatedDownloads >= 0);
295 mapNodeState.erase(nodeid);
297 if (mapNodeState.empty()) {
298 // Do a consistency check after the last peer is removed.
299 assert(mapBlocksInFlight.empty());
300 assert(nPreferredDownload == 0);
301 assert(nPeersWithValidatedDownloads == 0);
305 // Requires cs_main.
306 // Returns a bool indicating whether we requested this block.
307 // Also used if a block was /not/ received and timed out or started with another peer
308 bool MarkBlockAsReceived(const uint256& hash) {
309 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
310 if (itInFlight != mapBlocksInFlight.end()) {
311 CNodeState *state = State(itInFlight->second.first);
312 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
313 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
314 // Last validated block on the queue was received.
315 nPeersWithValidatedDownloads--;
317 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
318 // First block on the queue was received, update the start download time for the next one
319 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
321 state->vBlocksInFlight.erase(itInFlight->second.second);
322 state->nBlocksInFlight--;
323 state->nStallingSince = 0;
324 mapBlocksInFlight.erase(itInFlight);
325 return true;
327 return false;
330 // Requires cs_main.
331 // returns false, still setting pit, if the block was already in flight from the same peer
332 // pit will only be valid as long as the same cs_main lock is being held
333 bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL, list<QueuedBlock>::iterator **pit = NULL) {
334 CNodeState *state = State(nodeid);
335 assert(state != NULL);
337 // Short-circuit most stuff in case its from the same node
338 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
339 if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
340 *pit = &itInFlight->second.second;
341 return false;
344 // Make sure it's not listed somewhere already.
345 MarkBlockAsReceived(hash);
347 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
348 {hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)});
349 state->nBlocksInFlight++;
350 state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
351 if (state->nBlocksInFlight == 1) {
352 // We're starting a block download (batch) from this peer.
353 state->nDownloadingSince = GetTimeMicros();
355 if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
356 nPeersWithValidatedDownloads++;
358 itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
359 if (pit)
360 *pit = &itInFlight->second.second;
361 return true;
364 /** Check whether the last unknown block a peer advertised is not yet known. */
365 void ProcessBlockAvailability(NodeId nodeid) {
366 CNodeState *state = State(nodeid);
367 assert(state != NULL);
369 if (!state->hashLastUnknownBlock.IsNull()) {
370 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
371 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
372 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
373 state->pindexBestKnownBlock = itOld->second;
374 state->hashLastUnknownBlock.SetNull();
379 /** Update tracking information about which blocks a peer is assumed to have. */
380 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
381 CNodeState *state = State(nodeid);
382 assert(state != NULL);
384 ProcessBlockAvailability(nodeid);
386 BlockMap::iterator it = mapBlockIndex.find(hash);
387 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
388 // An actually better block was announced.
389 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
390 state->pindexBestKnownBlock = it->second;
391 } else {
392 // An unknown block was announced; just assume that the latest one is the best one.
393 state->hashLastUnknownBlock = hash;
397 void MaybeSetPeerAsAnnouncingHeaderAndIDs(const CNodeState* nodestate, CNode* pfrom, CConnman& connman) {
398 if (!nodestate->fSupportsDesiredCmpctVersion) {
399 // Never ask from peers who can't provide witnesses.
400 return;
402 if (nodestate->fProvidesHeaderAndIDs) {
403 for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
404 if (*it == pfrom->GetId()) {
405 lNodesAnnouncingHeaderAndIDs.erase(it);
406 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
407 return;
410 bool fAnnounceUsingCMPCTBLOCK = false;
411 uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
412 if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
413 // As per BIP152, we only get 3 of our peers to announce
414 // blocks using compact encodings.
415 connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [&connman, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion](CNode* pnodeStop){
416 connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
417 return true;
419 lNodesAnnouncingHeaderAndIDs.pop_front();
421 fAnnounceUsingCMPCTBLOCK = true;
422 connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
423 lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
427 // Requires cs_main
428 bool CanDirectFetch(const Consensus::Params &consensusParams)
430 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
433 // Requires cs_main
434 bool PeerHasHeader(CNodeState *state, CBlockIndex *pindex)
436 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
437 return true;
438 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
439 return true;
440 return false;
443 /** Find the last common ancestor two blocks have.
444 * Both pa and pb must be non-NULL. */
445 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
446 if (pa->nHeight > pb->nHeight) {
447 pa = pa->GetAncestor(pb->nHeight);
448 } else if (pb->nHeight > pa->nHeight) {
449 pb = pb->GetAncestor(pa->nHeight);
452 while (pa != pb && pa && pb) {
453 pa = pa->pprev;
454 pb = pb->pprev;
457 // Eventually all chain branches meet at the genesis block.
458 assert(pa == pb);
459 return pa;
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<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 != NULL);
472 // Make sure pindexBestKnownBlock is up to date, we'll need it.
473 ProcessBlockAvailability(nodeid);
475 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
476 // This peer has nothing interesting.
477 return;
480 if (state->pindexLastCommonBlock == NULL) {
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<CBlockIndex*> vToFetch;
493 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 BOOST_FOREACH(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 } // anon namespace
552 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
553 LOCK(cs_main);
554 CNodeState *state = State(nodeid);
555 if (state == NULL)
556 return false;
557 stats.nMisbehavior = state->nMisbehavior;
558 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
559 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
560 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
561 if (queue.pindex)
562 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
564 return true;
567 void RegisterNodeSignals(CNodeSignals& nodeSignals)
569 nodeSignals.ProcessMessages.connect(&ProcessMessages);
570 nodeSignals.SendMessages.connect(&SendMessages);
571 nodeSignals.InitializeNode.connect(&InitializeNode);
572 nodeSignals.FinalizeNode.connect(&FinalizeNode);
575 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
577 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
578 nodeSignals.SendMessages.disconnect(&SendMessages);
579 nodeSignals.InitializeNode.disconnect(&InitializeNode);
580 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
583 //////////////////////////////////////////////////////////////////////////////
585 // mapOrphanTransactions
588 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
590 uint256 hash = tx.GetHash();
591 if (mapOrphanTransactions.count(hash))
592 return false;
594 // Ignore big transactions, to avoid a
595 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
596 // large transaction with a missing parent then we assume
597 // it will rebroadcast it later, after the parent transaction(s)
598 // have been mined or received.
599 // 100 orphans, each of which is at most 99,999 bytes big is
600 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
601 unsigned int sz = GetTransactionWeight(tx);
602 if (sz >= MAX_STANDARD_TX_WEIGHT)
604 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
605 return false;
608 auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
609 assert(ret.second);
610 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
611 mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
614 LogPrint("mempool", "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
615 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
616 return true;
619 int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
621 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
622 if (it == mapOrphanTransactions.end())
623 return 0;
624 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
626 auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
627 if (itPrev == mapOrphanTransactionsByPrev.end())
628 continue;
629 itPrev->second.erase(it);
630 if (itPrev->second.empty())
631 mapOrphanTransactionsByPrev.erase(itPrev);
633 mapOrphanTransactions.erase(it);
634 return 1;
637 void EraseOrphansFor(NodeId peer)
639 int nErased = 0;
640 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
641 while (iter != mapOrphanTransactions.end())
643 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
644 if (maybeErase->second.fromPeer == peer)
646 nErased += EraseOrphanTx(maybeErase->second.tx.GetHash());
649 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
653 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
655 unsigned int nEvicted = 0;
656 static int64_t nNextSweep;
657 int64_t nNow = GetTime();
658 if (nNextSweep <= nNow) {
659 // Sweep out expired orphan pool entries:
660 int nErased = 0;
661 int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
662 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
663 while (iter != mapOrphanTransactions.end())
665 map<uint256, COrphanTx>::iterator maybeErase = iter++;
666 if (maybeErase->second.nTimeExpire <= nNow) {
667 nErased += EraseOrphanTx(maybeErase->second.tx.GetHash());
668 } else {
669 nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
672 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
673 nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
674 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx due to expiration\n", nErased);
676 while (mapOrphanTransactions.size() > nMaxOrphans)
678 // Evict a random orphan:
679 uint256 randomhash = GetRandHash();
680 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
681 if (it == mapOrphanTransactions.end())
682 it = mapOrphanTransactions.begin();
683 EraseOrphanTx(it->first);
684 ++nEvicted;
686 return nEvicted;
689 // Requires cs_main.
690 void Misbehaving(NodeId pnode, int howmuch)
692 if (howmuch == 0)
693 return;
695 CNodeState *state = State(pnode);
696 if (state == NULL)
697 return;
699 state->nMisbehavior += howmuch;
700 int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
701 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
703 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
704 state->fShouldBan = true;
705 } else
706 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
716 //////////////////////////////////////////////////////////////////////////////
718 // blockchain -> download logic notification
721 PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
722 // Initialize global variables that cannot be constructed at startup.
723 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
726 void PeerLogicValidation::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int nPosInBlock) {
727 if (nPosInBlock == CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK)
728 return;
730 LOCK(cs_main);
732 std::vector<uint256> vOrphanErase;
733 // Which orphan pool entries must we evict?
734 for (size_t j = 0; j < tx.vin.size(); j++) {
735 auto itByPrev = mapOrphanTransactionsByPrev.find(tx.vin[j].prevout);
736 if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
737 for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
738 const CTransaction& orphanTx = (*mi)->second.tx;
739 const uint256& orphanHash = orphanTx.GetHash();
740 vOrphanErase.push_back(orphanHash);
744 // Erase orphan transactions include or precluded by this block
745 if (vOrphanErase.size()) {
746 int nErased = 0;
747 BOOST_FOREACH(uint256 &orphanHash, vOrphanErase) {
748 nErased += EraseOrphanTx(orphanHash);
750 LogPrint("mempool", "Erased %d orphan tx included or conflicted by block\n", nErased);
754 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
755 const int nNewHeight = pindexNew->nHeight;
756 connman->SetBestHeight(nNewHeight);
758 if (!fInitialDownload) {
759 // Find the hashes of all blocks that weren't previously in the best chain.
760 std::vector<uint256> vHashes;
761 const CBlockIndex *pindexToAnnounce = pindexNew;
762 while (pindexToAnnounce != pindexFork) {
763 vHashes.push_back(pindexToAnnounce->GetBlockHash());
764 pindexToAnnounce = pindexToAnnounce->pprev;
765 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
766 // Limit announcements in case of a huge reorganization.
767 // Rely on the peer's synchronization mechanism in that case.
768 break;
771 // Relay inventory, but don't relay old inventory during initial block download.
772 connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
773 if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
774 BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
775 pnode->PushBlockHash(hash);
781 nTimeBestReceived = GetTime();
784 void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
785 LOCK(cs_main);
787 const uint256 hash(block.GetHash());
788 std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
790 int nDoS = 0;
791 if (state.IsInvalid(nDoS)) {
792 if (it != mapBlockSource.end() && State(it->second.first)) {
793 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
794 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
795 State(it->second.first)->rejects.push_back(reject);
796 if (nDoS > 0 && it->second.second)
797 Misbehaving(it->second.first, nDoS);
800 if (it != mapBlockSource.end())
801 mapBlockSource.erase(it);
804 //////////////////////////////////////////////////////////////////////////////
806 // Messages
810 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
812 switch (inv.type)
814 case MSG_TX:
815 case MSG_WITNESS_TX:
817 assert(recentRejects);
818 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
820 // If the chain tip has changed previously rejected transactions
821 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
822 // or a double-spend. Reset the rejects filter and give those
823 // txs a second chance.
824 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
825 recentRejects->reset();
828 // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
829 // requesting or processing some txs which have already been included in a block
830 return recentRejects->contains(inv.hash) ||
831 mempool.exists(inv.hash) ||
832 mapOrphanTransactions.count(inv.hash) ||
833 pcoinsTip->HaveCoinsInCache(inv.hash);
835 case MSG_BLOCK:
836 case MSG_WITNESS_BLOCK:
837 return mapBlockIndex.count(inv.hash);
839 // Don't know what it is, just say we already got one
840 return true;
843 static void RelayTransaction(const CTransaction& tx, CConnman& connman)
845 CInv inv(MSG_TX, tx.GetHash());
846 connman.ForEachNode([&inv](CNode* pnode)
848 pnode->PushInventory(inv);
852 static void RelayAddress(const CAddress& addr, bool fReachable, CConnman& connman)
854 unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
856 // Relay to a limited number of other nodes
857 // Use deterministic randomness to send to the same nodes for 24 hours
858 // at a time so the addrKnowns of the chosen nodes prevent repeats
859 uint64_t hashAddr = addr.GetHash();
860 const CSipHasher hasher = connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
861 FastRandomContext insecure_rand;
863 std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
864 assert(nRelayNodes <= best.size());
866 auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
867 if (pnode->nVersion >= CADDR_TIME_VERSION) {
868 uint64_t hashKey = CSipHasher(hasher).Write(pnode->id).Finalize();
869 for (unsigned int i = 0; i < nRelayNodes; i++) {
870 if (hashKey > best[i].first) {
871 std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
872 best[i] = std::make_pair(hashKey, pnode);
873 break;
879 auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
880 for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
881 best[i].second->PushAddress(addr, insecure_rand);
885 connman.ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
888 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman)
890 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
891 unsigned int nMaxSendBufferSize = connman.GetSendBufferSize();
892 vector<CInv> vNotFound;
893 CNetMsgMaker msgMaker(pfrom->GetSendVersion());
894 LOCK(cs_main);
896 while (it != pfrom->vRecvGetData.end()) {
897 // Don't bother if send buffer is too full to respond anyway
898 if (pfrom->nSendSize >= nMaxSendBufferSize)
899 break;
901 const CInv &inv = *it;
903 boost::this_thread::interruption_point();
904 it++;
906 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
908 bool send = false;
909 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
910 if (mi != mapBlockIndex.end())
912 if (chainActive.Contains(mi->second)) {
913 send = true;
914 } else {
915 static const int nOneMonth = 30 * 24 * 60 * 60;
916 // To prevent fingerprinting attacks, only send blocks outside of the active
917 // chain if they are valid, and no more than a month older (both in time, and in
918 // best equivalent proof of work) than the best header chain we know about.
919 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
920 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
921 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
922 if (!send) {
923 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
927 // disconnect node in case we have reached the outbound limit for serving historical blocks
928 // never disconnect whitelisted nodes
929 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
930 if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
932 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
934 //disconnect node
935 pfrom->fDisconnect = true;
936 send = false;
938 // Pruned nodes may have deleted the block, so check whether
939 // it's available before trying to send.
940 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
942 // Send block from disk
943 CBlock block;
944 if (!ReadBlockFromDisk(block, (*mi).second, consensusParams))
945 assert(!"cannot load block from disk");
946 if (inv.type == MSG_BLOCK)
947 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, block));
948 else if (inv.type == MSG_WITNESS_BLOCK)
949 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, block));
950 else if (inv.type == MSG_FILTERED_BLOCK)
952 bool sendMerkleBlock = false;
953 CMerkleBlock merkleBlock;
955 LOCK(pfrom->cs_filter);
956 if (pfrom->pfilter) {
957 sendMerkleBlock = true;
958 merkleBlock = CMerkleBlock(block, *pfrom->pfilter);
961 if (sendMerkleBlock) {
962 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
963 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
964 // This avoids hurting performance by pointlessly requiring a round-trip
965 // Note that there is currently no way for a node to request any single transactions we didn't send here -
966 // they must either disconnect and retry or request the full block.
967 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
968 // however we MUST always provide at least what the remote peer needs
969 typedef std::pair<unsigned int, uint256> PairType;
970 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
971 connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *block.vtx[pair.first]));
973 // else
974 // no response
976 else if (inv.type == MSG_CMPCT_BLOCK)
978 // If a peer is asking for old blocks, we're almost guaranteed
979 // they won't have a useful mempool to match against a compact block,
980 // and we don't feel like constructing the object for them, so
981 // instead we respond with the full, non-compact block.
982 bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
983 int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
984 if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
985 CBlockHeaderAndShortTxIDs cmpctblock(block, fPeerWantsWitness);
986 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
987 } else
988 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, block));
991 // Trigger the peer node to send a getblocks request for the next batch of inventory
992 if (inv.hash == pfrom->hashContinue)
994 // Bypass PushInventory, this must send even if redundant,
995 // and we want it right after the last block so they don't
996 // wait for other stuff first.
997 vector<CInv> vInv;
998 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
999 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
1000 pfrom->hashContinue.SetNull();
1004 else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
1006 // Send stream from relay memory
1007 bool push = false;
1008 auto mi = mapRelay.find(inv.hash);
1009 int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
1010 if (mi != mapRelay.end()) {
1011 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
1012 push = true;
1013 } else if (pfrom->timeLastMempoolReq) {
1014 auto txinfo = mempool.info(inv.hash);
1015 // To protect privacy, do not answer getdata using the mempool when
1016 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1017 if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
1018 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
1019 push = true;
1022 if (!push) {
1023 vNotFound.push_back(inv);
1027 // Track requests for our stuff.
1028 GetMainSignals().Inventory(inv.hash);
1030 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
1031 break;
1035 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
1037 if (!vNotFound.empty()) {
1038 // Let the peer know that we didn't find what it asked for, so it doesn't
1039 // have to wait around forever. Currently only SPV clients actually care
1040 // about this message: it's needed when they are recursively walking the
1041 // dependencies of relevant unconfirmed transactions. SPV clients want to
1042 // do that because they want to know about (and store and rebroadcast and
1043 // risk analyze) the dependencies of transactions relevant to them, without
1044 // having to download the entire memory pool.
1045 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
1049 uint32_t GetFetchFlags(CNode* pfrom, CBlockIndex* pprev, const Consensus::Params& chainparams) {
1050 uint32_t nFetchFlags = 0;
1051 if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
1052 nFetchFlags |= MSG_WITNESS_FLAG;
1054 return nFetchFlags;
1057 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman)
1059 unsigned int nMaxSendBufferSize = connman.GetSendBufferSize();
1061 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
1062 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1064 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1065 return true;
1069 if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
1070 (strCommand == NetMsgType::FILTERLOAD ||
1071 strCommand == NetMsgType::FILTERADD))
1073 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
1074 LOCK(cs_main);
1075 Misbehaving(pfrom->GetId(), 100);
1076 return false;
1077 } else {
1078 pfrom->fDisconnect = true;
1079 return false;
1084 if (strCommand == NetMsgType::VERSION)
1086 // Each connection can only send one version message
1087 if (pfrom->nVersion != 0)
1089 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message")));
1090 LOCK(cs_main);
1091 Misbehaving(pfrom->GetId(), 1);
1092 return false;
1095 int64_t nTime;
1096 CAddress addrMe;
1097 CAddress addrFrom;
1098 uint64_t nNonce = 1;
1099 uint64_t nServiceInt;
1100 vRecv >> pfrom->nVersion >> nServiceInt >> nTime >> addrMe;
1101 pfrom->nServices = ServiceFlags(nServiceInt);
1102 if (!pfrom->fInbound)
1104 connman.SetServices(pfrom->addr, pfrom->nServices);
1106 if (pfrom->nServicesExpected & ~pfrom->nServices)
1108 LogPrint("net", "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->id, pfrom->nServices, pfrom->nServicesExpected);
1109 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
1110 strprintf("Expected to offer services %08x", pfrom->nServicesExpected)));
1111 pfrom->fDisconnect = true;
1112 return false;
1115 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
1117 // disconnect from peers older than this proto version
1118 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
1119 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
1120 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
1121 pfrom->fDisconnect = true;
1122 return false;
1125 if (pfrom->nVersion == 10300)
1126 pfrom->nVersion = 300;
1127 if (!vRecv.empty())
1128 vRecv >> addrFrom >> nNonce;
1129 if (!vRecv.empty()) {
1130 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
1131 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
1133 if (!vRecv.empty()) {
1134 vRecv >> pfrom->nStartingHeight;
1137 LOCK(pfrom->cs_filter);
1138 if (!vRecv.empty())
1139 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
1140 else
1141 pfrom->fRelayTxes = true;
1144 // Disconnect if we connected to ourself
1145 if (pfrom->fInbound && !connman.CheckIncomingNonce(nNonce))
1147 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
1148 pfrom->fDisconnect = true;
1149 return true;
1152 pfrom->addrLocal = addrMe;
1153 if (pfrom->fInbound && addrMe.IsRoutable())
1155 SeenLocal(addrMe);
1158 // Be shy and don't send version until we hear
1159 if (pfrom->fInbound)
1160 PushNodeVersion(pfrom, connman, GetAdjustedTime());
1162 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1164 if((pfrom->nServices & NODE_WITNESS))
1166 LOCK(cs_main);
1167 State(pfrom->GetId())->fHaveWitness = true;
1170 // Potentially mark this peer as a preferred download peer.
1172 LOCK(cs_main);
1173 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
1176 // Change version
1177 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
1178 int nSendVersion = std::min(pfrom->nVersion, PROTOCOL_VERSION);
1179 pfrom->SetSendVersion(nSendVersion);
1181 if (!pfrom->fInbound)
1183 // Advertise our address
1184 if (fListen && !IsInitialBlockDownload())
1186 CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
1187 FastRandomContext insecure_rand;
1188 if (addr.IsRoutable())
1190 LogPrint("net", "ProcessMessages: advertising address %s\n", addr.ToString());
1191 pfrom->PushAddress(addr, insecure_rand);
1192 } else if (IsPeerAddrLocalGood(pfrom)) {
1193 addr.SetIP(pfrom->addrLocal);
1194 LogPrint("net", "ProcessMessages: advertising address %s\n", addr.ToString());
1195 pfrom->PushAddress(addr, insecure_rand);
1199 // Get recent addresses
1200 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman.GetAddressCount() < 1000)
1202 connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
1203 pfrom->fGetAddr = true;
1205 connman.MarkAddressGood(pfrom->addr);
1208 pfrom->fSuccessfullyConnected = true;
1210 string remoteAddr;
1211 if (fLogIPs)
1212 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
1214 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1215 pfrom->cleanSubVer, pfrom->nVersion,
1216 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
1217 remoteAddr);
1219 int64_t nTimeOffset = nTime - GetTime();
1220 pfrom->nTimeOffset = nTimeOffset;
1221 AddTimeData(pfrom->addr, nTimeOffset);
1223 // Feeler connections exist only to verify if address is online.
1224 if (pfrom->fFeeler) {
1225 assert(pfrom->fInbound == false);
1226 pfrom->fDisconnect = true;
1228 return true;
1232 else if (pfrom->nVersion == 0)
1234 // Must have a version message before anything else
1235 LOCK(cs_main);
1236 Misbehaving(pfrom->GetId(), 1);
1237 return false;
1240 // At this point, the outgoing message serialization version can't change.
1241 CNetMsgMaker msgMaker(pfrom->GetSendVersion());
1243 if (strCommand == NetMsgType::VERACK)
1245 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1247 if (!pfrom->fInbound) {
1248 // Mark this node as currently connected, so we update its timestamp later.
1249 LOCK(cs_main);
1250 State(pfrom->GetId())->fCurrentlyConnected = true;
1253 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
1254 // Tell our peer we prefer to receive headers rather than inv's
1255 // We send this to non-NODE NETWORK peers as well, because even
1256 // non-NODE NETWORK peers can announce blocks (such as pruning
1257 // nodes)
1258 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
1260 if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
1261 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1262 // However, we do not request new block announcements using
1263 // cmpctblock messages.
1264 // We send this to non-NODE NETWORK peers as well, because
1265 // they may wish to request compact blocks from us
1266 bool fAnnounceUsingCMPCTBLOCK = false;
1267 uint64_t nCMPCTBLOCKVersion = 2;
1268 if (pfrom->GetLocalServices() & NODE_WITNESS)
1269 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1270 nCMPCTBLOCKVersion = 1;
1271 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
1276 else if (strCommand == NetMsgType::ADDR)
1278 vector<CAddress> vAddr;
1279 vRecv >> vAddr;
1281 // Don't want addr from older versions unless seeding
1282 if (pfrom->nVersion < CADDR_TIME_VERSION && connman.GetAddressCount() > 1000)
1283 return true;
1284 if (vAddr.size() > 1000)
1286 LOCK(cs_main);
1287 Misbehaving(pfrom->GetId(), 20);
1288 return error("message addr size() = %u", vAddr.size());
1291 // Store the new addresses
1292 vector<CAddress> vAddrOk;
1293 int64_t nNow = GetAdjustedTime();
1294 int64_t nSince = nNow - 10 * 60;
1295 BOOST_FOREACH(CAddress& addr, vAddr)
1297 boost::this_thread::interruption_point();
1299 if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1300 continue;
1302 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1303 addr.nTime = nNow - 5 * 24 * 60 * 60;
1304 pfrom->AddAddressKnown(addr);
1305 bool fReachable = IsReachable(addr);
1306 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1308 // Relay to a limited number of other nodes
1309 RelayAddress(addr, fReachable, connman);
1311 // Do not store addresses outside our network
1312 if (fReachable)
1313 vAddrOk.push_back(addr);
1315 connman.AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
1316 if (vAddr.size() < 1000)
1317 pfrom->fGetAddr = false;
1318 if (pfrom->fOneShot)
1319 pfrom->fDisconnect = true;
1322 else if (strCommand == NetMsgType::SENDHEADERS)
1324 LOCK(cs_main);
1325 State(pfrom->GetId())->fPreferHeaders = true;
1328 else if (strCommand == NetMsgType::SENDCMPCT)
1330 bool fAnnounceUsingCMPCTBLOCK = false;
1331 uint64_t nCMPCTBLOCKVersion = 0;
1332 vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
1333 if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
1334 LOCK(cs_main);
1335 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1336 if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
1337 State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
1338 State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
1340 if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
1341 State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
1342 if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
1343 if (pfrom->GetLocalServices() & NODE_WITNESS)
1344 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
1345 else
1346 State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
1352 else if (strCommand == NetMsgType::INV)
1354 vector<CInv> vInv;
1355 vRecv >> vInv;
1356 if (vInv.size() > MAX_INV_SZ)
1358 LOCK(cs_main);
1359 Misbehaving(pfrom->GetId(), 20);
1360 return error("message inv size() = %u", vInv.size());
1363 bool fBlocksOnly = !fRelayTxes;
1365 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1366 if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
1367 fBlocksOnly = false;
1369 LOCK(cs_main);
1371 uint32_t nFetchFlags = GetFetchFlags(pfrom, chainActive.Tip(), chainparams.GetConsensus());
1373 std::vector<CInv> vToFetch;
1375 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
1377 CInv &inv = vInv[nInv];
1379 boost::this_thread::interruption_point();
1381 bool fAlreadyHave = AlreadyHave(inv);
1382 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
1384 if (inv.type == MSG_TX) {
1385 inv.type |= nFetchFlags;
1388 if (inv.type == MSG_BLOCK) {
1389 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
1390 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
1391 // We used to request the full block here, but since headers-announcements are now the
1392 // primary method of announcement on the network, and since, in the case that a node
1393 // fell back to inv we probably have a reorg which we should get the headers for first,
1394 // we now only provide a getheaders response here. When we receive the headers, we will
1395 // then ask for the blocks we need.
1396 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
1397 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
1400 else
1402 pfrom->AddInventoryKnown(inv);
1403 if (fBlocksOnly)
1404 LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
1405 else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload())
1406 pfrom->AskFor(inv);
1409 // Track requests for our stuff
1410 GetMainSignals().Inventory(inv.hash);
1412 if (pfrom->nSendSize > (nMaxSendBufferSize * 2)) {
1413 Misbehaving(pfrom->GetId(), 50);
1414 return error("send buffer size() = %u", pfrom->nSendSize);
1418 if (!vToFetch.empty())
1419 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vToFetch));
1423 else if (strCommand == NetMsgType::GETDATA)
1425 vector<CInv> vInv;
1426 vRecv >> vInv;
1427 if (vInv.size() > MAX_INV_SZ)
1429 LOCK(cs_main);
1430 Misbehaving(pfrom->GetId(), 20);
1431 return error("message getdata size() = %u", vInv.size());
1434 if (fDebug || (vInv.size() != 1))
1435 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
1437 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
1438 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
1440 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
1441 ProcessGetData(pfrom, chainparams.GetConsensus(), connman);
1445 else if (strCommand == NetMsgType::GETBLOCKS)
1447 CBlockLocator locator;
1448 uint256 hashStop;
1449 vRecv >> locator >> hashStop;
1451 LOCK(cs_main);
1453 // Find the last block the caller has in the main chain
1454 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
1456 // Send the rest of the chain
1457 if (pindex)
1458 pindex = chainActive.Next(pindex);
1459 int nLimit = 500;
1460 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
1461 for (; pindex; pindex = chainActive.Next(pindex))
1463 if (pindex->GetBlockHash() == hashStop)
1465 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1466 break;
1468 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1469 // for some reasonable time window (1 hour) that block relay might require.
1470 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
1471 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
1473 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1474 break;
1476 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1477 if (--nLimit <= 0)
1479 // When this block is requested, we'll send an inv that'll
1480 // trigger the peer to getblocks the next batch of inventory.
1481 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1482 pfrom->hashContinue = pindex->GetBlockHash();
1483 break;
1489 else if (strCommand == NetMsgType::GETBLOCKTXN)
1491 BlockTransactionsRequest req;
1492 vRecv >> req;
1494 LOCK(cs_main);
1496 BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
1497 if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
1498 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->id);
1499 return true;
1502 if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
1503 // If an older block is requested (should never happen in practice,
1504 // but can happen in tests) send a block response instead of a
1505 // blocktxn response. Sending a full block response instead of a
1506 // small blocktxn response is preferable in the case where a peer
1507 // might maliciously send lots of getblocktxn requests to trigger
1508 // expensive disk reads, because it will require the peer to
1509 // actually receive all the data read from disk over the network.
1510 LogPrint("net", "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->id, MAX_BLOCKTXN_DEPTH);
1511 CInv inv;
1512 inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
1513 inv.hash = req.blockhash;
1514 pfrom->vRecvGetData.push_back(inv);
1515 ProcessGetData(pfrom, chainparams.GetConsensus(), connman);
1516 return true;
1519 CBlock block;
1520 assert(ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()));
1522 BlockTransactions resp(req);
1523 for (size_t i = 0; i < req.indexes.size(); i++) {
1524 if (req.indexes[i] >= block.vtx.size()) {
1525 Misbehaving(pfrom->GetId(), 100);
1526 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->id);
1527 return true;
1529 resp.txn[i] = block.vtx[req.indexes[i]];
1531 int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
1532 connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
1536 else if (strCommand == NetMsgType::GETHEADERS)
1538 CBlockLocator locator;
1539 uint256 hashStop;
1540 vRecv >> locator >> hashStop;
1542 LOCK(cs_main);
1543 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
1544 LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
1545 return true;
1548 CNodeState *nodestate = State(pfrom->GetId());
1549 CBlockIndex* pindex = NULL;
1550 if (locator.IsNull())
1552 // If locator is null, return the hashStop block
1553 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
1554 if (mi == mapBlockIndex.end())
1555 return true;
1556 pindex = (*mi).second;
1558 else
1560 // Find the last block the caller has in the main chain
1561 pindex = FindForkInGlobalIndex(chainActive, locator);
1562 if (pindex)
1563 pindex = chainActive.Next(pindex);
1566 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1567 vector<CBlock> vHeaders;
1568 int nLimit = MAX_HEADERS_RESULTS;
1569 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->id);
1570 for (; pindex; pindex = chainActive.Next(pindex))
1572 vHeaders.push_back(pindex->GetBlockHeader());
1573 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
1574 break;
1576 // pindex can be NULL either if we sent chainActive.Tip() OR
1577 // if our peer has chainActive.Tip() (and thus we are sending an empty
1578 // headers message). In both cases it's safe to update
1579 // pindexBestHeaderSent to be our tip.
1580 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
1581 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
1585 else if (strCommand == NetMsgType::TX)
1587 // Stop processing the transaction early if
1588 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1589 if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
1591 LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id);
1592 return true;
1595 deque<COutPoint> vWorkQueue;
1596 vector<uint256> vEraseQueue;
1597 CTransaction tx(deserialize, vRecv);
1599 CInv inv(MSG_TX, tx.GetHash());
1600 pfrom->AddInventoryKnown(inv);
1602 LOCK(cs_main);
1604 bool fMissingInputs = false;
1605 CValidationState state;
1607 pfrom->setAskFor.erase(inv.hash);
1608 mapAlreadyAskedFor.erase(inv.hash);
1610 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) {
1611 mempool.check(pcoinsTip);
1612 RelayTransaction(tx, connman);
1613 for (unsigned int i = 0; i < tx.vout.size(); i++) {
1614 vWorkQueue.emplace_back(inv.hash, i);
1617 pfrom->nLastTXTime = GetTime();
1619 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1620 pfrom->id,
1621 tx.GetHash().ToString(),
1622 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
1624 // Recursively process any orphan transactions that depended on this one
1625 set<NodeId> setMisbehaving;
1626 while (!vWorkQueue.empty()) {
1627 auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
1628 vWorkQueue.pop_front();
1629 if (itByPrev == mapOrphanTransactionsByPrev.end())
1630 continue;
1631 for (auto mi = itByPrev->second.begin();
1632 mi != itByPrev->second.end();
1633 ++mi)
1635 const CTransaction& orphanTx = (*mi)->second.tx;
1636 const uint256& orphanHash = orphanTx.GetHash();
1637 NodeId fromPeer = (*mi)->second.fromPeer;
1638 bool fMissingInputs2 = false;
1639 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1640 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1641 // anyone relaying LegitTxX banned)
1642 CValidationState stateDummy;
1645 if (setMisbehaving.count(fromPeer))
1646 continue;
1647 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
1648 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
1649 RelayTransaction(orphanTx, connman);
1650 for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
1651 vWorkQueue.emplace_back(orphanHash, i);
1653 vEraseQueue.push_back(orphanHash);
1655 else if (!fMissingInputs2)
1657 int nDos = 0;
1658 if (stateDummy.IsInvalid(nDos) && nDos > 0)
1660 // Punish peer that gave us an invalid orphan tx
1661 Misbehaving(fromPeer, nDos);
1662 setMisbehaving.insert(fromPeer);
1663 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
1665 // Has inputs but not accepted to mempool
1666 // Probably non-standard or insufficient fee/priority
1667 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
1668 vEraseQueue.push_back(orphanHash);
1669 if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
1670 // Do not use rejection cache for witness transactions or
1671 // witness-stripped transactions, as they can have been malleated.
1672 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1673 assert(recentRejects);
1674 recentRejects->insert(orphanHash);
1677 mempool.check(pcoinsTip);
1681 BOOST_FOREACH(uint256 hash, vEraseQueue)
1682 EraseOrphanTx(hash);
1684 else if (fMissingInputs)
1686 bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
1687 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1688 if (recentRejects->contains(txin.prevout.hash)) {
1689 fRejectedParents = true;
1690 break;
1693 if (!fRejectedParents) {
1694 uint32_t nFetchFlags = GetFetchFlags(pfrom, chainActive.Tip(), chainparams.GetConsensus());
1695 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
1696 CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
1697 pfrom->AddInventoryKnown(_inv);
1698 if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
1700 AddOrphanTx(tx, pfrom->GetId());
1702 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1703 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
1704 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
1705 if (nEvicted > 0)
1706 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
1707 } else {
1708 LogPrint("mempool", "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
1710 } else {
1711 if (!tx.HasWitness() && !state.CorruptionPossible()) {
1712 // Do not use rejection cache for witness transactions or
1713 // witness-stripped transactions, as they can have been malleated.
1714 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1715 assert(recentRejects);
1716 recentRejects->insert(tx.GetHash());
1719 if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1720 // Always relay transactions received from whitelisted peers, even
1721 // if they were already in the mempool or rejected from it due
1722 // to policy, allowing the node to function as a gateway for
1723 // nodes hidden behind it.
1725 // Never relay transactions that we would assign a non-zero DoS
1726 // score for, as we expect peers to do the same with us in that
1727 // case.
1728 int nDoS = 0;
1729 if (!state.IsInvalid(nDoS) || nDoS == 0) {
1730 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
1731 RelayTransaction(tx, connman);
1732 } else {
1733 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state));
1737 int nDoS = 0;
1738 if (state.IsInvalid(nDoS))
1740 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
1741 pfrom->id,
1742 FormatStateMessage(state));
1743 if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
1744 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
1745 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
1746 if (nDoS > 0) {
1747 Misbehaving(pfrom->GetId(), nDoS);
1753 else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
1755 CBlockHeaderAndShortTxIDs cmpctblock;
1756 vRecv >> cmpctblock;
1759 LOCK(cs_main);
1761 if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
1762 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1763 if (!IsInitialBlockDownload())
1764 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1765 return true;
1769 CBlockIndex *pindex = NULL;
1770 CValidationState state;
1771 if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
1772 int nDoS;
1773 if (state.IsInvalid(nDoS)) {
1774 if (nDoS > 0) {
1775 LOCK(cs_main);
1776 Misbehaving(pfrom->GetId(), nDoS);
1778 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->id);
1779 return true;
1783 LOCK(cs_main);
1784 // If AcceptBlockHeader returned true, it set pindex
1785 assert(pindex);
1786 UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
1788 std::map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
1789 bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
1791 if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
1792 return true;
1794 if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
1795 pindex->nTx != 0) { // We had this block at some point, but pruned it
1796 if (fAlreadyInFlight) {
1797 // We requested this block for some reason, but our mempool will probably be useless
1798 // so we just grab the block via normal getdata
1799 std::vector<CInv> vInv(1);
1800 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom, pindex->pprev, chainparams.GetConsensus()), cmpctblock.header.GetHash());
1801 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
1803 return true;
1806 // If we're not close to tip yet, give up and let parallel block fetch work its magic
1807 if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
1808 return true;
1810 CNodeState *nodestate = State(pfrom->GetId());
1812 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
1813 // Don't bother trying to process compact blocks from v1 peers
1814 // after segwit activates.
1815 return true;
1818 // We want to be a bit conservative just to be extra careful about DoS
1819 // possibilities in compact block processing...
1820 if (pindex->nHeight <= chainActive.Height() + 2) {
1821 if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
1822 (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
1823 list<QueuedBlock>::iterator *queuedBlockIt = NULL;
1824 if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex, &queuedBlockIt)) {
1825 if (!(*queuedBlockIt)->partialBlock)
1826 (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
1827 else {
1828 // The block was already in flight using compact blocks from the same peer
1829 LogPrint("net", "Peer sent us compact block we were already syncing!\n");
1830 return true;
1834 PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
1835 ReadStatus status = partialBlock.InitData(cmpctblock);
1836 if (status == READ_STATUS_INVALID) {
1837 MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
1838 Misbehaving(pfrom->GetId(), 100);
1839 LogPrintf("Peer %d sent us invalid compact block\n", pfrom->id);
1840 return true;
1841 } else if (status == READ_STATUS_FAILED) {
1842 // Duplicate txindexes, the block is now in-flight, so just request it
1843 std::vector<CInv> vInv(1);
1844 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom, pindex->pprev, chainparams.GetConsensus()), cmpctblock.header.GetHash());
1845 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
1846 return true;
1849 if (!fAlreadyInFlight && mapBlocksInFlight.size() == 1 && pindex->pprev->IsValid(BLOCK_VALID_CHAIN)) {
1850 // We seem to be rather well-synced, so it appears pfrom was the first to provide us
1851 // with this block! Let's get them to announce using compact blocks in the future.
1852 MaybeSetPeerAsAnnouncingHeaderAndIDs(nodestate, pfrom, connman);
1855 BlockTransactionsRequest req;
1856 for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
1857 if (!partialBlock.IsTxAvailable(i))
1858 req.indexes.push_back(i);
1860 if (req.indexes.empty()) {
1861 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
1862 BlockTransactions txn;
1863 txn.blockhash = cmpctblock.header.GetHash();
1864 CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
1865 blockTxnMsg << txn;
1866 return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman);
1867 } else {
1868 req.blockhash = pindex->GetBlockHash();
1869 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
1872 } else {
1873 if (fAlreadyInFlight) {
1874 // We requested this block, but its far into the future, so our
1875 // mempool will probably be useless - request the block normally
1876 std::vector<CInv> vInv(1);
1877 vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom, pindex->pprev, chainparams.GetConsensus()), cmpctblock.header.GetHash());
1878 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
1879 return true;
1880 } else {
1881 // If this was an announce-cmpctblock, we want the same treatment as a header message
1882 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
1883 std::vector<CBlock> headers;
1884 headers.push_back(cmpctblock.header);
1885 CDataStream vHeadersMsg(SER_NETWORK, PROTOCOL_VERSION);
1886 vHeadersMsg << headers;
1887 return ProcessMessage(pfrom, NetMsgType::HEADERS, vHeadersMsg, nTimeReceived, chainparams, connman);
1892 else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
1894 BlockTransactions resp;
1895 vRecv >> resp;
1897 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
1898 bool fBlockRead = false;
1900 LOCK(cs_main);
1902 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
1903 if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
1904 it->second.first != pfrom->GetId()) {
1905 LogPrint("net", "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->id);
1906 return true;
1909 PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
1910 ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
1911 if (status == READ_STATUS_INVALID) {
1912 MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
1913 Misbehaving(pfrom->GetId(), 100);
1914 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->id);
1915 return true;
1916 } else if (status == READ_STATUS_FAILED) {
1917 // Might have collided, fall back to getdata now :(
1918 std::vector<CInv> invs;
1919 invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom, chainActive.Tip(), chainparams.GetConsensus()), resp.blockhash));
1920 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
1921 } else {
1922 // Block is either okay, or possibly we received
1923 // READ_STATUS_CHECKBLOCK_FAILED.
1924 // Note that CheckBlock can only fail for one of a few reasons:
1925 // 1. bad-proof-of-work (impossible here, because we've already
1926 // accepted the header)
1927 // 2. merkleroot doesn't match the transactions given (already
1928 // caught in FillBlock with READ_STATUS_FAILED, so
1929 // impossible here)
1930 // 3. the block is otherwise invalid (eg invalid coinbase,
1931 // block is too big, too many legacy sigops, etc).
1932 // So if CheckBlock failed, #3 is the only possibility.
1933 // Under BIP 152, we don't DoS-ban unless proof of work is
1934 // invalid (we don't require all the stateless checks to have
1935 // been run). This is handled below, so just treat this as
1936 // though the block was successfully read, and rely on the
1937 // handling in ProcessNewBlock to ensure the block index is
1938 // updated, reject messages go out, etc.
1939 MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
1940 fBlockRead = true;
1941 // mapBlockSource is only used for sending reject messages and DoS scores,
1942 // so the race between here and cs_main in ProcessNewBlock is fine.
1943 // BIP 152 permits peers to relay compact blocks after validating
1944 // the header only; we should not punish peers if the block turns
1945 // out to be invalid.
1946 mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
1948 } // Don't hold cs_main when we call into ProcessNewBlock
1949 if (fBlockRead) {
1950 bool fNewBlock = false;
1951 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
1952 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
1953 ProcessNewBlock(chainparams, pblock, true, NULL, &fNewBlock);
1954 if (fNewBlock)
1955 pfrom->nLastBlockTime = GetTime();
1960 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
1962 std::vector<CBlockHeader> headers;
1964 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
1965 unsigned int nCount = ReadCompactSize(vRecv);
1966 if (nCount > MAX_HEADERS_RESULTS) {
1967 LOCK(cs_main);
1968 Misbehaving(pfrom->GetId(), 20);
1969 return error("headers message size = %u", nCount);
1971 headers.resize(nCount);
1972 for (unsigned int n = 0; n < nCount; n++) {
1973 vRecv >> headers[n];
1974 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
1977 if (nCount == 0) {
1978 // Nothing interesting. Stop asking this peers for more headers.
1979 return true;
1982 CBlockIndex *pindexLast = NULL;
1984 LOCK(cs_main);
1985 CNodeState *nodestate = State(pfrom->GetId());
1987 // If this looks like it could be a block announcement (nCount <
1988 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1989 // don't connect:
1990 // - Send a getheaders message in response to try to connect the chain.
1991 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1992 // don't connect before giving DoS points
1993 // - Once a headers message is received that is valid and does connect,
1994 // nUnconnectingHeaders gets reset back to 0.
1995 if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
1996 nodestate->nUnconnectingHeaders++;
1997 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
1998 LogPrint("net", "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1999 headers[0].GetHash().ToString(),
2000 headers[0].hashPrevBlock.ToString(),
2001 pindexBestHeader->nHeight,
2002 pfrom->id, nodestate->nUnconnectingHeaders);
2003 // Set hashLastUnknownBlock for this peer, so that if we
2004 // eventually get the headers - even from a different peer -
2005 // we can use this peer to download.
2006 UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
2008 if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
2009 Misbehaving(pfrom->GetId(), 20);
2011 return true;
2014 uint256 hashLastBlock;
2015 for (const CBlockHeader& header : headers) {
2016 if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
2017 Misbehaving(pfrom->GetId(), 20);
2018 return error("non-continuous headers sequence");
2020 hashLastBlock = header.GetHash();
2024 CValidationState state;
2025 if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast)) {
2026 int nDoS;
2027 if (state.IsInvalid(nDoS)) {
2028 if (nDoS > 0) {
2029 LOCK(cs_main);
2030 Misbehaving(pfrom->GetId(), nDoS);
2032 return error("invalid header received");
2037 LOCK(cs_main);
2038 CNodeState *nodestate = State(pfrom->GetId());
2039 if (nodestate->nUnconnectingHeaders > 0) {
2040 LogPrint("net", "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->id, nodestate->nUnconnectingHeaders);
2042 nodestate->nUnconnectingHeaders = 0;
2044 assert(pindexLast);
2045 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
2047 if (nCount == MAX_HEADERS_RESULTS) {
2048 // Headers message had its maximum size; the peer may have more headers.
2049 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2050 // from there instead.
2051 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
2052 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
2055 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
2056 // If this set of headers is valid and ends in a block with at least as
2057 // much work as our tip, download as much as possible.
2058 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
2059 vector<CBlockIndex *> vToFetch;
2060 CBlockIndex *pindexWalk = pindexLast;
2061 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2062 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2063 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
2064 !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
2065 (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
2066 // We don't have this block, and it's not yet in flight.
2067 vToFetch.push_back(pindexWalk);
2069 pindexWalk = pindexWalk->pprev;
2071 // If pindexWalk still isn't on our main chain, we're looking at a
2072 // very large reorg at a time we think we're close to caught up to
2073 // the main chain -- this shouldn't really happen. Bail out on the
2074 // direct fetch and rely on parallel download instead.
2075 if (!chainActive.Contains(pindexWalk)) {
2076 LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
2077 pindexLast->GetBlockHash().ToString(),
2078 pindexLast->nHeight);
2079 } else {
2080 vector<CInv> vGetData;
2081 // Download as much as possible, from earliest to latest.
2082 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vToFetch) {
2083 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2084 // Can't download any more from this peer
2085 break;
2087 uint32_t nFetchFlags = GetFetchFlags(pfrom, pindex->pprev, chainparams.GetConsensus());
2088 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2089 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex);
2090 LogPrint("net", "Requesting block %s from peer=%d\n",
2091 pindex->GetBlockHash().ToString(), pfrom->id);
2093 if (vGetData.size() > 1) {
2094 LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
2095 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
2097 if (vGetData.size() > 0) {
2098 if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
2099 // We seem to be rather well-synced, so it appears pfrom was the first to provide us
2100 // with this block! Let's get them to announce using compact blocks in the future.
2101 MaybeSetPeerAsAnnouncingHeaderAndIDs(nodestate, pfrom, connman);
2102 // In any case, we want to download using a compact block, not a regular one
2103 vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
2105 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2112 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
2114 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2115 vRecv >> *pblock;
2117 LogPrint("net", "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->id);
2119 // Process all blocks from whitelisted peers, even if not requested,
2120 // unless we're still syncing with the network.
2121 // Such an unrequested block may still be processed, subject to the
2122 // conditions in AcceptBlock().
2123 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
2124 const uint256 hash(pblock->GetHash());
2126 LOCK(cs_main);
2127 // Also always process if we requested the block explicitly, as we may
2128 // need it even though it is not a candidate for a new best tip.
2129 forceProcessing |= MarkBlockAsReceived(hash);
2130 // mapBlockSource is only used for sending reject messages and DoS scores,
2131 // so the race between here and cs_main in ProcessNewBlock is fine.
2132 mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
2134 bool fNewBlock = false;
2135 ProcessNewBlock(chainparams, pblock, forceProcessing, NULL, &fNewBlock);
2136 if (fNewBlock)
2137 pfrom->nLastBlockTime = GetTime();
2141 else if (strCommand == NetMsgType::GETADDR)
2143 // This asymmetric behavior for inbound and outbound connections was introduced
2144 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2145 // to users' AddrMan and later request them by sending getaddr messages.
2146 // Making nodes which are behind NAT and can only make outgoing connections ignore
2147 // the getaddr message mitigates the attack.
2148 if (!pfrom->fInbound) {
2149 LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id);
2150 return true;
2153 // Only send one GetAddr response per connection to reduce resource waste
2154 // and discourage addr stamping of INV announcements.
2155 if (pfrom->fSentAddr) {
2156 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
2157 return true;
2159 pfrom->fSentAddr = true;
2161 pfrom->vAddrToSend.clear();
2162 vector<CAddress> vAddr = connman.GetAddresses();
2163 FastRandomContext insecure_rand;
2164 BOOST_FOREACH(const CAddress &addr, vAddr)
2165 pfrom->PushAddress(addr, insecure_rand);
2169 else if (strCommand == NetMsgType::MEMPOOL)
2171 if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
2173 LogPrint("net", "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
2174 pfrom->fDisconnect = true;
2175 return true;
2178 if (connman.OutboundTargetReached(false) && !pfrom->fWhitelisted)
2180 LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
2181 pfrom->fDisconnect = true;
2182 return true;
2185 LOCK(pfrom->cs_inventory);
2186 pfrom->fSendMempool = true;
2190 else if (strCommand == NetMsgType::PING)
2192 if (pfrom->nVersion > BIP0031_VERSION)
2194 uint64_t nonce = 0;
2195 vRecv >> nonce;
2196 // Echo the message back with the nonce. This allows for two useful features:
2198 // 1) A remote node can quickly check if the connection is operational
2199 // 2) Remote nodes can measure the latency of the network thread. If this node
2200 // is overloaded it won't respond to pings quickly and the remote node can
2201 // avoid sending us more work, like chain download requests.
2203 // The nonce stops the remote getting confused between different pings: without
2204 // it, if the remote node sends a ping once per second and this node takes 5
2205 // seconds to respond to each, the 5th ping the remote sends would appear to
2206 // return very quickly.
2207 connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
2212 else if (strCommand == NetMsgType::PONG)
2214 int64_t pingUsecEnd = nTimeReceived;
2215 uint64_t nonce = 0;
2216 size_t nAvail = vRecv.in_avail();
2217 bool bPingFinished = false;
2218 std::string sProblem;
2220 if (nAvail >= sizeof(nonce)) {
2221 vRecv >> nonce;
2223 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2224 if (pfrom->nPingNonceSent != 0) {
2225 if (nonce == pfrom->nPingNonceSent) {
2226 // Matching pong received, this ping is no longer outstanding
2227 bPingFinished = true;
2228 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
2229 if (pingUsecTime > 0) {
2230 // Successful ping time measurement, replace previous
2231 pfrom->nPingUsecTime = pingUsecTime;
2232 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
2233 } else {
2234 // This should never happen
2235 sProblem = "Timing mishap";
2237 } else {
2238 // Nonce mismatches are normal when pings are overlapping
2239 sProblem = "Nonce mismatch";
2240 if (nonce == 0) {
2241 // This is most likely a bug in another implementation somewhere; cancel this ping
2242 bPingFinished = true;
2243 sProblem = "Nonce zero";
2246 } else {
2247 sProblem = "Unsolicited pong without ping";
2249 } else {
2250 // This is most likely a bug in another implementation somewhere; cancel this ping
2251 bPingFinished = true;
2252 sProblem = "Short payload";
2255 if (!(sProblem.empty())) {
2256 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2257 pfrom->id,
2258 sProblem,
2259 pfrom->nPingNonceSent,
2260 nonce,
2261 nAvail);
2263 if (bPingFinished) {
2264 pfrom->nPingNonceSent = 0;
2269 else if (strCommand == NetMsgType::FILTERLOAD)
2271 CBloomFilter filter;
2272 vRecv >> filter;
2274 if (!filter.IsWithinSizeConstraints())
2276 // There is no excuse for sending a too-large filter
2277 LOCK(cs_main);
2278 Misbehaving(pfrom->GetId(), 100);
2280 else
2282 LOCK(pfrom->cs_filter);
2283 delete pfrom->pfilter;
2284 pfrom->pfilter = new CBloomFilter(filter);
2285 pfrom->pfilter->UpdateEmptyFull();
2286 pfrom->fRelayTxes = true;
2291 else if (strCommand == NetMsgType::FILTERADD)
2293 vector<unsigned char> vData;
2294 vRecv >> vData;
2296 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2297 // and thus, the maximum size any matched object can have) in a filteradd message
2298 bool bad = false;
2299 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
2300 bad = true;
2301 } else {
2302 LOCK(pfrom->cs_filter);
2303 if (pfrom->pfilter) {
2304 pfrom->pfilter->insert(vData);
2305 } else {
2306 bad = true;
2309 if (bad) {
2310 LOCK(cs_main);
2311 Misbehaving(pfrom->GetId(), 100);
2316 else if (strCommand == NetMsgType::FILTERCLEAR)
2318 LOCK(pfrom->cs_filter);
2319 if (pfrom->GetLocalServices() & NODE_BLOOM) {
2320 delete pfrom->pfilter;
2321 pfrom->pfilter = new CBloomFilter();
2323 pfrom->fRelayTxes = true;
2327 else if (strCommand == NetMsgType::REJECT)
2329 if (fDebug) {
2330 try {
2331 string strMsg; unsigned char ccode; string strReason;
2332 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
2334 ostringstream ss;
2335 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
2337 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
2339 uint256 hash;
2340 vRecv >> hash;
2341 ss << ": hash " << hash.ToString();
2343 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
2344 } catch (const std::ios_base::failure&) {
2345 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
2346 LogPrint("net", "Unparseable reject message received\n");
2351 else if (strCommand == NetMsgType::FEEFILTER) {
2352 CAmount newFeeFilter = 0;
2353 vRecv >> newFeeFilter;
2354 if (MoneyRange(newFeeFilter)) {
2356 LOCK(pfrom->cs_feeFilter);
2357 pfrom->minFeeFilter = newFeeFilter;
2359 LogPrint("net", "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->id);
2363 else if (strCommand == NetMsgType::NOTFOUND) {
2364 // We do not care about the NOTFOUND message, but logging an Unknown Command
2365 // message would be undesirable as we transmit it ourselves.
2368 else {
2369 // Ignore unknown commands for extensibility
2370 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
2375 return true;
2378 // requires LOCK(cs_vRecvMsg)
2379 bool ProcessMessages(CNode* pfrom, CConnman& connman)
2381 const CChainParams& chainparams = Params();
2382 unsigned int nMaxSendBufferSize = connman.GetSendBufferSize();
2383 //if (fDebug)
2384 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
2387 // Message format
2388 // (4) message start
2389 // (12) command
2390 // (4) size
2391 // (4) checksum
2392 // (x) data
2394 bool fOk = true;
2396 if (!pfrom->vRecvGetData.empty())
2397 ProcessGetData(pfrom, chainparams.GetConsensus(), connman);
2399 // this maintains the order of responses
2400 if (!pfrom->vRecvGetData.empty()) return fOk;
2402 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
2403 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
2404 // Don't bother if send buffer is too full to respond anyway
2405 if (pfrom->nSendSize >= nMaxSendBufferSize)
2406 break;
2408 // get next message
2409 CNetMessage& msg = *it;
2411 //if (fDebug)
2412 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
2413 // msg.hdr.nMessageSize, msg.vRecv.size(),
2414 // msg.complete() ? "Y" : "N");
2416 // end, if an incomplete message is found
2417 if (!msg.complete())
2418 break;
2420 // at this point, any failure means we can delete the current message
2421 it++;
2423 // Scan for message start
2424 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
2425 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
2426 fOk = false;
2427 break;
2430 // Read header
2431 CMessageHeader& hdr = msg.hdr;
2432 if (!hdr.IsValid(chainparams.MessageStart()))
2434 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
2435 continue;
2437 string strCommand = hdr.GetCommand();
2439 // Message size
2440 unsigned int nMessageSize = hdr.nMessageSize;
2442 // Checksum
2443 CDataStream& vRecv = msg.vRecv;
2444 const uint256& hash = msg.GetMessageHash();
2445 if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
2447 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
2448 SanitizeString(strCommand), nMessageSize,
2449 HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
2450 HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
2451 continue;
2454 // Process message
2455 bool fRet = false;
2458 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman);
2459 boost::this_thread::interruption_point();
2461 catch (const std::ios_base::failure& e)
2463 connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message")));
2464 if (strstr(e.what(), "end of data"))
2466 // Allow exceptions from under-length message on vRecv
2467 LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2469 else if (strstr(e.what(), "size too large"))
2471 // Allow exceptions from over-long size
2472 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2474 else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
2476 // Allow exceptions from non-canonical encoding
2477 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
2479 else
2481 PrintExceptionContinue(&e, "ProcessMessages()");
2484 catch (const boost::thread_interrupted&) {
2485 throw;
2487 catch (const std::exception& e) {
2488 PrintExceptionContinue(&e, "ProcessMessages()");
2489 } catch (...) {
2490 PrintExceptionContinue(NULL, "ProcessMessages()");
2493 if (!fRet)
2494 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
2496 break;
2499 // In case the connection got shut down, its receive buffer was wiped
2500 if (!pfrom->fDisconnect)
2501 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
2503 return fOk;
2506 class CompareInvMempoolOrder
2508 CTxMemPool *mp;
2509 public:
2510 CompareInvMempoolOrder(CTxMemPool *_mempool)
2512 mp = _mempool;
2515 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
2517 /* As std::make_heap produces a max-heap, we want the entries with the
2518 * fewest ancestors/highest fee to sort later. */
2519 return mp->CompareDepthAndScore(*b, *a);
2523 bool SendMessages(CNode* pto, CConnman& connman)
2525 const Consensus::Params& consensusParams = Params().GetConsensus();
2527 // Don't send anything until we get its version message
2528 if (pto->nVersion == 0 || pto->fDisconnect)
2529 return true;
2531 // If we get here, the outgoing message serialization version is set and can't change.
2532 CNetMsgMaker msgMaker(pto->GetSendVersion());
2535 // Message: ping
2537 bool pingSend = false;
2538 if (pto->fPingQueued) {
2539 // RPC ping request by user
2540 pingSend = true;
2542 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
2543 // Ping automatically sent as a latency probe & keepalive.
2544 pingSend = true;
2546 if (pingSend) {
2547 uint64_t nonce = 0;
2548 while (nonce == 0) {
2549 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
2551 pto->fPingQueued = false;
2552 pto->nPingUsecStart = GetTimeMicros();
2553 if (pto->nVersion > BIP0031_VERSION) {
2554 pto->nPingNonceSent = nonce;
2555 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
2556 } else {
2557 // Peer is too old to support ping command with nonce, pong will never arrive.
2558 pto->nPingNonceSent = 0;
2559 connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING));
2563 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2564 if (!lockMain)
2565 return true;
2567 CNodeState &state = *State(pto->GetId());
2569 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
2570 connman.PushMessage(pto, msgMaker.Make(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
2571 state.rejects.clear();
2573 if (state.fShouldBan) {
2574 state.fShouldBan = false;
2575 if (pto->fWhitelisted)
2576 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
2577 else {
2578 pto->fDisconnect = true;
2579 if (pto->addr.IsLocal())
2580 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
2581 else
2583 connman.Ban(pto->addr, BanReasonNodeMisbehaving);
2585 return true;
2589 // Address refresh broadcast
2590 int64_t nNow = GetTimeMicros();
2591 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
2592 AdvertiseLocal(pto);
2593 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
2597 // Message: addr
2599 if (pto->nNextAddrSend < nNow) {
2600 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
2601 vector<CAddress> vAddr;
2602 vAddr.reserve(pto->vAddrToSend.size());
2603 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2605 if (!pto->addrKnown.contains(addr.GetKey()))
2607 pto->addrKnown.insert(addr.GetKey());
2608 vAddr.push_back(addr);
2609 // receiver rejects addr messages larger than 1000
2610 if (vAddr.size() >= 1000)
2612 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2613 vAddr.clear();
2617 pto->vAddrToSend.clear();
2618 if (!vAddr.empty())
2619 connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
2620 // we only send the big addr message once
2621 if (pto->vAddrToSend.capacity() > 40)
2622 pto->vAddrToSend.shrink_to_fit();
2625 // Start block sync
2626 if (pindexBestHeader == NULL)
2627 pindexBestHeader = chainActive.Tip();
2628 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.
2629 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
2630 // Only actively request headers from a single peer, unless we're close to today.
2631 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2632 state.fSyncStarted = true;
2633 nSyncStarted++;
2634 const CBlockIndex *pindexStart = pindexBestHeader;
2635 /* If possible, start at the block preceding the currently
2636 best known header. This ensures that we always get a
2637 non-empty list of headers back as long as the peer
2638 is up-to-date. With a non-empty response, we can initialise
2639 the peer's known best block. This wouldn't be possible
2640 if we requested starting at pindexBestHeader and
2641 got back an empty response. */
2642 if (pindexStart->pprev)
2643 pindexStart = pindexStart->pprev;
2644 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
2645 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
2649 // Resend wallet transactions that haven't gotten in a block yet
2650 // Except during reindex, importing and IBD, when old wallet
2651 // transactions become unconfirmed and spams other nodes.
2652 if (!fReindex && !fImporting && !IsInitialBlockDownload())
2654 GetMainSignals().Broadcast(nTimeBestReceived, &connman);
2658 // Try sending block announcements via headers
2661 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2662 // list of block hashes we're relaying, and our peer wants
2663 // headers announcements, then find the first header
2664 // not yet known to our peer but would connect, and send.
2665 // If no header would connect, or if we have too many
2666 // blocks, or if the peer doesn't want headers, just
2667 // add all to the inv queue.
2668 LOCK(pto->cs_inventory);
2669 vector<CBlock> vHeaders;
2670 bool fRevertToInv = ((!state.fPreferHeaders &&
2671 (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
2672 pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
2673 CBlockIndex *pBestIndex = NULL; // last header queued for delivery
2674 ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date
2676 if (!fRevertToInv) {
2677 bool fFoundStartingHeader = false;
2678 // Try to find first header that our peer doesn't have, and
2679 // then send all headers past that one. If we come across any
2680 // headers that aren't on chainActive, give up.
2681 BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
2682 BlockMap::iterator mi = mapBlockIndex.find(hash);
2683 assert(mi != mapBlockIndex.end());
2684 CBlockIndex *pindex = mi->second;
2685 if (chainActive[pindex->nHeight] != pindex) {
2686 // Bail out if we reorged away from this block
2687 fRevertToInv = true;
2688 break;
2690 if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
2691 // This means that the list of blocks to announce don't
2692 // connect to each other.
2693 // This shouldn't really be possible to hit during
2694 // regular operation (because reorgs should take us to
2695 // a chain that has some block not on the prior chain,
2696 // which should be caught by the prior check), but one
2697 // way this could happen is by using invalidateblock /
2698 // reconsiderblock repeatedly on the tip, causing it to
2699 // be added multiple times to vBlockHashesToAnnounce.
2700 // Robustly deal with this rare situation by reverting
2701 // to an inv.
2702 fRevertToInv = true;
2703 break;
2705 pBestIndex = pindex;
2706 if (fFoundStartingHeader) {
2707 // add this to the headers message
2708 vHeaders.push_back(pindex->GetBlockHeader());
2709 } else if (PeerHasHeader(&state, pindex)) {
2710 continue; // keep looking for the first new block
2711 } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
2712 // Peer doesn't have this header but they do have the prior one.
2713 // Start sending headers.
2714 fFoundStartingHeader = true;
2715 vHeaders.push_back(pindex->GetBlockHeader());
2716 } else {
2717 // Peer doesn't have this header or the prior one -- nothing will
2718 // connect, so bail out.
2719 fRevertToInv = true;
2720 break;
2724 if (!fRevertToInv && !vHeaders.empty()) {
2725 if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
2726 // We only send up to 1 block as header-and-ids, as otherwise
2727 // probably means we're doing an initial-ish-sync or they're slow
2728 LogPrint("net", "%s sending header-and-ids %s to peer %d\n", __func__,
2729 vHeaders.front().GetHash().ToString(), pto->id);
2730 //TODO: Shouldn't need to reload block from disk, but requires refactor
2731 CBlock block;
2732 assert(ReadBlockFromDisk(block, pBestIndex, consensusParams));
2733 CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
2734 int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
2735 connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
2736 state.pindexBestHeaderSent = pBestIndex;
2737 } else if (state.fPreferHeaders) {
2738 if (vHeaders.size() > 1) {
2739 LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
2740 vHeaders.size(),
2741 vHeaders.front().GetHash().ToString(),
2742 vHeaders.back().GetHash().ToString(), pto->id);
2743 } else {
2744 LogPrint("net", "%s: sending header %s to peer=%d\n", __func__,
2745 vHeaders.front().GetHash().ToString(), pto->id);
2747 connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
2748 state.pindexBestHeaderSent = pBestIndex;
2749 } else
2750 fRevertToInv = true;
2752 if (fRevertToInv) {
2753 // If falling back to using an inv, just try to inv the tip.
2754 // The last entry in vBlockHashesToAnnounce was our tip at some point
2755 // in the past.
2756 if (!pto->vBlockHashesToAnnounce.empty()) {
2757 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
2758 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
2759 assert(mi != mapBlockIndex.end());
2760 CBlockIndex *pindex = mi->second;
2762 // Warn if we're announcing a block that is not on the main chain.
2763 // This should be very rare and could be optimized out.
2764 // Just log for now.
2765 if (chainActive[pindex->nHeight] != pindex) {
2766 LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
2767 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
2770 // If the peer's chain has this block, don't inv it back.
2771 if (!PeerHasHeader(&state, pindex)) {
2772 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
2773 LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__,
2774 pto->id, hashToAnnounce.ToString());
2778 pto->vBlockHashesToAnnounce.clear();
2782 // Message: inventory
2784 vector<CInv> vInv;
2786 LOCK(pto->cs_inventory);
2787 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
2789 // Add blocks
2790 BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
2791 vInv.push_back(CInv(MSG_BLOCK, hash));
2792 if (vInv.size() == MAX_INV_SZ) {
2793 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2794 vInv.clear();
2797 pto->vInventoryBlockToSend.clear();
2799 // Check whether periodic sends should happen
2800 bool fSendTrickle = pto->fWhitelisted;
2801 if (pto->nNextInvSend < nNow) {
2802 fSendTrickle = true;
2803 // Use half the delay for outbound peers, as there is less privacy concern for them.
2804 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
2807 // Time to send but the peer has requested we not relay transactions.
2808 if (fSendTrickle) {
2809 LOCK(pto->cs_filter);
2810 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
2813 // Respond to BIP35 mempool requests
2814 if (fSendTrickle && pto->fSendMempool) {
2815 auto vtxinfo = mempool.infoAll();
2816 pto->fSendMempool = false;
2817 CAmount filterrate = 0;
2819 LOCK(pto->cs_feeFilter);
2820 filterrate = pto->minFeeFilter;
2823 LOCK(pto->cs_filter);
2825 for (const auto& txinfo : vtxinfo) {
2826 const uint256& hash = txinfo.tx->GetHash();
2827 CInv inv(MSG_TX, hash);
2828 pto->setInventoryTxToSend.erase(hash);
2829 if (filterrate) {
2830 if (txinfo.feeRate.GetFeePerK() < filterrate)
2831 continue;
2833 if (pto->pfilter) {
2834 if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
2836 pto->filterInventoryKnown.insert(hash);
2837 vInv.push_back(inv);
2838 if (vInv.size() == MAX_INV_SZ) {
2839 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2840 vInv.clear();
2843 pto->timeLastMempoolReq = GetTime();
2846 // Determine transactions to relay
2847 if (fSendTrickle) {
2848 // Produce a vector with all candidates for sending
2849 vector<std::set<uint256>::iterator> vInvTx;
2850 vInvTx.reserve(pto->setInventoryTxToSend.size());
2851 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
2852 vInvTx.push_back(it);
2854 CAmount filterrate = 0;
2856 LOCK(pto->cs_feeFilter);
2857 filterrate = pto->minFeeFilter;
2859 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
2860 // A heap is used so that not all items need sorting if only a few are being sent.
2861 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
2862 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
2863 // No reason to drain out at many times the network's capacity,
2864 // especially since we have many peers and some will draw much shorter delays.
2865 unsigned int nRelayedTransactions = 0;
2866 LOCK(pto->cs_filter);
2867 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
2868 // Fetch the top element from the heap
2869 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
2870 std::set<uint256>::iterator it = vInvTx.back();
2871 vInvTx.pop_back();
2872 uint256 hash = *it;
2873 // Remove it from the to-be-sent set
2874 pto->setInventoryTxToSend.erase(it);
2875 // Check if not in the filter already
2876 if (pto->filterInventoryKnown.contains(hash)) {
2877 continue;
2879 // Not in the mempool anymore? don't bother sending it.
2880 auto txinfo = mempool.info(hash);
2881 if (!txinfo.tx) {
2882 continue;
2884 if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
2885 continue;
2887 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
2888 // Send
2889 vInv.push_back(CInv(MSG_TX, hash));
2890 nRelayedTransactions++;
2892 // Expire old relay messages
2893 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
2895 mapRelay.erase(vRelayExpiration.front().second);
2896 vRelayExpiration.pop_front();
2899 auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
2900 if (ret.second) {
2901 vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
2904 if (vInv.size() == MAX_INV_SZ) {
2905 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2906 vInv.clear();
2908 pto->filterInventoryKnown.insert(hash);
2912 if (!vInv.empty())
2913 connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
2915 // Detect whether we're stalling
2916 nNow = GetTimeMicros();
2917 if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
2918 // Stalling only triggers when the block download window cannot move. During normal steady state,
2919 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
2920 // should only happen during initial block download.
2921 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
2922 pto->fDisconnect = true;
2923 return true;
2925 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
2926 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
2927 // We compensate for other peers to prevent killing off peers due to our own downstream link
2928 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
2929 // to unreasonably increase our timeout.
2930 if (state.vBlocksInFlight.size() > 0) {
2931 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
2932 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
2933 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
2934 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
2935 pto->fDisconnect = true;
2936 return true;
2941 // Message: getdata (blocks)
2943 vector<CInv> vGetData;
2944 if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
2945 vector<CBlockIndex*> vToDownload;
2946 NodeId staller = -1;
2947 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
2948 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
2949 uint32_t nFetchFlags = GetFetchFlags(pto, pindex->pprev, consensusParams);
2950 vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
2951 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
2952 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
2953 pindex->nHeight, pto->id);
2955 if (state.nBlocksInFlight == 0 && staller != -1) {
2956 if (State(staller)->nStallingSince == 0) {
2957 State(staller)->nStallingSince = nNow;
2958 LogPrint("net", "Stall started peer=%d\n", staller);
2964 // Message: getdata (non-blocks)
2966 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2968 const CInv& inv = (*pto->mapAskFor.begin()).second;
2969 if (!AlreadyHave(inv))
2971 if (fDebug)
2972 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
2973 vGetData.push_back(inv);
2974 if (vGetData.size() >= 1000)
2976 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2977 vGetData.clear();
2979 } else {
2980 //If we're not going to ask, don't expect a response.
2981 pto->setAskFor.erase(inv.hash);
2983 pto->mapAskFor.erase(pto->mapAskFor.begin());
2985 if (!vGetData.empty())
2986 connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
2989 // Message: feefilter
2991 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
2992 if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
2993 !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
2994 CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
2995 int64_t timeNow = GetTimeMicros();
2996 if (timeNow > pto->nextSendTimeFeeFilter) {
2997 static FeeFilterRounder filterRounder(::minRelayTxFee);
2998 CAmount filterToSend = filterRounder.round(currentFilter);
2999 if (filterToSend != pto->lastSentFeeFilter) {
3000 connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
3001 pto->lastSentFeeFilter = filterToSend;
3003 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
3005 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3006 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3007 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
3008 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
3009 pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
3013 return true;
3016 class CNetProcessingCleanup
3018 public:
3019 CNetProcessingCleanup() {}
3020 ~CNetProcessingCleanup() {
3021 // orphan transactions
3022 mapOrphanTransactions.clear();
3023 mapOrphanTransactionsByPrev.clear();
3025 } instance_of_cnetprocessingcleanup;