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"
9 #include "arith_uint256.h"
10 #include "blockencodings.h"
11 #include "chainparams.h"
12 #include "consensus/validation.h"
15 #include "validation.h"
16 #include "merkleblock.h"
18 #include "netmessagemaker.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
25 #include "reverse_iterator.h"
26 #include "tinyformat.h"
27 #include "txmempool.h"
28 #include "ui_interface.h"
30 #include "utilmoneystr.h"
31 #include "utilstrencodings.h"
32 #include "validationinterface.h"
35 # error "Bitcoin cannot be compiled without assertions."
38 std::atomic
<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
40 struct IteratorComparator
43 bool operator()(const I
& a
, const I
& b
)
50 // When modifying, adapt the copy of this definition in tests/DoS_tests.
55 std::map
<uint256
, COrphanTx
> mapOrphanTransactions
GUARDED_BY(cs_main
);
56 std::map
<COutPoint
, std::set
<std::map
<uint256
, COrphanTx
>::iterator
, IteratorComparator
>> mapOrphanTransactionsByPrev
GUARDED_BY(cs_main
);
57 void EraseOrphansFor(NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
);
59 static size_t vExtraTxnForCompactIt
= 0;
60 static std::vector
<std::pair
<uint256
, CTransactionRef
>> vExtraTxnForCompact
GUARDED_BY(cs_main
);
62 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY
= 0x3cac0035b5866b90ULL
; // SHA256("main address relay")[0:8]
66 /** Number of nodes with fSyncStarted. */
70 * Sources of received blocks, saved to be able to send them reject
71 * messages or ban them when processing happens afterwards. Protected by
73 * Set mapBlockSource[hash].second to false if the node should not be
74 * punished if the block is invalid.
76 std::map
<uint256
, std::pair
<NodeId
, bool>> mapBlockSource
;
79 * Filter for transactions that were recently rejected by
80 * AcceptToMemoryPool. These are not rerequested until the chain tip
81 * changes, at which point the entire filter is reset. Protected by
84 * Without this filter we'd be re-requesting txs from each of our peers,
85 * increasing bandwidth consumption considerably. For instance, with 100
86 * peers, half of which relay a tx we don't accept, that might be a 50x
87 * bandwidth increase. A flooding attacker attempting to roll-over the
88 * filter using minimum-sized, 60byte, transactions might manage to send
89 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
90 * two minute window to send invs to us.
92 * Decreasing the false positive rate is fairly cheap, so we pick one in a
93 * million to make it highly unlikely for users to have issues with this
98 std::unique_ptr
<CRollingBloomFilter
> recentRejects
;
99 uint256 hashRecentRejectsChainTip
;
101 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
104 const CBlockIndex
* pindex
; //!< Optional.
105 bool fValidatedHeaders
; //!< Whether this block has validated headers at the time of request.
106 std::unique_ptr
<PartiallyDownloadedBlock
> partialBlock
; //!< Optional, used for CMPCTBLOCK downloads
108 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> > mapBlocksInFlight
;
110 /** Stack of nodes which we have set to announce using compact blocks */
111 std::list
<NodeId
> lNodesAnnouncingHeaderAndIDs
;
113 /** Number of preferable block download peers. */
114 int nPreferredDownload
= 0;
116 /** Number of peers from which we're downloading blocks. */
117 int nPeersWithValidatedDownloads
= 0;
119 /** Relay map, protected by cs_main. */
120 typedef std::map
<uint256
, CTransactionRef
> MapRelay
;
122 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
123 std::deque
<std::pair
<int64_t, MapRelay::iterator
>> vRelayExpiration
;
126 //////////////////////////////////////////////////////////////////////////////
128 // Registration of network node signals.
133 struct CBlockReject
{
134 unsigned char chRejectCode
;
135 std::string strRejectReason
;
140 * Maintain validation-specific state about nodes, protected by cs_main, instead
141 * by CNode's own locks. This simplifies asynchronous operation, where
142 * processing of incoming data is done after the ProcessMessage call returns,
143 * and we're no longer holding the node's locks.
146 //! The peer's address
147 const CService address
;
148 //! Whether we have a fully established connection.
149 bool fCurrentlyConnected
;
150 //! Accumulated misbehaviour score for this peer.
152 //! Whether this peer should be disconnected and banned (unless whitelisted).
154 //! String name of this peer (debugging/logging purposes).
155 const std::string name
;
156 //! List of asynchronously-determined block rejections to notify this peer about.
157 std::vector
<CBlockReject
> rejects
;
158 //! The best known block we know this peer has announced.
159 const CBlockIndex
*pindexBestKnownBlock
;
160 //! The hash of the last unknown block this peer has announced.
161 uint256 hashLastUnknownBlock
;
162 //! The last full block we both have.
163 const CBlockIndex
*pindexLastCommonBlock
;
164 //! The best header we have sent our peer.
165 const CBlockIndex
*pindexBestHeaderSent
;
166 //! Length of current-streak of unconnecting headers announcements
167 int nUnconnectingHeaders
;
168 //! Whether we've started headers synchronization with this peer.
170 //! When to potentially disconnect peer for stalling headers download
171 int64_t nHeadersSyncTimeout
;
172 //! Since when we're stalling block download progress (in microseconds), or 0.
173 int64_t nStallingSince
;
174 std::list
<QueuedBlock
> vBlocksInFlight
;
175 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
176 int64_t nDownloadingSince
;
178 int nBlocksInFlightValidHeaders
;
179 //! Whether we consider this a preferred download peer.
180 bool fPreferredDownload
;
181 //! Whether this peer wants invs or headers (when possible) for block announcements.
183 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
184 bool fPreferHeaderAndIDs
;
186 * Whether this peer will send us cmpctblocks if we request them.
187 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
188 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
190 bool fProvidesHeaderAndIDs
;
191 //! Whether this peer can give us witnesses
193 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
194 bool fWantsCmpctWitness
;
196 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
197 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
199 bool fSupportsDesiredCmpctVersion
;
201 CNodeState(CAddress addrIn
, std::string addrNameIn
) : address(addrIn
), name(addrNameIn
) {
202 fCurrentlyConnected
= false;
205 pindexBestKnownBlock
= NULL
;
206 hashLastUnknownBlock
.SetNull();
207 pindexLastCommonBlock
= NULL
;
208 pindexBestHeaderSent
= NULL
;
209 nUnconnectingHeaders
= 0;
210 fSyncStarted
= false;
211 nHeadersSyncTimeout
= 0;
213 nDownloadingSince
= 0;
215 nBlocksInFlightValidHeaders
= 0;
216 fPreferredDownload
= false;
217 fPreferHeaders
= false;
218 fPreferHeaderAndIDs
= false;
219 fProvidesHeaderAndIDs
= false;
220 fHaveWitness
= false;
221 fWantsCmpctWitness
= false;
222 fSupportsDesiredCmpctVersion
= false;
226 /** Map maintaining per-node state. Requires cs_main. */
227 std::map
<NodeId
, CNodeState
> mapNodeState
;
230 CNodeState
*State(NodeId pnode
) {
231 std::map
<NodeId
, CNodeState
>::iterator it
= mapNodeState
.find(pnode
);
232 if (it
== mapNodeState
.end())
237 void UpdatePreferredDownload(CNode
* node
, CNodeState
* state
)
239 nPreferredDownload
-= state
->fPreferredDownload
;
241 // Whether this node should be marked as a preferred download node.
242 state
->fPreferredDownload
= (!node
->fInbound
|| node
->fWhitelisted
) && !node
->fOneShot
&& !node
->fClient
;
244 nPreferredDownload
+= state
->fPreferredDownload
;
247 void PushNodeVersion(CNode
*pnode
, CConnman
& connman
, int64_t nTime
)
249 ServiceFlags nLocalNodeServices
= pnode
->GetLocalServices();
250 uint64_t nonce
= pnode
->GetLocalNonce();
251 int nNodeStartingHeight
= pnode
->GetMyStartingHeight();
252 NodeId nodeid
= pnode
->GetId();
253 CAddress addr
= pnode
->addr
;
255 CAddress addrYou
= (addr
.IsRoutable() && !IsProxy(addr
) ? addr
: CAddress(CService(), addr
.nServices
));
256 CAddress addrMe
= CAddress(CService(), nLocalNodeServices
);
258 connman
.PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERSION
, PROTOCOL_VERSION
, (uint64_t)nLocalNodeServices
, nTime
, addrYou
, addrMe
,
259 nonce
, strSubVersion
, nNodeStartingHeight
, ::fRelayTxes
));
262 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), addrYou
.ToString(), nodeid
);
264 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), nodeid
);
268 void InitializeNode(CNode
*pnode
, CConnman
& connman
) {
269 CAddress addr
= pnode
->addr
;
270 std::string addrName
= pnode
->GetAddrName();
271 NodeId nodeid
= pnode
->GetId();
274 mapNodeState
.emplace_hint(mapNodeState
.end(), std::piecewise_construct
, std::forward_as_tuple(nodeid
), std::forward_as_tuple(addr
, std::move(addrName
)));
277 PushNodeVersion(pnode
, connman
, GetTime());
280 void FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
281 fUpdateConnectionTime
= false;
283 CNodeState
*state
= State(nodeid
);
285 if (state
->fSyncStarted
)
288 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
289 fUpdateConnectionTime
= true;
292 for (const QueuedBlock
& entry
: state
->vBlocksInFlight
) {
293 mapBlocksInFlight
.erase(entry
.hash
);
295 EraseOrphansFor(nodeid
);
296 nPreferredDownload
-= state
->fPreferredDownload
;
297 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
298 assert(nPeersWithValidatedDownloads
>= 0);
300 mapNodeState
.erase(nodeid
);
302 if (mapNodeState
.empty()) {
303 // Do a consistency check after the last peer is removed.
304 assert(mapBlocksInFlight
.empty());
305 assert(nPreferredDownload
== 0);
306 assert(nPeersWithValidatedDownloads
== 0);
308 LogPrint(BCLog::NET
, "Cleared nodestate for peer=%d\n", nodeid
);
312 // Returns a bool indicating whether we requested this block.
313 // Also used if a block was /not/ received and timed out or started with another peer
314 bool MarkBlockAsReceived(const uint256
& hash
) {
315 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
316 if (itInFlight
!= mapBlocksInFlight
.end()) {
317 CNodeState
*state
= State(itInFlight
->second
.first
);
318 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
319 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
320 // Last validated block on the queue was received.
321 nPeersWithValidatedDownloads
--;
323 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
324 // First block on the queue was received, update the start download time for the next one
325 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
327 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
328 state
->nBlocksInFlight
--;
329 state
->nStallingSince
= 0;
330 mapBlocksInFlight
.erase(itInFlight
);
337 // returns false, still setting pit, if the block was already in flight from the same peer
338 // pit will only be valid as long as the same cs_main lock is being held
339 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const CBlockIndex
* pindex
= NULL
, std::list
<QueuedBlock
>::iterator
** pit
= NULL
) {
340 CNodeState
*state
= State(nodeid
);
341 assert(state
!= NULL
);
343 // Short-circuit most stuff in case its from the same node
344 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
345 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
347 *pit
= &itInFlight
->second
.second
;
352 // Make sure it's not listed somewhere already.
353 MarkBlockAsReceived(hash
);
355 std::list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
356 {hash
, pindex
, pindex
!= NULL
, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : NULL
)});
357 state
->nBlocksInFlight
++;
358 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
359 if (state
->nBlocksInFlight
== 1) {
360 // We're starting a block download (batch) from this peer.
361 state
->nDownloadingSince
= GetTimeMicros();
363 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= NULL
) {
364 nPeersWithValidatedDownloads
++;
366 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
368 *pit
= &itInFlight
->second
.second
;
372 /** Check whether the last unknown block a peer advertised is not yet known. */
373 void ProcessBlockAvailability(NodeId nodeid
) {
374 CNodeState
*state
= State(nodeid
);
375 assert(state
!= NULL
);
377 if (!state
->hashLastUnknownBlock
.IsNull()) {
378 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
379 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
380 if (state
->pindexBestKnownBlock
== NULL
|| itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
381 state
->pindexBestKnownBlock
= itOld
->second
;
382 state
->hashLastUnknownBlock
.SetNull();
387 /** Update tracking information about which blocks a peer is assumed to have. */
388 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
389 CNodeState
*state
= State(nodeid
);
390 assert(state
!= NULL
);
392 ProcessBlockAvailability(nodeid
);
394 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
395 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
396 // An actually better block was announced.
397 if (state
->pindexBestKnownBlock
== NULL
|| it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
398 state
->pindexBestKnownBlock
= it
->second
;
400 // An unknown block was announced; just assume that the latest one is the best one.
401 state
->hashLastUnknownBlock
= hash
;
405 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid
, CConnman
& connman
) {
406 AssertLockHeld(cs_main
);
407 CNodeState
* nodestate
= State(nodeid
);
408 if (!nodestate
|| !nodestate
->fSupportsDesiredCmpctVersion
) {
409 // Never ask from peers who can't provide witnesses.
412 if (nodestate
->fProvidesHeaderAndIDs
) {
413 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
415 lNodesAnnouncingHeaderAndIDs
.erase(it
);
416 lNodesAnnouncingHeaderAndIDs
.push_back(nodeid
);
420 connman
.ForNode(nodeid
, [&connman
](CNode
* pfrom
){
421 bool fAnnounceUsingCMPCTBLOCK
= false;
422 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
423 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
424 // As per BIP152, we only get 3 of our peers to announce
425 // blocks using compact encodings.
426 connman
.ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [&connman
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
427 connman
.PushMessage(pnodeStop
, CNetMsgMaker(pnodeStop
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
430 lNodesAnnouncingHeaderAndIDs
.pop_front();
432 fAnnounceUsingCMPCTBLOCK
= true;
433 connman
.PushMessage(pfrom
, CNetMsgMaker(pfrom
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
434 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
441 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
443 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
447 bool PeerHasHeader(CNodeState
*state
, const CBlockIndex
*pindex
)
449 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
451 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
456 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
457 * at most count entries. */
458 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<const CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
462 vBlocks
.reserve(vBlocks
.size() + count
);
463 CNodeState
*state
= State(nodeid
);
464 assert(state
!= NULL
);
466 // Make sure pindexBestKnownBlock is up to date, we'll need it.
467 ProcessBlockAvailability(nodeid
);
469 if (state
->pindexBestKnownBlock
== NULL
|| state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
|| state
->pindexBestKnownBlock
->nChainWork
< UintToArith256(consensusParams
.nMinimumChainWork
)) {
470 // This peer has nothing interesting.
474 if (state
->pindexLastCommonBlock
== NULL
) {
475 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
476 // Guessing wrong in either direction is not a problem.
477 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
480 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
481 // of its current tip anymore. Go back enough to fix that.
482 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
483 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
486 std::vector
<const CBlockIndex
*> vToFetch
;
487 const CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
488 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
489 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
490 // download that next block if the window were 1 larger.
491 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
492 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
493 NodeId waitingfor
= -1;
494 while (pindexWalk
->nHeight
< nMaxHeight
) {
495 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
496 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
497 // as iterating over ~100 CBlockIndex* entries anyway.
498 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
499 vToFetch
.resize(nToFetch
);
500 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
501 vToFetch
[nToFetch
- 1] = pindexWalk
;
502 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
503 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
506 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
507 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
508 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
509 // already part of our chain (and therefore don't need it even if pruned).
510 for (const CBlockIndex
* pindex
: vToFetch
) {
511 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
512 // We consider the chain that this peer is on invalid.
515 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
516 // We wouldn't download this block or its descendants from this peer.
519 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
520 if (pindex
->nChainTx
)
521 state
->pindexLastCommonBlock
= pindex
;
522 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
523 // The block is not already downloaded, and not yet in flight.
524 if (pindex
->nHeight
> nWindowEnd
) {
525 // We reached the end of the window.
526 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
527 // We aren't able to fetch anything, but we would be if the download window was one larger.
528 nodeStaller
= waitingfor
;
532 vBlocks
.push_back(pindex
);
533 if (vBlocks
.size() == count
) {
536 } else if (waitingfor
== -1) {
537 // This is the first already-in-flight block.
538 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
546 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
548 CNodeState
*state
= State(nodeid
);
551 stats
.nMisbehavior
= state
->nMisbehavior
;
552 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
553 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
554 for (const QueuedBlock
& queue
: state
->vBlocksInFlight
) {
556 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
561 void RegisterNodeSignals(CNodeSignals
& nodeSignals
)
563 nodeSignals
.ProcessMessages
.connect(&ProcessMessages
);
564 nodeSignals
.SendMessages
.connect(&SendMessages
);
565 nodeSignals
.InitializeNode
.connect(&InitializeNode
);
566 nodeSignals
.FinalizeNode
.connect(&FinalizeNode
);
569 void UnregisterNodeSignals(CNodeSignals
& nodeSignals
)
571 nodeSignals
.ProcessMessages
.disconnect(&ProcessMessages
);
572 nodeSignals
.SendMessages
.disconnect(&SendMessages
);
573 nodeSignals
.InitializeNode
.disconnect(&InitializeNode
);
574 nodeSignals
.FinalizeNode
.disconnect(&FinalizeNode
);
577 //////////////////////////////////////////////////////////////////////////////
579 // mapOrphanTransactions
582 void AddToCompactExtraTransactions(const CTransactionRef
& tx
)
584 size_t max_extra_txn
= GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
);
585 if (max_extra_txn
<= 0)
587 if (!vExtraTxnForCompact
.size())
588 vExtraTxnForCompact
.resize(max_extra_txn
);
589 vExtraTxnForCompact
[vExtraTxnForCompactIt
] = std::make_pair(tx
->GetWitnessHash(), tx
);
590 vExtraTxnForCompactIt
= (vExtraTxnForCompactIt
+ 1) % max_extra_txn
;
593 bool AddOrphanTx(const CTransactionRef
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
595 const uint256
& hash
= tx
->GetHash();
596 if (mapOrphanTransactions
.count(hash
))
599 // Ignore big transactions, to avoid a
600 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
601 // large transaction with a missing parent then we assume
602 // it will rebroadcast it later, after the parent transaction(s)
603 // have been mined or received.
604 // 100 orphans, each of which is at most 99,999 bytes big is
605 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
606 unsigned int sz
= GetTransactionWeight(*tx
);
607 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
609 LogPrint(BCLog::MEMPOOL
, "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
613 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
615 for (const CTxIn
& txin
: tx
->vin
) {
616 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
619 AddToCompactExtraTransactions(tx
);
621 LogPrint(BCLog::MEMPOOL
, "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
622 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
626 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
628 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
629 if (it
== mapOrphanTransactions
.end())
631 for (const CTxIn
& txin
: it
->second
.tx
->vin
)
633 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
634 if (itPrev
== mapOrphanTransactionsByPrev
.end())
636 itPrev
->second
.erase(it
);
637 if (itPrev
->second
.empty())
638 mapOrphanTransactionsByPrev
.erase(itPrev
);
640 mapOrphanTransactions
.erase(it
);
644 void EraseOrphansFor(NodeId peer
)
647 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
648 while (iter
!= mapOrphanTransactions
.end())
650 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
651 if (maybeErase
->second
.fromPeer
== peer
)
653 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
656 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx from peer=%d\n", nErased
, peer
);
660 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
662 unsigned int nEvicted
= 0;
663 static int64_t nNextSweep
;
664 int64_t nNow
= GetTime();
665 if (nNextSweep
<= nNow
) {
666 // Sweep out expired orphan pool entries:
668 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
669 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
670 while (iter
!= mapOrphanTransactions
.end())
672 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
673 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
674 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
676 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
679 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
680 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
681 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx due to expiration\n", nErased
);
683 while (mapOrphanTransactions
.size() > nMaxOrphans
)
685 // Evict a random orphan:
686 uint256 randomhash
= GetRandHash();
687 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
688 if (it
== mapOrphanTransactions
.end())
689 it
= mapOrphanTransactions
.begin();
690 EraseOrphanTx(it
->first
);
697 void Misbehaving(NodeId pnode
, int howmuch
)
702 CNodeState
*state
= State(pnode
);
706 state
->nMisbehavior
+= howmuch
;
707 int banscore
= GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
708 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
710 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
711 state
->fShouldBan
= true;
713 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
723 //////////////////////////////////////////////////////////////////////////////
725 // blockchain -> download logic notification
728 PeerLogicValidation::PeerLogicValidation(CConnman
* connmanIn
) : connman(connmanIn
) {
729 // Initialize global variables that cannot be constructed at startup.
730 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
733 void PeerLogicValidation::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
* pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
736 std::vector
<uint256
> vOrphanErase
;
738 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
739 const CTransaction
& tx
= *ptx
;
741 // Which orphan pool entries must we evict?
742 for (const auto& txin
: tx
.vin
) {
743 auto itByPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
744 if (itByPrev
== mapOrphanTransactionsByPrev
.end()) continue;
745 for (auto mi
= itByPrev
->second
.begin(); mi
!= itByPrev
->second
.end(); ++mi
) {
746 const CTransaction
& orphanTx
= *(*mi
)->second
.tx
;
747 const uint256
& orphanHash
= orphanTx
.GetHash();
748 vOrphanErase
.push_back(orphanHash
);
753 // Erase orphan transactions include or precluded by this block
754 if (vOrphanErase
.size()) {
756 for (uint256
&orphanHash
: vOrphanErase
) {
757 nErased
+= EraseOrphanTx(orphanHash
);
759 LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx included or conflicted by block\n", nErased
);
763 // All of the following cache a recent block, and are protected by cs_most_recent_block
764 static CCriticalSection cs_most_recent_block
;
765 static std::shared_ptr
<const CBlock
> most_recent_block
;
766 static std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> most_recent_compact_block
;
767 static uint256 most_recent_block_hash
;
768 static bool fWitnessesPresentInMostRecentCompactBlock
;
770 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex
*pindex
, const std::shared_ptr
<const CBlock
>& pblock
) {
771 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> pcmpctblock
= std::make_shared
<const CBlockHeaderAndShortTxIDs
> (*pblock
, true);
772 const CNetMsgMaker
msgMaker(PROTOCOL_VERSION
);
776 static int nHighestFastAnnounce
= 0;
777 if (pindex
->nHeight
<= nHighestFastAnnounce
)
779 nHighestFastAnnounce
= pindex
->nHeight
;
781 bool fWitnessEnabled
= IsWitnessEnabled(pindex
->pprev
, Params().GetConsensus());
782 uint256
hashBlock(pblock
->GetHash());
785 LOCK(cs_most_recent_block
);
786 most_recent_block_hash
= hashBlock
;
787 most_recent_block
= pblock
;
788 most_recent_compact_block
= pcmpctblock
;
789 fWitnessesPresentInMostRecentCompactBlock
= fWitnessEnabled
;
792 connman
->ForEachNode([this, &pcmpctblock
, pindex
, &msgMaker
, fWitnessEnabled
, &hashBlock
](CNode
* pnode
) {
793 // TODO: Avoid the repeated-serialization here
794 if (pnode
->nVersion
< INVALID_CB_NO_BAN_VERSION
|| pnode
->fDisconnect
)
796 ProcessBlockAvailability(pnode
->GetId());
797 CNodeState
&state
= *State(pnode
->GetId());
798 // If the peer has, or we announced to them the previous block already,
799 // but we don't think they have this one, go ahead and announce it
800 if (state
.fPreferHeaderAndIDs
&& (!fWitnessEnabled
|| state
.fWantsCmpctWitness
) &&
801 !PeerHasHeader(&state
, pindex
) && PeerHasHeader(&state
, pindex
->pprev
)) {
803 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
804 hashBlock
.ToString(), pnode
->GetId());
805 connman
->PushMessage(pnode
, msgMaker
.Make(NetMsgType::CMPCTBLOCK
, *pcmpctblock
));
806 state
.pindexBestHeaderSent
= pindex
;
811 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex
*pindexNew
, const CBlockIndex
*pindexFork
, bool fInitialDownload
) {
812 const int nNewHeight
= pindexNew
->nHeight
;
813 connman
->SetBestHeight(nNewHeight
);
815 if (!fInitialDownload
) {
816 // Find the hashes of all blocks that weren't previously in the best chain.
817 std::vector
<uint256
> vHashes
;
818 const CBlockIndex
*pindexToAnnounce
= pindexNew
;
819 while (pindexToAnnounce
!= pindexFork
) {
820 vHashes
.push_back(pindexToAnnounce
->GetBlockHash());
821 pindexToAnnounce
= pindexToAnnounce
->pprev
;
822 if (vHashes
.size() == MAX_BLOCKS_TO_ANNOUNCE
) {
823 // Limit announcements in case of a huge reorganization.
824 // Rely on the peer's synchronization mechanism in that case.
828 // Relay inventory, but don't relay old inventory during initial block download.
829 connman
->ForEachNode([nNewHeight
, &vHashes
](CNode
* pnode
) {
830 if (nNewHeight
> (pnode
->nStartingHeight
!= -1 ? pnode
->nStartingHeight
- 2000 : 0)) {
831 for (const uint256
& hash
: reverse_iterate(vHashes
)) {
832 pnode
->PushBlockHash(hash
);
836 connman
->WakeMessageHandler();
839 nTimeBestReceived
= GetTime();
842 void PeerLogicValidation::BlockChecked(const CBlock
& block
, const CValidationState
& state
) {
845 const uint256
hash(block
.GetHash());
846 std::map
<uint256
, std::pair
<NodeId
, bool>>::iterator it
= mapBlockSource
.find(hash
);
849 if (state
.IsInvalid(nDoS
)) {
850 // Don't send reject message with code 0 or an internal reject code.
851 if (it
!= mapBlockSource
.end() && State(it
->second
.first
) && state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) {
852 CBlockReject reject
= {(unsigned char)state
.GetRejectCode(), state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), hash
};
853 State(it
->second
.first
)->rejects
.push_back(reject
);
854 if (nDoS
> 0 && it
->second
.second
)
855 Misbehaving(it
->second
.first
, nDoS
);
859 // 1. The block is valid
860 // 2. We're not in initial block download
861 // 3. This is currently the best block we're aware of. We haven't updated
862 // the tip yet so we have no way to check this directly here. Instead we
863 // just check that there are currently no other blocks in flight.
864 else if (state
.IsValid() &&
865 !IsInitialBlockDownload() &&
866 mapBlocksInFlight
.count(hash
) == mapBlocksInFlight
.size()) {
867 if (it
!= mapBlockSource
.end()) {
868 MaybeSetPeerAsAnnouncingHeaderAndIDs(it
->second
.first
, *connman
);
871 if (it
!= mapBlockSource
.end())
872 mapBlockSource
.erase(it
);
875 //////////////////////////////////////////////////////////////////////////////
881 bool static AlreadyHave(const CInv
& inv
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
888 assert(recentRejects
);
889 if (chainActive
.Tip()->GetBlockHash() != hashRecentRejectsChainTip
)
891 // If the chain tip has changed previously rejected transactions
892 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
893 // or a double-spend. Reset the rejects filter and give those
894 // txs a second chance.
895 hashRecentRejectsChainTip
= chainActive
.Tip()->GetBlockHash();
896 recentRejects
->reset();
899 return recentRejects
->contains(inv
.hash
) ||
900 mempool
.exists(inv
.hash
) ||
901 mapOrphanTransactions
.count(inv
.hash
) ||
902 pcoinsTip
->HaveCoinInCache(COutPoint(inv
.hash
, 0)) || // Best effort: only try output 0 and 1
903 pcoinsTip
->HaveCoinInCache(COutPoint(inv
.hash
, 1));
906 case MSG_WITNESS_BLOCK
:
907 return mapBlockIndex
.count(inv
.hash
);
909 // Don't know what it is, just say we already got one
913 static void RelayTransaction(const CTransaction
& tx
, CConnman
& connman
)
915 CInv
inv(MSG_TX
, tx
.GetHash());
916 connman
.ForEachNode([&inv
](CNode
* pnode
)
918 pnode
->PushInventory(inv
);
922 static void RelayAddress(const CAddress
& addr
, bool fReachable
, CConnman
& connman
)
924 unsigned int nRelayNodes
= fReachable
? 2 : 1; // limited relaying of addresses outside our network(s)
926 // Relay to a limited number of other nodes
927 // Use deterministic randomness to send to the same nodes for 24 hours
928 // at a time so the addrKnowns of the chosen nodes prevent repeats
929 uint64_t hashAddr
= addr
.GetHash();
930 const CSipHasher hasher
= connman
.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY
).Write(hashAddr
<< 32).Write((GetTime() + hashAddr
) / (24*60*60));
931 FastRandomContext insecure_rand
;
933 std::array
<std::pair
<uint64_t, CNode
*>,2> best
{{{0, nullptr}, {0, nullptr}}};
934 assert(nRelayNodes
<= best
.size());
936 auto sortfunc
= [&best
, &hasher
, nRelayNodes
](CNode
* pnode
) {
937 if (pnode
->nVersion
>= CADDR_TIME_VERSION
) {
938 uint64_t hashKey
= CSipHasher(hasher
).Write(pnode
->GetId()).Finalize();
939 for (unsigned int i
= 0; i
< nRelayNodes
; i
++) {
940 if (hashKey
> best
[i
].first
) {
941 std::copy(best
.begin() + i
, best
.begin() + nRelayNodes
- 1, best
.begin() + i
+ 1);
942 best
[i
] = std::make_pair(hashKey
, pnode
);
949 auto pushfunc
= [&addr
, &best
, nRelayNodes
, &insecure_rand
] {
950 for (unsigned int i
= 0; i
< nRelayNodes
&& best
[i
].first
!= 0; i
++) {
951 best
[i
].second
->PushAddress(addr
, insecure_rand
);
955 connman
.ForEachNodeThen(std::move(sortfunc
), std::move(pushfunc
));
958 void static ProcessGetData(CNode
* pfrom
, const Consensus::Params
& consensusParams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
960 std::deque
<CInv
>::iterator it
= pfrom
->vRecvGetData
.begin();
961 std::vector
<CInv
> vNotFound
;
962 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
965 while (it
!= pfrom
->vRecvGetData
.end()) {
966 // Don't bother if send buffer is too full to respond anyway
967 if (pfrom
->fPauseSend
)
970 const CInv
&inv
= *it
;
972 if (interruptMsgProc
)
977 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
980 BlockMap::iterator mi
= mapBlockIndex
.find(inv
.hash
);
981 std::shared_ptr
<const CBlock
> a_recent_block
;
982 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> a_recent_compact_block
;
983 bool fWitnessesPresentInARecentCompactBlock
;
985 LOCK(cs_most_recent_block
);
986 a_recent_block
= most_recent_block
;
987 a_recent_compact_block
= most_recent_compact_block
;
988 fWitnessesPresentInARecentCompactBlock
= fWitnessesPresentInMostRecentCompactBlock
;
990 if (mi
!= mapBlockIndex
.end())
992 if (mi
->second
->nChainTx
&& !mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) &&
993 mi
->second
->IsValid(BLOCK_VALID_TREE
)) {
994 // If we have the block and all of its parents, but have not yet validated it,
995 // we might be in the middle of connecting it (ie in the unlock of cs_main
996 // before ActivateBestChain but after AcceptBlock).
997 // In this case, we need to run ActivateBestChain prior to checking the relay
999 CValidationState dummy
;
1000 ActivateBestChain(dummy
, Params(), a_recent_block
);
1002 if (chainActive
.Contains(mi
->second
)) {
1005 static const int nOneMonth
= 30 * 24 * 60 * 60;
1006 // To prevent fingerprinting attacks, only send blocks outside of the active
1007 // chain if they are valid, and no more than a month older (both in time, and in
1008 // best equivalent proof of work) than the best header chain we know about.
1009 send
= mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) && (pindexBestHeader
!= NULL
) &&
1010 (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() < nOneMonth
) &&
1011 (GetBlockProofEquivalentTime(*pindexBestHeader
, *mi
->second
, *pindexBestHeader
, consensusParams
) < nOneMonth
);
1013 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
1017 // disconnect node in case we have reached the outbound limit for serving historical blocks
1018 // never disconnect whitelisted nodes
1019 static const int nOneWeek
= 7 * 24 * 60 * 60; // assume > 1 week = historical
1020 if (send
&& connman
.OutboundTargetReached(true) && ( ((pindexBestHeader
!= NULL
) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > nOneWeek
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
1022 LogPrint(BCLog::NET
, "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
1025 pfrom
->fDisconnect
= true;
1028 // Pruned nodes may have deleted the block, so check whether
1029 // it's available before trying to send.
1030 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
1032 std::shared_ptr
<const CBlock
> pblock
;
1033 if (a_recent_block
&& a_recent_block
->GetHash() == (*mi
).second
->GetBlockHash()) {
1034 pblock
= a_recent_block
;
1036 // Send block from disk
1037 std::shared_ptr
<CBlock
> pblockRead
= std::make_shared
<CBlock
>();
1038 if (!ReadBlockFromDisk(*pblockRead
, (*mi
).second
, consensusParams
))
1039 assert(!"cannot load block from disk");
1040 pblock
= pblockRead
;
1042 if (inv
.type
== MSG_BLOCK
)
1043 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, *pblock
));
1044 else if (inv
.type
== MSG_WITNESS_BLOCK
)
1045 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::BLOCK
, *pblock
));
1046 else if (inv
.type
== MSG_FILTERED_BLOCK
)
1048 bool sendMerkleBlock
= false;
1049 CMerkleBlock merkleBlock
;
1051 LOCK(pfrom
->cs_filter
);
1052 if (pfrom
->pfilter
) {
1053 sendMerkleBlock
= true;
1054 merkleBlock
= CMerkleBlock(*pblock
, *pfrom
->pfilter
);
1057 if (sendMerkleBlock
) {
1058 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::MERKLEBLOCK
, merkleBlock
));
1059 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1060 // This avoids hurting performance by pointlessly requiring a round-trip
1061 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1062 // they must either disconnect and retry or request the full block.
1063 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1064 // however we MUST always provide at least what the remote peer needs
1065 typedef std::pair
<unsigned int, uint256
> PairType
;
1066 for (PairType
& pair
: merkleBlock
.vMatchedTxn
)
1067 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, *pblock
->vtx
[pair
.first
]));
1072 else if (inv
.type
== MSG_CMPCT_BLOCK
)
1074 // If a peer is asking for old blocks, we're almost guaranteed
1075 // they won't have a useful mempool to match against a compact block,
1076 // and we don't feel like constructing the object for them, so
1077 // instead we respond with the full, non-compact block.
1078 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
1079 int nSendFlags
= fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1080 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
1081 if ((fPeerWantsWitness
|| !fWitnessesPresentInARecentCompactBlock
) && a_recent_compact_block
&& a_recent_compact_block
->header
.GetHash() == mi
->second
->GetBlockHash()) {
1082 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *a_recent_compact_block
));
1084 CBlockHeaderAndShortTxIDs
cmpctblock(*pblock
, fPeerWantsWitness
);
1085 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
1088 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCK
, *pblock
));
1092 // Trigger the peer node to send a getblocks request for the next batch of inventory
1093 if (inv
.hash
== pfrom
->hashContinue
)
1095 // Bypass PushInventory, this must send even if redundant,
1096 // and we want it right after the last block so they don't
1097 // wait for other stuff first.
1098 std::vector
<CInv
> vInv
;
1099 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
1100 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::INV
, vInv
));
1101 pfrom
->hashContinue
.SetNull();
1105 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
1107 // Send stream from relay memory
1109 auto mi
= mapRelay
.find(inv
.hash
);
1110 int nSendFlags
= (inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0);
1111 if (mi
!= mapRelay
.end()) {
1112 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *mi
->second
));
1114 } else if (pfrom
->timeLastMempoolReq
) {
1115 auto txinfo
= mempool
.info(inv
.hash
);
1116 // To protect privacy, do not answer getdata using the mempool when
1117 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1118 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
1119 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *txinfo
.tx
));
1124 vNotFound
.push_back(inv
);
1128 // Track requests for our stuff.
1129 GetMainSignals().Inventory(inv
.hash
);
1131 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1136 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
1138 if (!vNotFound
.empty()) {
1139 // Let the peer know that we didn't find what it asked for, so it doesn't
1140 // have to wait around forever. Currently only SPV clients actually care
1141 // about this message: it's needed when they are recursively walking the
1142 // dependencies of relevant unconfirmed transactions. SPV clients want to
1143 // do that because they want to know about (and store and rebroadcast and
1144 // risk analyze) the dependencies of transactions relevant to them, without
1145 // having to download the entire memory pool.
1146 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::NOTFOUND
, vNotFound
));
1150 uint32_t GetFetchFlags(CNode
* pfrom
) {
1151 uint32_t nFetchFlags
= 0;
1152 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
1153 nFetchFlags
|= MSG_WITNESS_FLAG
;
1158 inline void static SendBlockTransactions(const CBlock
& block
, const BlockTransactionsRequest
& req
, CNode
* pfrom
, CConnman
& connman
) {
1159 BlockTransactions
resp(req
);
1160 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
1161 if (req
.indexes
[i
] >= block
.vtx
.size()) {
1163 Misbehaving(pfrom
->GetId(), 100);
1164 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->GetId());
1167 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
1170 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1171 int nSendFlags
= State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1172 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCKTXN
, resp
));
1175 bool static ProcessMessage(CNode
* pfrom
, const std::string
& strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
1177 LogPrint(BCLog::NET
, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->GetId());
1178 if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
1180 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1185 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
1186 (strCommand
== NetMsgType::FILTERLOAD
||
1187 strCommand
== NetMsgType::FILTERADD
))
1189 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
1191 Misbehaving(pfrom
->GetId(), 100);
1194 pfrom
->fDisconnect
= true;
1199 if (strCommand
== NetMsgType::REJECT
)
1201 if (LogAcceptCategory(BCLog::NET
)) {
1203 std::string strMsg
; unsigned char ccode
; std::string strReason
;
1204 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
1206 std::ostringstream ss
;
1207 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
1209 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
1213 ss
<< ": hash " << hash
.ToString();
1215 LogPrint(BCLog::NET
, "Reject %s\n", SanitizeString(ss
.str()));
1216 } catch (const std::ios_base::failure
&) {
1217 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1218 LogPrint(BCLog::NET
, "Unparseable reject message received\n");
1223 else if (strCommand
== NetMsgType::VERSION
)
1225 // Each connection can only send one version message
1226 if (pfrom
->nVersion
!= 0)
1228 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, std::string("Duplicate version message")));
1230 Misbehaving(pfrom
->GetId(), 1);
1237 uint64_t nNonce
= 1;
1238 uint64_t nServiceInt
;
1239 ServiceFlags nServices
;
1242 std::string strSubVer
;
1243 std::string cleanSubVer
;
1244 int nStartingHeight
= -1;
1247 vRecv
>> nVersion
>> nServiceInt
>> nTime
>> addrMe
;
1248 nSendVersion
= std::min(nVersion
, PROTOCOL_VERSION
);
1249 nServices
= ServiceFlags(nServiceInt
);
1250 if (!pfrom
->fInbound
)
1252 connman
.SetServices(pfrom
->addr
, nServices
);
1254 if (pfrom
->nServicesExpected
& ~nServices
)
1256 LogPrint(BCLog::NET
, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->GetId(), nServices
, pfrom
->nServicesExpected
);
1257 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
1258 strprintf("Expected to offer services %08x", pfrom
->nServicesExpected
)));
1259 pfrom
->fDisconnect
= true;
1263 if (nServices
& ((1 << 7) | (1 << 5))) {
1264 if (GetTime() < 1533096000) {
1265 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1266 // These bits have been used as a flag to indicate that a node is running incompatible
1267 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1268 // based on these service bits, at least for a while.
1269 pfrom
->fDisconnect
= true;
1274 if (nVersion
< MIN_PEER_PROTO_VERSION
)
1276 // disconnect from peers older than this proto version
1277 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom
->GetId(), nVersion
);
1278 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
1279 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
)));
1280 pfrom
->fDisconnect
= true;
1284 if (nVersion
== 10300)
1287 vRecv
>> addrFrom
>> nNonce
;
1288 if (!vRecv
.empty()) {
1289 vRecv
>> LIMITED_STRING(strSubVer
, MAX_SUBVERSION_LENGTH
);
1290 cleanSubVer
= SanitizeString(strSubVer
);
1292 if (!vRecv
.empty()) {
1293 vRecv
>> nStartingHeight
;
1297 // Disconnect if we connected to ourself
1298 if (pfrom
->fInbound
&& !connman
.CheckIncomingNonce(nNonce
))
1300 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
1301 pfrom
->fDisconnect
= true;
1305 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
1310 // Be shy and don't send version until we hear
1311 if (pfrom
->fInbound
)
1312 PushNodeVersion(pfrom
, connman
, GetAdjustedTime());
1314 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERACK
));
1316 pfrom
->nServices
= nServices
;
1317 pfrom
->SetAddrLocal(addrMe
);
1319 LOCK(pfrom
->cs_SubVer
);
1320 pfrom
->strSubVer
= strSubVer
;
1321 pfrom
->cleanSubVer
= cleanSubVer
;
1323 pfrom
->nStartingHeight
= nStartingHeight
;
1324 pfrom
->fClient
= !(nServices
& NODE_NETWORK
);
1326 LOCK(pfrom
->cs_filter
);
1327 pfrom
->fRelayTxes
= fRelay
; // set to true after we get the first filter* message
1331 pfrom
->SetSendVersion(nSendVersion
);
1332 pfrom
->nVersion
= nVersion
;
1334 if((nServices
& NODE_WITNESS
))
1337 State(pfrom
->GetId())->fHaveWitness
= true;
1340 // Potentially mark this peer as a preferred download peer.
1343 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
1346 if (!pfrom
->fInbound
)
1348 // Advertise our address
1349 if (fListen
&& !IsInitialBlockDownload())
1351 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
1352 FastRandomContext insecure_rand
;
1353 if (addr
.IsRoutable())
1355 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1356 pfrom
->PushAddress(addr
, insecure_rand
);
1357 } else if (IsPeerAddrLocalGood(pfrom
)) {
1359 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1360 pfrom
->PushAddress(addr
, insecure_rand
);
1364 // Get recent addresses
1365 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
.GetAddressCount() < 1000)
1367 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make(NetMsgType::GETADDR
));
1368 pfrom
->fGetAddr
= true;
1370 connman
.MarkAddressGood(pfrom
->addr
);
1373 std::string remoteAddr
;
1375 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
1377 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1378 cleanSubVer
, pfrom
->nVersion
,
1379 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->GetId(),
1382 int64_t nTimeOffset
= nTime
- GetTime();
1383 pfrom
->nTimeOffset
= nTimeOffset
;
1384 AddTimeData(pfrom
->addr
, nTimeOffset
);
1386 // If the peer is old enough to have the old alert system, send it the final alert.
1387 if (pfrom
->nVersion
<= 70012) {
1388 CDataStream
finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK
, PROTOCOL_VERSION
);
1389 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make("alert", finalAlert
));
1392 // Feeler connections exist only to verify if address is online.
1393 if (pfrom
->fFeeler
) {
1394 assert(pfrom
->fInbound
== false);
1395 pfrom
->fDisconnect
= true;
1401 else if (pfrom
->nVersion
== 0)
1403 // Must have a version message before anything else
1405 Misbehaving(pfrom
->GetId(), 1);
1409 // At this point, the outgoing message serialization version can't change.
1410 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1412 if (strCommand
== NetMsgType::VERACK
)
1414 pfrom
->SetRecvVersion(std::min(pfrom
->nVersion
.load(), PROTOCOL_VERSION
));
1416 if (!pfrom
->fInbound
) {
1417 // Mark this node as currently connected, so we update its timestamp later.
1419 State(pfrom
->GetId())->fCurrentlyConnected
= true;
1422 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
1423 // Tell our peer we prefer to receive headers rather than inv's
1424 // We send this to non-NODE NETWORK peers as well, because even
1425 // non-NODE NETWORK peers can announce blocks (such as pruning
1427 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDHEADERS
));
1429 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
1430 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1431 // However, we do not request new block announcements using
1432 // cmpctblock messages.
1433 // We send this to non-NODE NETWORK peers as well, because
1434 // they may wish to request compact blocks from us
1435 bool fAnnounceUsingCMPCTBLOCK
= false;
1436 uint64_t nCMPCTBLOCKVersion
= 2;
1437 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1438 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1439 nCMPCTBLOCKVersion
= 1;
1440 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1442 pfrom
->fSuccessfullyConnected
= true;
1445 else if (!pfrom
->fSuccessfullyConnected
)
1447 // Must have a verack message before anything else
1449 Misbehaving(pfrom
->GetId(), 1);
1453 else if (strCommand
== NetMsgType::ADDR
)
1455 std::vector
<CAddress
> vAddr
;
1458 // Don't want addr from older versions unless seeding
1459 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
.GetAddressCount() > 1000)
1461 if (vAddr
.size() > 1000)
1464 Misbehaving(pfrom
->GetId(), 20);
1465 return error("message addr size() = %u", vAddr
.size());
1468 // Store the new addresses
1469 std::vector
<CAddress
> vAddrOk
;
1470 int64_t nNow
= GetAdjustedTime();
1471 int64_t nSince
= nNow
- 10 * 60;
1472 for (CAddress
& addr
: vAddr
)
1474 if (interruptMsgProc
)
1477 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1480 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
1481 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
1482 pfrom
->AddAddressKnown(addr
);
1483 bool fReachable
= IsReachable(addr
);
1484 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
1486 // Relay to a limited number of other nodes
1487 RelayAddress(addr
, fReachable
, connman
);
1489 // Do not store addresses outside our network
1491 vAddrOk
.push_back(addr
);
1493 connman
.AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
1494 if (vAddr
.size() < 1000)
1495 pfrom
->fGetAddr
= false;
1496 if (pfrom
->fOneShot
)
1497 pfrom
->fDisconnect
= true;
1500 else if (strCommand
== NetMsgType::SENDHEADERS
)
1503 State(pfrom
->GetId())->fPreferHeaders
= true;
1506 else if (strCommand
== NetMsgType::SENDCMPCT
)
1508 bool fAnnounceUsingCMPCTBLOCK
= false;
1509 uint64_t nCMPCTBLOCKVersion
= 0;
1510 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
1511 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
1513 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1514 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
1515 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
1516 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
1518 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
1519 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
1520 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
1521 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1522 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
1524 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
1530 else if (strCommand
== NetMsgType::INV
)
1532 std::vector
<CInv
> vInv
;
1534 if (vInv
.size() > MAX_INV_SZ
)
1537 Misbehaving(pfrom
->GetId(), 20);
1538 return error("message inv size() = %u", vInv
.size());
1541 bool fBlocksOnly
= !fRelayTxes
;
1543 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1544 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
1545 fBlocksOnly
= false;
1549 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1551 for (CInv
&inv
: vInv
)
1553 if (interruptMsgProc
)
1556 bool fAlreadyHave
= AlreadyHave(inv
);
1557 LogPrint(BCLog::NET
, "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->GetId());
1559 if (inv
.type
== MSG_TX
) {
1560 inv
.type
|= nFetchFlags
;
1563 if (inv
.type
== MSG_BLOCK
) {
1564 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
1565 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
1566 // We used to request the full block here, but since headers-announcements are now the
1567 // primary method of announcement on the network, and since, in the case that a node
1568 // fell back to inv we probably have a reorg which we should get the headers for first,
1569 // we now only provide a getheaders response here. When we receive the headers, we will
1570 // then ask for the blocks we need.
1571 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
));
1572 LogPrint(BCLog::NET
, "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->GetId());
1577 pfrom
->AddInventoryKnown(inv
);
1579 LogPrint(BCLog::NET
, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->GetId());
1580 } else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload()) {
1585 // Track requests for our stuff
1586 GetMainSignals().Inventory(inv
.hash
);
1591 else if (strCommand
== NetMsgType::GETDATA
)
1593 std::vector
<CInv
> vInv
;
1595 if (vInv
.size() > MAX_INV_SZ
)
1598 Misbehaving(pfrom
->GetId(), 20);
1599 return error("message getdata size() = %u", vInv
.size());
1602 LogPrint(BCLog::NET
, "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->GetId());
1604 if (vInv
.size() > 0) {
1605 LogPrint(BCLog::NET
, "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->GetId());
1608 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
1609 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1613 else if (strCommand
== NetMsgType::GETBLOCKS
)
1615 CBlockLocator locator
;
1617 vRecv
>> locator
>> hashStop
;
1619 // We might have announced the currently-being-connected tip using a
1620 // compact block, which resulted in the peer sending a getblocks
1621 // request, which we would otherwise respond to without the new block.
1622 // To avoid this situation we simply verify that we are on our best
1623 // known chain now. This is super overkill, but we handle it better
1624 // for getheaders requests, and there are no known nodes which support
1625 // compact blocks but still use getblocks to request blocks.
1627 std::shared_ptr
<const CBlock
> a_recent_block
;
1629 LOCK(cs_most_recent_block
);
1630 a_recent_block
= most_recent_block
;
1632 CValidationState dummy
;
1633 ActivateBestChain(dummy
, Params(), a_recent_block
);
1638 // Find the last block the caller has in the main chain
1639 const CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1641 // Send the rest of the chain
1643 pindex
= chainActive
.Next(pindex
);
1645 LogPrint(BCLog::NET
, "getblocks %d to %s limit %d from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), nLimit
, pfrom
->GetId());
1646 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1648 if (pindex
->GetBlockHash() == hashStop
)
1650 LogPrint(BCLog::NET
, " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1653 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1654 // for some reasonable time window (1 hour) that block relay might require.
1655 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
1656 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
1658 LogPrint(BCLog::NET
, " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1661 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
1664 // When this block is requested, we'll send an inv that'll
1665 // trigger the peer to getblocks the next batch of inventory.
1666 LogPrint(BCLog::NET
, " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1667 pfrom
->hashContinue
= pindex
->GetBlockHash();
1674 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
1676 BlockTransactionsRequest req
;
1679 std::shared_ptr
<const CBlock
> recent_block
;
1681 LOCK(cs_most_recent_block
);
1682 if (most_recent_block_hash
== req
.blockhash
)
1683 recent_block
= most_recent_block
;
1684 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1687 SendBlockTransactions(*recent_block
, req
, pfrom
, connman
);
1693 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
1694 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
1695 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom
->GetId());
1699 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
1700 // If an older block is requested (should never happen in practice,
1701 // but can happen in tests) send a block response instead of a
1702 // blocktxn response. Sending a full block response instead of a
1703 // small blocktxn response is preferable in the case where a peer
1704 // might maliciously send lots of getblocktxn requests to trigger
1705 // expensive disk reads, because it will require the peer to
1706 // actually receive all the data read from disk over the network.
1707 LogPrint(BCLog::NET
, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->GetId(), MAX_BLOCKTXN_DEPTH
);
1709 inv
.type
= State(pfrom
->GetId())->fWantsCmpctWitness
? MSG_WITNESS_BLOCK
: MSG_BLOCK
;
1710 inv
.hash
= req
.blockhash
;
1711 pfrom
->vRecvGetData
.push_back(inv
);
1712 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1717 bool ret
= ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus());
1720 SendBlockTransactions(block
, req
, pfrom
, connman
);
1724 else if (strCommand
== NetMsgType::GETHEADERS
)
1726 CBlockLocator locator
;
1728 vRecv
>> locator
>> hashStop
;
1731 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
1732 LogPrint(BCLog::NET
, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->GetId());
1736 CNodeState
*nodestate
= State(pfrom
->GetId());
1737 const CBlockIndex
* pindex
= NULL
;
1738 if (locator
.IsNull())
1740 // If locator is null, return the hashStop block
1741 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
1742 if (mi
== mapBlockIndex
.end())
1744 pindex
= (*mi
).second
;
1748 // Find the last block the caller has in the main chain
1749 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1751 pindex
= chainActive
.Next(pindex
);
1754 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1755 std::vector
<CBlock
> vHeaders
;
1756 int nLimit
= MAX_HEADERS_RESULTS
;
1757 LogPrint(BCLog::NET
, "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->GetId());
1758 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1760 vHeaders
.push_back(pindex
->GetBlockHeader());
1761 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
1764 // pindex can be NULL either if we sent chainActive.Tip() OR
1765 // if our peer has chainActive.Tip() (and thus we are sending an empty
1766 // headers message). In both cases it's safe to update
1767 // pindexBestHeaderSent to be our tip.
1769 // It is important that we simply reset the BestHeaderSent value here,
1770 // and not max(BestHeaderSent, newHeaderSent). We might have announced
1771 // the currently-being-connected tip using a compact block, which
1772 // resulted in the peer sending a headers request, which we respond to
1773 // without the new block. By resetting the BestHeaderSent, we ensure we
1774 // will re-announce the new block via headers (or compact blocks again)
1775 // in the SendMessages logic.
1776 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
1777 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
1781 else if (strCommand
== NetMsgType::TX
)
1783 // Stop processing the transaction early if
1784 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1785 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
1787 LogPrint(BCLog::NET
, "transaction sent in violation of protocol peer=%d\n", pfrom
->GetId());
1791 std::deque
<COutPoint
> vWorkQueue
;
1792 std::vector
<uint256
> vEraseQueue
;
1793 CTransactionRef ptx
;
1795 const CTransaction
& tx
= *ptx
;
1797 CInv
inv(MSG_TX
, tx
.GetHash());
1798 pfrom
->AddInventoryKnown(inv
);
1802 bool fMissingInputs
= false;
1803 CValidationState state
;
1805 pfrom
->setAskFor
.erase(inv
.hash
);
1806 mapAlreadyAskedFor
.erase(inv
.hash
);
1808 std::list
<CTransactionRef
> lRemovedTxn
;
1810 if (!AlreadyHave(inv
) && AcceptToMemoryPool(mempool
, state
, ptx
, true, &fMissingInputs
, &lRemovedTxn
)) {
1811 mempool
.check(pcoinsTip
);
1812 RelayTransaction(tx
, connman
);
1813 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
1814 vWorkQueue
.emplace_back(inv
.hash
, i
);
1817 pfrom
->nLastTXTime
= GetTime();
1819 LogPrint(BCLog::MEMPOOL
, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1821 tx
.GetHash().ToString(),
1822 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
1824 // Recursively process any orphan transactions that depended on this one
1825 std::set
<NodeId
> setMisbehaving
;
1826 while (!vWorkQueue
.empty()) {
1827 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
1828 vWorkQueue
.pop_front();
1829 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
1831 for (auto mi
= itByPrev
->second
.begin();
1832 mi
!= itByPrev
->second
.end();
1835 const CTransactionRef
& porphanTx
= (*mi
)->second
.tx
;
1836 const CTransaction
& orphanTx
= *porphanTx
;
1837 const uint256
& orphanHash
= orphanTx
.GetHash();
1838 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
1839 bool fMissingInputs2
= false;
1840 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1841 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1842 // anyone relaying LegitTxX banned)
1843 CValidationState stateDummy
;
1846 if (setMisbehaving
.count(fromPeer
))
1848 if (AcceptToMemoryPool(mempool
, stateDummy
, porphanTx
, true, &fMissingInputs2
, &lRemovedTxn
)) {
1849 LogPrint(BCLog::MEMPOOL
, " accepted orphan tx %s\n", orphanHash
.ToString());
1850 RelayTransaction(orphanTx
, connman
);
1851 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
1852 vWorkQueue
.emplace_back(orphanHash
, i
);
1854 vEraseQueue
.push_back(orphanHash
);
1856 else if (!fMissingInputs2
)
1859 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
1861 // Punish peer that gave us an invalid orphan tx
1862 Misbehaving(fromPeer
, nDos
);
1863 setMisbehaving
.insert(fromPeer
);
1864 LogPrint(BCLog::MEMPOOL
, " invalid orphan tx %s\n", orphanHash
.ToString());
1866 // Has inputs but not accepted to mempool
1867 // Probably non-standard or insufficient fee
1868 LogPrint(BCLog::MEMPOOL
, " removed orphan tx %s\n", orphanHash
.ToString());
1869 vEraseQueue
.push_back(orphanHash
);
1870 if (!orphanTx
.HasWitness() && !stateDummy
.CorruptionPossible()) {
1871 // Do not use rejection cache for witness transactions or
1872 // witness-stripped transactions, as they can have been malleated.
1873 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1874 assert(recentRejects
);
1875 recentRejects
->insert(orphanHash
);
1878 mempool
.check(pcoinsTip
);
1882 for (uint256 hash
: vEraseQueue
)
1883 EraseOrphanTx(hash
);
1885 else if (fMissingInputs
)
1887 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
1888 for (const CTxIn
& txin
: tx
.vin
) {
1889 if (recentRejects
->contains(txin
.prevout
.hash
)) {
1890 fRejectedParents
= true;
1894 if (!fRejectedParents
) {
1895 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1896 for (const CTxIn
& txin
: tx
.vin
) {
1897 CInv
_inv(MSG_TX
| nFetchFlags
, txin
.prevout
.hash
);
1898 pfrom
->AddInventoryKnown(_inv
);
1899 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
1901 AddOrphanTx(ptx
, pfrom
->GetId());
1903 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1904 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
1905 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
1907 LogPrint(BCLog::MEMPOOL
, "mapOrphan overflow, removed %u tx\n", nEvicted
);
1910 LogPrint(BCLog::MEMPOOL
, "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
1911 // We will continue to reject this tx since it has rejected
1912 // parents so avoid re-requesting it from other peers.
1913 recentRejects
->insert(tx
.GetHash());
1916 if (!tx
.HasWitness() && !state
.CorruptionPossible()) {
1917 // Do not use rejection cache for witness transactions or
1918 // witness-stripped transactions, as they can have been malleated.
1919 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1920 assert(recentRejects
);
1921 recentRejects
->insert(tx
.GetHash());
1922 if (RecursiveDynamicUsage(*ptx
) < 100000) {
1923 AddToCompactExtraTransactions(ptx
);
1925 } else if (tx
.HasWitness() && RecursiveDynamicUsage(*ptx
) < 100000) {
1926 AddToCompactExtraTransactions(ptx
);
1929 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
1930 // Always relay transactions received from whitelisted peers, even
1931 // if they were already in the mempool or rejected from it due
1932 // to policy, allowing the node to function as a gateway for
1933 // nodes hidden behind it.
1935 // Never relay transactions that we would assign a non-zero DoS
1936 // score for, as we expect peers to do the same with us in that
1939 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
1940 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->GetId());
1941 RelayTransaction(tx
, connman
);
1943 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->GetId(), FormatStateMessage(state
));
1948 for (const CTransactionRef
& removedTx
: lRemovedTxn
)
1949 AddToCompactExtraTransactions(removedTx
);
1952 if (state
.IsInvalid(nDoS
))
1954 LogPrint(BCLog::MEMPOOLREJ
, "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
1956 FormatStateMessage(state
));
1957 if (state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
1958 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
1959 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
));
1961 Misbehaving(pfrom
->GetId(), nDoS
);
1967 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
1969 CBlockHeaderAndShortTxIDs cmpctblock
;
1970 vRecv
>> cmpctblock
;
1975 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
1976 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1977 if (!IsInitialBlockDownload())
1978 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
1983 const CBlockIndex
*pindex
= NULL
;
1984 CValidationState state
;
1985 if (!ProcessNewBlockHeaders({cmpctblock
.header
}, state
, chainparams
, &pindex
)) {
1987 if (state
.IsInvalid(nDoS
)) {
1990 Misbehaving(pfrom
->GetId(), nDoS
);
1992 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->GetId());
1997 // When we succeed in decoding a block's txids from a cmpctblock
1998 // message we typically jump to the BLOCKTXN handling code, with a
1999 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2000 // completing processing of the putative block (without cs_main).
2001 bool fProcessBLOCKTXN
= false;
2002 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2004 // If we end up treating this as a plain headers message, call that as well
2006 bool fRevertToHeaderProcessing
= false;
2007 CDataStream
vHeadersMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2009 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2011 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2012 bool fBlockReconstructed
= false;
2016 // If AcceptBlockHeader returned true, it set pindex
2018 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
2020 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
2021 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
2023 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
2026 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
2027 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
2028 if (fAlreadyInFlight
) {
2029 // We requested this block for some reason, but our mempool will probably be useless
2030 // so we just grab the block via normal getdata
2031 std::vector
<CInv
> vInv(1);
2032 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2033 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2038 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2039 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
2042 CNodeState
*nodestate
= State(pfrom
->GetId());
2044 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
2045 // Don't bother trying to process compact blocks from v1 peers
2046 // after segwit activates.
2050 // We want to be a bit conservative just to be extra careful about DoS
2051 // possibilities in compact block processing...
2052 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
2053 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
2054 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
2055 std::list
<QueuedBlock
>::iterator
* queuedBlockIt
= NULL
;
2056 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
, &queuedBlockIt
)) {
2057 if (!(*queuedBlockIt
)->partialBlock
)
2058 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
2060 // The block was already in flight using compact blocks from the same peer
2061 LogPrint(BCLog::NET
, "Peer sent us compact block we were already syncing!\n");
2066 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
2067 ReadStatus status
= partialBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2068 if (status
== READ_STATUS_INVALID
) {
2069 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
2070 Misbehaving(pfrom
->GetId(), 100);
2071 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->GetId());
2073 } else if (status
== READ_STATUS_FAILED
) {
2074 // Duplicate txindexes, the block is now in-flight, so just request it
2075 std::vector
<CInv
> vInv(1);
2076 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2077 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2081 BlockTransactionsRequest req
;
2082 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
2083 if (!partialBlock
.IsTxAvailable(i
))
2084 req
.indexes
.push_back(i
);
2086 if (req
.indexes
.empty()) {
2087 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2088 BlockTransactions txn
;
2089 txn
.blockhash
= cmpctblock
.header
.GetHash();
2091 fProcessBLOCKTXN
= true;
2093 req
.blockhash
= pindex
->GetBlockHash();
2094 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETBLOCKTXN
, req
));
2097 // This block is either already in flight from a different
2098 // peer, or this peer has too many blocks outstanding to
2100 // Optimistically try to reconstruct anyway since we might be
2101 // able to without any round trips.
2102 PartiallyDownloadedBlock
tempBlock(&mempool
);
2103 ReadStatus status
= tempBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2104 if (status
!= READ_STATUS_OK
) {
2105 // TODO: don't ignore failures
2108 std::vector
<CTransactionRef
> dummy
;
2109 status
= tempBlock
.FillBlock(*pblock
, dummy
);
2110 if (status
== READ_STATUS_OK
) {
2111 fBlockReconstructed
= true;
2115 if (fAlreadyInFlight
) {
2116 // We requested this block, but its far into the future, so our
2117 // mempool will probably be useless - request the block normally
2118 std::vector
<CInv
> vInv(1);
2119 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2120 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2123 // If this was an announce-cmpctblock, we want the same treatment as a header message
2124 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
2125 std::vector
<CBlock
> headers
;
2126 headers
.push_back(cmpctblock
.header
);
2127 vHeadersMsg
<< headers
;
2128 fRevertToHeaderProcessing
= true;
2133 if (fProcessBLOCKTXN
)
2134 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2136 if (fRevertToHeaderProcessing
)
2137 return ProcessMessage(pfrom
, NetMsgType::HEADERS
, vHeadersMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2139 if (fBlockReconstructed
) {
2140 // If we got here, we were able to optimistically reconstruct a
2141 // block that is in flight from some other peer.
2144 mapBlockSource
.emplace(pblock
->GetHash(), std::make_pair(pfrom
->GetId(), false));
2146 bool fNewBlock
= false;
2147 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2149 pfrom
->nLastBlockTime
= GetTime();
2151 LOCK(cs_main
); // hold cs_main for CBlockIndex::IsValid()
2152 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
)) {
2153 // Clear download state for this block, which is in
2154 // process from some other peer. We do this after calling
2155 // ProcessNewBlock so that a malleated cmpctblock announcement
2156 // can't be used to interfere with block relay.
2157 MarkBlockAsReceived(pblock
->GetHash());
2163 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2165 BlockTransactions resp
;
2168 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2169 bool fBlockRead
= false;
2173 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
2174 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
2175 it
->second
.first
!= pfrom
->GetId()) {
2176 LogPrint(BCLog::NET
, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->GetId());
2180 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
2181 ReadStatus status
= partialBlock
.FillBlock(*pblock
, resp
.txn
);
2182 if (status
== READ_STATUS_INVALID
) {
2183 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
2184 Misbehaving(pfrom
->GetId(), 100);
2185 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->GetId());
2187 } else if (status
== READ_STATUS_FAILED
) {
2188 // Might have collided, fall back to getdata now :(
2189 std::vector
<CInv
> invs
;
2190 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), resp
.blockhash
));
2191 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, invs
));
2193 // Block is either okay, or possibly we received
2194 // READ_STATUS_CHECKBLOCK_FAILED.
2195 // Note that CheckBlock can only fail for one of a few reasons:
2196 // 1. bad-proof-of-work (impossible here, because we've already
2197 // accepted the header)
2198 // 2. merkleroot doesn't match the transactions given (already
2199 // caught in FillBlock with READ_STATUS_FAILED, so
2201 // 3. the block is otherwise invalid (eg invalid coinbase,
2202 // block is too big, too many legacy sigops, etc).
2203 // So if CheckBlock failed, #3 is the only possibility.
2204 // Under BIP 152, we don't DoS-ban unless proof of work is
2205 // invalid (we don't require all the stateless checks to have
2206 // been run). This is handled below, so just treat this as
2207 // though the block was successfully read, and rely on the
2208 // handling in ProcessNewBlock to ensure the block index is
2209 // updated, reject messages go out, etc.
2210 MarkBlockAsReceived(resp
.blockhash
); // it is now an empty pointer
2212 // mapBlockSource is only used for sending reject messages and DoS scores,
2213 // so the race between here and cs_main in ProcessNewBlock is fine.
2214 // BIP 152 permits peers to relay compact blocks after validating
2215 // the header only; we should not punish peers if the block turns
2216 // out to be invalid.
2217 mapBlockSource
.emplace(resp
.blockhash
, std::make_pair(pfrom
->GetId(), false));
2219 } // Don't hold cs_main when we call into ProcessNewBlock
2221 bool fNewBlock
= false;
2222 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2223 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2224 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2226 pfrom
->nLastBlockTime
= GetTime();
2231 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
2233 std::vector
<CBlockHeader
> headers
;
2235 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2236 unsigned int nCount
= ReadCompactSize(vRecv
);
2237 if (nCount
> MAX_HEADERS_RESULTS
) {
2239 Misbehaving(pfrom
->GetId(), 20);
2240 return error("headers message size = %u", nCount
);
2242 headers
.resize(nCount
);
2243 for (unsigned int n
= 0; n
< nCount
; n
++) {
2244 vRecv
>> headers
[n
];
2245 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
2249 // Nothing interesting. Stop asking this peers for more headers.
2253 const CBlockIndex
*pindexLast
= NULL
;
2256 CNodeState
*nodestate
= State(pfrom
->GetId());
2258 // If this looks like it could be a block announcement (nCount <
2259 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2261 // - Send a getheaders message in response to try to connect the chain.
2262 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2263 // don't connect before giving DoS points
2264 // - Once a headers message is received that is valid and does connect,
2265 // nUnconnectingHeaders gets reset back to 0.
2266 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
2267 nodestate
->nUnconnectingHeaders
++;
2268 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
2269 LogPrint(BCLog::NET
, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2270 headers
[0].GetHash().ToString(),
2271 headers
[0].hashPrevBlock
.ToString(),
2272 pindexBestHeader
->nHeight
,
2273 pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
2274 // Set hashLastUnknownBlock for this peer, so that if we
2275 // eventually get the headers - even from a different peer -
2276 // we can use this peer to download.
2277 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
2279 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
2280 Misbehaving(pfrom
->GetId(), 20);
2285 uint256 hashLastBlock
;
2286 for (const CBlockHeader
& header
: headers
) {
2287 if (!hashLastBlock
.IsNull() && header
.hashPrevBlock
!= hashLastBlock
) {
2288 Misbehaving(pfrom
->GetId(), 20);
2289 return error("non-continuous headers sequence");
2291 hashLastBlock
= header
.GetHash();
2295 CValidationState state
;
2296 if (!ProcessNewBlockHeaders(headers
, state
, chainparams
, &pindexLast
)) {
2298 if (state
.IsInvalid(nDoS
)) {
2301 Misbehaving(pfrom
->GetId(), nDoS
);
2303 return error("invalid header received");
2309 CNodeState
*nodestate
= State(pfrom
->GetId());
2310 if (nodestate
->nUnconnectingHeaders
> 0) {
2311 LogPrint(BCLog::NET
, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
2313 nodestate
->nUnconnectingHeaders
= 0;
2316 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
2318 if (nCount
== MAX_HEADERS_RESULTS
) {
2319 // Headers message had its maximum size; the peer may have more headers.
2320 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2321 // from there instead.
2322 LogPrint(BCLog::NET
, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->GetId(), pfrom
->nStartingHeight
);
2323 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256()));
2326 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
2327 // If this set of headers is valid and ends in a block with at least as
2328 // much work as our tip, download as much as possible.
2329 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
2330 std::vector
<const CBlockIndex
*> vToFetch
;
2331 const CBlockIndex
*pindexWalk
= pindexLast
;
2332 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2333 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2334 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
2335 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
2336 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
2337 // We don't have this block, and it's not yet in flight.
2338 vToFetch
.push_back(pindexWalk
);
2340 pindexWalk
= pindexWalk
->pprev
;
2342 // If pindexWalk still isn't on our main chain, we're looking at a
2343 // very large reorg at a time we think we're close to caught up to
2344 // the main chain -- this shouldn't really happen. Bail out on the
2345 // direct fetch and rely on parallel download instead.
2346 if (!chainActive
.Contains(pindexWalk
)) {
2347 LogPrint(BCLog::NET
, "Large reorg, won't direct fetch to %s (%d)\n",
2348 pindexLast
->GetBlockHash().ToString(),
2349 pindexLast
->nHeight
);
2351 std::vector
<CInv
> vGetData
;
2352 // Download as much as possible, from earliest to latest.
2353 for (const CBlockIndex
*pindex
: reverse_iterate(vToFetch
)) {
2354 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2355 // Can't download any more from this peer
2358 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
2359 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
2360 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
);
2361 LogPrint(BCLog::NET
, "Requesting block %s from peer=%d\n",
2362 pindex
->GetBlockHash().ToString(), pfrom
->GetId());
2364 if (vGetData
.size() > 1) {
2365 LogPrint(BCLog::NET
, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2366 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
2368 if (vGetData
.size() > 0) {
2369 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
2370 // In any case, we want to download using a compact block, not a regular one
2371 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
2373 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
2380 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2382 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2385 LogPrint(BCLog::NET
, "received block %s peer=%d\n", pblock
->GetHash().ToString(), pfrom
->GetId());
2387 // Process all blocks from whitelisted peers, even if not requested,
2388 // unless we're still syncing with the network.
2389 // Such an unrequested block may still be processed, subject to the
2390 // conditions in AcceptBlock().
2391 bool forceProcessing
= pfrom
->fWhitelisted
&& !IsInitialBlockDownload();
2392 const uint256
hash(pblock
->GetHash());
2395 // Also always process if we requested the block explicitly, as we may
2396 // need it even though it is not a candidate for a new best tip.
2397 forceProcessing
|= MarkBlockAsReceived(hash
);
2398 // mapBlockSource is only used for sending reject messages and DoS scores,
2399 // so the race between here and cs_main in ProcessNewBlock is fine.
2400 mapBlockSource
.emplace(hash
, std::make_pair(pfrom
->GetId(), true));
2402 bool fNewBlock
= false;
2403 ProcessNewBlock(chainparams
, pblock
, forceProcessing
, &fNewBlock
);
2405 pfrom
->nLastBlockTime
= GetTime();
2409 else if (strCommand
== NetMsgType::GETADDR
)
2411 // This asymmetric behavior for inbound and outbound connections was introduced
2412 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2413 // to users' AddrMan and later request them by sending getaddr messages.
2414 // Making nodes which are behind NAT and can only make outgoing connections ignore
2415 // the getaddr message mitigates the attack.
2416 if (!pfrom
->fInbound
) {
2417 LogPrint(BCLog::NET
, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->GetId());
2421 // Only send one GetAddr response per connection to reduce resource waste
2422 // and discourage addr stamping of INV announcements.
2423 if (pfrom
->fSentAddr
) {
2424 LogPrint(BCLog::NET
, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->GetId());
2427 pfrom
->fSentAddr
= true;
2429 pfrom
->vAddrToSend
.clear();
2430 std::vector
<CAddress
> vAddr
= connman
.GetAddresses();
2431 FastRandomContext insecure_rand
;
2432 for (const CAddress
&addr
: vAddr
)
2433 pfrom
->PushAddress(addr
, insecure_rand
);
2437 else if (strCommand
== NetMsgType::MEMPOOL
)
2439 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
2441 LogPrint(BCLog::NET
, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
2442 pfrom
->fDisconnect
= true;
2446 if (connman
.OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
2448 LogPrint(BCLog::NET
, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
2449 pfrom
->fDisconnect
= true;
2453 LOCK(pfrom
->cs_inventory
);
2454 pfrom
->fSendMempool
= true;
2458 else if (strCommand
== NetMsgType::PING
)
2460 if (pfrom
->nVersion
> BIP0031_VERSION
)
2464 // Echo the message back with the nonce. This allows for two useful features:
2466 // 1) A remote node can quickly check if the connection is operational
2467 // 2) Remote nodes can measure the latency of the network thread. If this node
2468 // is overloaded it won't respond to pings quickly and the remote node can
2469 // avoid sending us more work, like chain download requests.
2471 // The nonce stops the remote getting confused between different pings: without
2472 // it, if the remote node sends a ping once per second and this node takes 5
2473 // seconds to respond to each, the 5th ping the remote sends would appear to
2474 // return very quickly.
2475 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::PONG
, nonce
));
2480 else if (strCommand
== NetMsgType::PONG
)
2482 int64_t pingUsecEnd
= nTimeReceived
;
2484 size_t nAvail
= vRecv
.in_avail();
2485 bool bPingFinished
= false;
2486 std::string sProblem
;
2488 if (nAvail
>= sizeof(nonce
)) {
2491 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2492 if (pfrom
->nPingNonceSent
!= 0) {
2493 if (nonce
== pfrom
->nPingNonceSent
) {
2494 // Matching pong received, this ping is no longer outstanding
2495 bPingFinished
= true;
2496 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
2497 if (pingUsecTime
> 0) {
2498 // Successful ping time measurement, replace previous
2499 pfrom
->nPingUsecTime
= pingUsecTime
;
2500 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
.load(), pingUsecTime
);
2502 // This should never happen
2503 sProblem
= "Timing mishap";
2506 // Nonce mismatches are normal when pings are overlapping
2507 sProblem
= "Nonce mismatch";
2509 // This is most likely a bug in another implementation somewhere; cancel this ping
2510 bPingFinished
= true;
2511 sProblem
= "Nonce zero";
2515 sProblem
= "Unsolicited pong without ping";
2518 // This is most likely a bug in another implementation somewhere; cancel this ping
2519 bPingFinished
= true;
2520 sProblem
= "Short payload";
2523 if (!(sProblem
.empty())) {
2524 LogPrint(BCLog::NET
, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2527 pfrom
->nPingNonceSent
,
2531 if (bPingFinished
) {
2532 pfrom
->nPingNonceSent
= 0;
2537 else if (strCommand
== NetMsgType::FILTERLOAD
)
2539 CBloomFilter filter
;
2542 if (!filter
.IsWithinSizeConstraints())
2544 // There is no excuse for sending a too-large filter
2546 Misbehaving(pfrom
->GetId(), 100);
2550 LOCK(pfrom
->cs_filter
);
2551 delete pfrom
->pfilter
;
2552 pfrom
->pfilter
= new CBloomFilter(filter
);
2553 pfrom
->pfilter
->UpdateEmptyFull();
2554 pfrom
->fRelayTxes
= true;
2559 else if (strCommand
== NetMsgType::FILTERADD
)
2561 std::vector
<unsigned char> vData
;
2564 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2565 // and thus, the maximum size any matched object can have) in a filteradd message
2567 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
2570 LOCK(pfrom
->cs_filter
);
2571 if (pfrom
->pfilter
) {
2572 pfrom
->pfilter
->insert(vData
);
2579 Misbehaving(pfrom
->GetId(), 100);
2584 else if (strCommand
== NetMsgType::FILTERCLEAR
)
2586 LOCK(pfrom
->cs_filter
);
2587 if (pfrom
->GetLocalServices() & NODE_BLOOM
) {
2588 delete pfrom
->pfilter
;
2589 pfrom
->pfilter
= new CBloomFilter();
2591 pfrom
->fRelayTxes
= true;
2594 else if (strCommand
== NetMsgType::FEEFILTER
) {
2595 CAmount newFeeFilter
= 0;
2596 vRecv
>> newFeeFilter
;
2597 if (MoneyRange(newFeeFilter
)) {
2599 LOCK(pfrom
->cs_feeFilter
);
2600 pfrom
->minFeeFilter
= newFeeFilter
;
2602 LogPrint(BCLog::NET
, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->GetId());
2606 else if (strCommand
== NetMsgType::NOTFOUND
) {
2607 // We do not care about the NOTFOUND message, but logging an Unknown Command
2608 // message would be undesirable as we transmit it ourselves.
2612 // Ignore unknown commands for extensibility
2613 LogPrint(BCLog::NET
, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->GetId());
2621 static bool SendRejectsAndCheckIfBanned(CNode
* pnode
, CConnman
& connman
)
2623 AssertLockHeld(cs_main
);
2624 CNodeState
&state
= *State(pnode
->GetId());
2626 for (const CBlockReject
& reject
: state
.rejects
) {
2627 connman
.PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, (std::string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
));
2629 state
.rejects
.clear();
2631 if (state
.fShouldBan
) {
2632 state
.fShouldBan
= false;
2633 if (pnode
->fWhitelisted
)
2634 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode
->addr
.ToString());
2635 else if (pnode
->fAddnode
)
2636 LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode
->addr
.ToString());
2638 pnode
->fDisconnect
= true;
2639 if (pnode
->addr
.IsLocal())
2640 LogPrintf("Warning: not banning local peer %s!\n", pnode
->addr
.ToString());
2643 connman
.Ban(pnode
->addr
, BanReasonNodeMisbehaving
);
2651 bool ProcessMessages(CNode
* pfrom
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2653 const CChainParams
& chainparams
= Params();
2656 // (4) message start
2662 bool fMoreWork
= false;
2664 if (!pfrom
->vRecvGetData
.empty())
2665 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2667 if (pfrom
->fDisconnect
)
2670 // this maintains the order of responses
2671 if (!pfrom
->vRecvGetData
.empty()) return true;
2673 // Don't bother if send buffer is too full to respond anyway
2674 if (pfrom
->fPauseSend
)
2677 std::list
<CNetMessage
> msgs
;
2679 LOCK(pfrom
->cs_vProcessMsg
);
2680 if (pfrom
->vProcessMsg
.empty())
2682 // Just take one message
2683 msgs
.splice(msgs
.begin(), pfrom
->vProcessMsg
, pfrom
->vProcessMsg
.begin());
2684 pfrom
->nProcessQueueSize
-= msgs
.front().vRecv
.size() + CMessageHeader::HEADER_SIZE
;
2685 pfrom
->fPauseRecv
= pfrom
->nProcessQueueSize
> connman
.GetReceiveFloodSize();
2686 fMoreWork
= !pfrom
->vProcessMsg
.empty();
2688 CNetMessage
& msg(msgs
.front());
2690 msg
.SetVersion(pfrom
->GetRecvVersion());
2691 // Scan for message start
2692 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
2693 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->GetId());
2694 pfrom
->fDisconnect
= true;
2699 CMessageHeader
& hdr
= msg
.hdr
;
2700 if (!hdr
.IsValid(chainparams
.MessageStart()))
2702 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->GetId());
2705 std::string strCommand
= hdr
.GetCommand();
2708 unsigned int nMessageSize
= hdr
.nMessageSize
;
2711 CDataStream
& vRecv
= msg
.vRecv
;
2712 const uint256
& hash
= msg
.GetMessageHash();
2713 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
2715 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
2716 SanitizeString(strCommand
), nMessageSize
,
2717 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
2718 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
2726 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
, interruptMsgProc
);
2727 if (interruptMsgProc
)
2729 if (!pfrom
->vRecvGetData
.empty())
2732 catch (const std::ios_base::failure
& e
)
2734 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, std::string("error parsing message")));
2735 if (strstr(e
.what(), "end of data"))
2737 // Allow exceptions from under-length message on vRecv
2738 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());
2740 else if (strstr(e
.what(), "size too large"))
2742 // Allow exceptions from over-long size
2743 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2745 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
2747 // Allow exceptions from non-canonical encoding
2748 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2752 PrintExceptionContinue(&e
, "ProcessMessages()");
2755 catch (const std::exception
& e
) {
2756 PrintExceptionContinue(&e
, "ProcessMessages()");
2758 PrintExceptionContinue(NULL
, "ProcessMessages()");
2762 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->GetId());
2766 SendRejectsAndCheckIfBanned(pfrom
, connman
);
2771 class CompareInvMempoolOrder
2775 CompareInvMempoolOrder(CTxMemPool
*_mempool
)
2780 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
2782 /* As std::make_heap produces a max-heap, we want the entries with the
2783 * fewest ancestors/highest fee to sort later. */
2784 return mp
->CompareDepthAndScore(*b
, *a
);
2788 bool SendMessages(CNode
* pto
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2790 const Consensus::Params
& consensusParams
= Params().GetConsensus();
2792 // Don't send anything until the version handshake is complete
2793 if (!pto
->fSuccessfullyConnected
|| pto
->fDisconnect
)
2796 // If we get here, the outgoing message serialization version is set and can't change.
2797 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
2802 bool pingSend
= false;
2803 if (pto
->fPingQueued
) {
2804 // RPC ping request by user
2807 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
2808 // Ping automatically sent as a latency probe & keepalive.
2813 while (nonce
== 0) {
2814 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
2816 pto
->fPingQueued
= false;
2817 pto
->nPingUsecStart
= GetTimeMicros();
2818 if (pto
->nVersion
> BIP0031_VERSION
) {
2819 pto
->nPingNonceSent
= nonce
;
2820 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
, nonce
));
2822 // Peer is too old to support ping command with nonce, pong will never arrive.
2823 pto
->nPingNonceSent
= 0;
2824 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
));
2828 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2832 if (SendRejectsAndCheckIfBanned(pto
, connman
))
2834 CNodeState
&state
= *State(pto
->GetId());
2836 // Address refresh broadcast
2837 int64_t nNow
= GetTimeMicros();
2838 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
2839 AdvertiseLocal(pto
);
2840 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
2846 if (pto
->nNextAddrSend
< nNow
) {
2847 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
2848 std::vector
<CAddress
> vAddr
;
2849 vAddr
.reserve(pto
->vAddrToSend
.size());
2850 for (const CAddress
& addr
: pto
->vAddrToSend
)
2852 if (!pto
->addrKnown
.contains(addr
.GetKey()))
2854 pto
->addrKnown
.insert(addr
.GetKey());
2855 vAddr
.push_back(addr
);
2856 // receiver rejects addr messages larger than 1000
2857 if (vAddr
.size() >= 1000)
2859 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2864 pto
->vAddrToSend
.clear();
2866 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2867 // we only send the big addr message once
2868 if (pto
->vAddrToSend
.capacity() > 40)
2869 pto
->vAddrToSend
.shrink_to_fit();
2873 if (pindexBestHeader
== NULL
)
2874 pindexBestHeader
= chainActive
.Tip();
2875 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.
2876 if (!state
.fSyncStarted
&& !pto
->fClient
&& !fImporting
&& !fReindex
) {
2877 // Only actively request headers from a single peer, unless we're close to today.
2878 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2879 state
.fSyncStarted
= true;
2880 state
.nHeadersSyncTimeout
= GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE
+ HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
* (GetAdjustedTime() - pindexBestHeader
->GetBlockTime())/(consensusParams
.nPowTargetSpacing
);
2882 const CBlockIndex
*pindexStart
= pindexBestHeader
;
2883 /* If possible, start at the block preceding the currently
2884 best known header. This ensures that we always get a
2885 non-empty list of headers back as long as the peer
2886 is up-to-date. With a non-empty response, we can initialise
2887 the peer's known best block. This wouldn't be possible
2888 if we requested starting at pindexBestHeader and
2889 got back an empty response. */
2890 if (pindexStart
->pprev
)
2891 pindexStart
= pindexStart
->pprev
;
2892 LogPrint(BCLog::NET
, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->GetId(), pto
->nStartingHeight
);
2893 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256()));
2897 // Resend wallet transactions that haven't gotten in a block yet
2898 // Except during reindex, importing and IBD, when old wallet
2899 // transactions become unconfirmed and spams other nodes.
2900 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
2902 GetMainSignals().Broadcast(nTimeBestReceived
, &connman
);
2906 // Try sending block announcements via headers
2909 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2910 // list of block hashes we're relaying, and our peer wants
2911 // headers announcements, then find the first header
2912 // not yet known to our peer but would connect, and send.
2913 // If no header would connect, or if we have too many
2914 // blocks, or if the peer doesn't want headers, just
2915 // add all to the inv queue.
2916 LOCK(pto
->cs_inventory
);
2917 std::vector
<CBlock
> vHeaders
;
2918 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
2919 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
2920 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
2921 const CBlockIndex
*pBestIndex
= NULL
; // last header queued for delivery
2922 ProcessBlockAvailability(pto
->GetId()); // ensure pindexBestKnownBlock is up-to-date
2924 if (!fRevertToInv
) {
2925 bool fFoundStartingHeader
= false;
2926 // Try to find first header that our peer doesn't have, and
2927 // then send all headers past that one. If we come across any
2928 // headers that aren't on chainActive, give up.
2929 for (const uint256
&hash
: pto
->vBlockHashesToAnnounce
) {
2930 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
2931 assert(mi
!= mapBlockIndex
.end());
2932 const CBlockIndex
*pindex
= mi
->second
;
2933 if (chainActive
[pindex
->nHeight
] != pindex
) {
2934 // Bail out if we reorged away from this block
2935 fRevertToInv
= true;
2938 if (pBestIndex
!= NULL
&& pindex
->pprev
!= pBestIndex
) {
2939 // This means that the list of blocks to announce don't
2940 // connect to each other.
2941 // This shouldn't really be possible to hit during
2942 // regular operation (because reorgs should take us to
2943 // a chain that has some block not on the prior chain,
2944 // which should be caught by the prior check), but one
2945 // way this could happen is by using invalidateblock /
2946 // reconsiderblock repeatedly on the tip, causing it to
2947 // be added multiple times to vBlockHashesToAnnounce.
2948 // Robustly deal with this rare situation by reverting
2950 fRevertToInv
= true;
2953 pBestIndex
= pindex
;
2954 if (fFoundStartingHeader
) {
2955 // add this to the headers message
2956 vHeaders
.push_back(pindex
->GetBlockHeader());
2957 } else if (PeerHasHeader(&state
, pindex
)) {
2958 continue; // keep looking for the first new block
2959 } else if (pindex
->pprev
== NULL
|| PeerHasHeader(&state
, pindex
->pprev
)) {
2960 // Peer doesn't have this header but they do have the prior one.
2961 // Start sending headers.
2962 fFoundStartingHeader
= true;
2963 vHeaders
.push_back(pindex
->GetBlockHeader());
2965 // Peer doesn't have this header or the prior one -- nothing will
2966 // connect, so bail out.
2967 fRevertToInv
= true;
2972 if (!fRevertToInv
&& !vHeaders
.empty()) {
2973 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
2974 // We only send up to 1 block as header-and-ids, as otherwise
2975 // probably means we're doing an initial-ish-sync or they're slow
2976 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", __func__
,
2977 vHeaders
.front().GetHash().ToString(), pto
->GetId());
2979 int nSendFlags
= state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
2981 bool fGotBlockFromCache
= false;
2983 LOCK(cs_most_recent_block
);
2984 if (most_recent_block_hash
== pBestIndex
->GetBlockHash()) {
2985 if (state
.fWantsCmpctWitness
|| !fWitnessesPresentInMostRecentCompactBlock
)
2986 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *most_recent_compact_block
));
2988 CBlockHeaderAndShortTxIDs
cmpctblock(*most_recent_block
, state
.fWantsCmpctWitness
);
2989 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
2991 fGotBlockFromCache
= true;
2994 if (!fGotBlockFromCache
) {
2996 bool ret
= ReadBlockFromDisk(block
, pBestIndex
, consensusParams
);
2998 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
2999 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3001 state
.pindexBestHeaderSent
= pBestIndex
;
3002 } else if (state
.fPreferHeaders
) {
3003 if (vHeaders
.size() > 1) {
3004 LogPrint(BCLog::NET
, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
3006 vHeaders
.front().GetHash().ToString(),
3007 vHeaders
.back().GetHash().ToString(), pto
->GetId());
3009 LogPrint(BCLog::NET
, "%s: sending header %s to peer=%d\n", __func__
,
3010 vHeaders
.front().GetHash().ToString(), pto
->GetId());
3012 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
3013 state
.pindexBestHeaderSent
= pBestIndex
;
3015 fRevertToInv
= true;
3018 // If falling back to using an inv, just try to inv the tip.
3019 // The last entry in vBlockHashesToAnnounce was our tip at some point
3021 if (!pto
->vBlockHashesToAnnounce
.empty()) {
3022 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
3023 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
3024 assert(mi
!= mapBlockIndex
.end());
3025 const CBlockIndex
*pindex
= mi
->second
;
3027 // Warn if we're announcing a block that is not on the main chain.
3028 // This should be very rare and could be optimized out.
3029 // Just log for now.
3030 if (chainActive
[pindex
->nHeight
] != pindex
) {
3031 LogPrint(BCLog::NET
, "Announcing block %s not on main chain (tip=%s)\n",
3032 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
3035 // If the peer's chain has this block, don't inv it back.
3036 if (!PeerHasHeader(&state
, pindex
)) {
3037 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
3038 LogPrint(BCLog::NET
, "%s: sending inv peer=%d hash=%s\n", __func__
,
3039 pto
->GetId(), hashToAnnounce
.ToString());
3043 pto
->vBlockHashesToAnnounce
.clear();
3047 // Message: inventory
3049 std::vector
<CInv
> vInv
;
3051 LOCK(pto
->cs_inventory
);
3052 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
3055 for (const uint256
& hash
: pto
->vInventoryBlockToSend
) {
3056 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
3057 if (vInv
.size() == MAX_INV_SZ
) {
3058 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3062 pto
->vInventoryBlockToSend
.clear();
3064 // Check whether periodic sends should happen
3065 bool fSendTrickle
= pto
->fWhitelisted
;
3066 if (pto
->nNextInvSend
< nNow
) {
3067 fSendTrickle
= true;
3068 // Use half the delay for outbound peers, as there is less privacy concern for them.
3069 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
3072 // Time to send but the peer has requested we not relay transactions.
3074 LOCK(pto
->cs_filter
);
3075 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
3078 // Respond to BIP35 mempool requests
3079 if (fSendTrickle
&& pto
->fSendMempool
) {
3080 auto vtxinfo
= mempool
.infoAll();
3081 pto
->fSendMempool
= false;
3082 CAmount filterrate
= 0;
3084 LOCK(pto
->cs_feeFilter
);
3085 filterrate
= pto
->minFeeFilter
;
3088 LOCK(pto
->cs_filter
);
3090 for (const auto& txinfo
: vtxinfo
) {
3091 const uint256
& hash
= txinfo
.tx
->GetHash();
3092 CInv
inv(MSG_TX
, hash
);
3093 pto
->setInventoryTxToSend
.erase(hash
);
3095 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
3099 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3101 pto
->filterInventoryKnown
.insert(hash
);
3102 vInv
.push_back(inv
);
3103 if (vInv
.size() == MAX_INV_SZ
) {
3104 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3108 pto
->timeLastMempoolReq
= GetTime();
3111 // Determine transactions to relay
3113 // Produce a vector with all candidates for sending
3114 std::vector
<std::set
<uint256
>::iterator
> vInvTx
;
3115 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
3116 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
3117 vInvTx
.push_back(it
);
3119 CAmount filterrate
= 0;
3121 LOCK(pto
->cs_feeFilter
);
3122 filterrate
= pto
->minFeeFilter
;
3124 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3125 // A heap is used so that not all items need sorting if only a few are being sent.
3126 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
3127 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3128 // No reason to drain out at many times the network's capacity,
3129 // especially since we have many peers and some will draw much shorter delays.
3130 unsigned int nRelayedTransactions
= 0;
3131 LOCK(pto
->cs_filter
);
3132 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
3133 // Fetch the top element from the heap
3134 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3135 std::set
<uint256
>::iterator it
= vInvTx
.back();
3138 // Remove it from the to-be-sent set
3139 pto
->setInventoryTxToSend
.erase(it
);
3140 // Check if not in the filter already
3141 if (pto
->filterInventoryKnown
.contains(hash
)) {
3144 // Not in the mempool anymore? don't bother sending it.
3145 auto txinfo
= mempool
.info(hash
);
3149 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
3152 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3154 vInv
.push_back(CInv(MSG_TX
, hash
));
3155 nRelayedTransactions
++;
3157 // Expire old relay messages
3158 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
3160 mapRelay
.erase(vRelayExpiration
.front().second
);
3161 vRelayExpiration
.pop_front();
3164 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
3166 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
3169 if (vInv
.size() == MAX_INV_SZ
) {
3170 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3173 pto
->filterInventoryKnown
.insert(hash
);
3178 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3180 // Detect whether we're stalling
3181 nNow
= GetTimeMicros();
3182 if (state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
3183 // Stalling only triggers when the block download window cannot move. During normal steady state,
3184 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3185 // should only happen during initial block download.
3186 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->GetId());
3187 pto
->fDisconnect
= true;
3190 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3191 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3192 // We compensate for other peers to prevent killing off peers due to our own downstream link
3193 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3194 // to unreasonably increase our timeout.
3195 if (state
.vBlocksInFlight
.size() > 0) {
3196 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
3197 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
3198 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
3199 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->GetId());
3200 pto
->fDisconnect
= true;
3204 // Check for headers sync timeouts
3205 if (state
.fSyncStarted
&& state
.nHeadersSyncTimeout
< std::numeric_limits
<int64_t>::max()) {
3206 // Detect whether this is a stalling initial-headers-sync peer
3207 if (pindexBestHeader
->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3208 if (nNow
> state
.nHeadersSyncTimeout
&& nSyncStarted
== 1 && (nPreferredDownload
- state
.fPreferredDownload
>= 1)) {
3209 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3210 // and we have others we could be using instead.
3211 // Note: If all our peers are inbound, then we won't
3212 // disconnect our sync peer for stalling; we have bigger
3213 // problems if we can't get any outbound peers.
3214 if (!pto
->fWhitelisted
) {
3215 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto
->GetId());
3216 pto
->fDisconnect
= true;
3219 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto
->GetId());
3220 // Reset the headers sync state so that we have a
3221 // chance to try downloading from a different peer.
3222 // Note: this will also result in at least one more
3223 // getheaders message to be sent to
3224 // this peer (eventually).
3225 state
.fSyncStarted
= false;
3227 state
.nHeadersSyncTimeout
= 0;
3231 // After we've caught up once, reset the timeout so we can't trigger
3232 // disconnect later.
3233 state
.nHeadersSyncTimeout
= std::numeric_limits
<int64_t>::max();
3239 // Message: getdata (blocks)
3241 std::vector
<CInv
> vGetData
;
3242 if (!pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
3243 std::vector
<const CBlockIndex
*> vToDownload
;
3244 NodeId staller
= -1;
3245 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
3246 for (const CBlockIndex
*pindex
: vToDownload
) {
3247 uint32_t nFetchFlags
= GetFetchFlags(pto
);
3248 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
3249 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), pindex
);
3250 LogPrint(BCLog::NET
, "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
3251 pindex
->nHeight
, pto
->GetId());
3253 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
3254 if (State(staller
)->nStallingSince
== 0) {
3255 State(staller
)->nStallingSince
= nNow
;
3256 LogPrint(BCLog::NET
, "Stall started peer=%d\n", staller
);
3262 // Message: getdata (non-blocks)
3264 while (!pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
3266 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
3267 if (!AlreadyHave(inv
))
3269 LogPrint(BCLog::NET
, "Requesting %s peer=%d\n", inv
.ToString(), pto
->GetId());
3270 vGetData
.push_back(inv
);
3271 if (vGetData
.size() >= 1000)
3273 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3277 //If we're not going to ask, don't expect a response.
3278 pto
->setAskFor
.erase(inv
.hash
);
3280 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
3282 if (!vGetData
.empty())
3283 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3286 // Message: feefilter
3288 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3289 if (pto
->nVersion
>= FEEFILTER_VERSION
&& GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
3290 !(pto
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
3291 CAmount currentFilter
= mempool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
3292 int64_t timeNow
= GetTimeMicros();
3293 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
3294 static CFeeRate
default_feerate(DEFAULT_MIN_RELAY_TX_FEE
);
3295 static FeeFilterRounder
filterRounder(default_feerate
);
3296 CAmount filterToSend
= filterRounder
.round(currentFilter
);
3297 // We always have a fee filter of at least minRelayTxFee
3298 filterToSend
= std::max(filterToSend
, ::minRelayTxFee
.GetFeePerK());
3299 if (filterToSend
!= pto
->lastSentFeeFilter
) {
3300 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::FEEFILTER
, filterToSend
));
3301 pto
->lastSentFeeFilter
= filterToSend
;
3303 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
3305 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3306 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3307 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
3308 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
3309 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
3316 class CNetProcessingCleanup
3319 CNetProcessingCleanup() {}
3320 ~CNetProcessingCleanup() {
3321 // orphan transactions
3322 mapOrphanTransactions
.clear();
3323 mapOrphanTransactionsByPrev
.clear();
3325 } instance_of_cnetprocessingcleanup
;