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>
17 #include <netmessagemaker.h>
19 #include <policy/fees.h>
20 #include <policy/policy.h>
21 #include <primitives/block.h>
22 #include <primitives/transaction.h>
24 #include <reverse_iterator.h>
25 #include <scheduler.h>
26 #include <tinyformat.h>
27 #include <txmempool.h>
28 #include <ui_interface.h>
30 #include <utilmoneystr.h>
31 #include <utilstrencodings.h>
34 # error "Bitcoin cannot be compiled without assertions."
37 std::atomic
<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
39 struct IteratorComparator
42 bool operator()(const I
& a
, const I
& b
)
49 // When modifying, adapt the copy of this definition in tests/DoS_tests.
54 std::map
<uint256
, COrphanTx
> mapOrphanTransactions
GUARDED_BY(cs_main
);
55 std::map
<COutPoint
, std::set
<std::map
<uint256
, COrphanTx
>::iterator
, IteratorComparator
>> mapOrphanTransactionsByPrev
GUARDED_BY(cs_main
);
56 void EraseOrphansFor(NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
);
58 static size_t vExtraTxnForCompactIt
= 0;
59 static std::vector
<std::pair
<uint256
, CTransactionRef
>> vExtraTxnForCompact
GUARDED_BY(cs_main
);
61 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY
= 0x3cac0035b5866b90ULL
; // SHA256("main address relay")[0:8]
63 /// Age after which a stale block will no longer be served if requested as
64 /// protection against fingerprinting. Set to one month, denominated in seconds.
65 static const int STALE_RELAY_AGE_LIMIT
= 30 * 24 * 60 * 60;
67 /// Age after which a block is considered historical for purposes of rate
68 /// limiting block relay. Set to one week, denominated in seconds.
69 static const int HISTORICAL_BLOCK_AGE
= 7 * 24 * 60 * 60;
73 /** Number of nodes with fSyncStarted. */
77 * Sources of received blocks, saved to be able to send them reject
78 * messages or ban them when processing happens afterwards. Protected by
80 * Set mapBlockSource[hash].second to false if the node should not be
81 * punished if the block is invalid.
83 std::map
<uint256
, std::pair
<NodeId
, bool>> mapBlockSource
;
86 * Filter for transactions that were recently rejected by
87 * AcceptToMemoryPool. These are not rerequested until the chain tip
88 * changes, at which point the entire filter is reset. Protected by
91 * Without this filter we'd be re-requesting txs from each of our peers,
92 * increasing bandwidth consumption considerably. For instance, with 100
93 * peers, half of which relay a tx we don't accept, that might be a 50x
94 * bandwidth increase. A flooding attacker attempting to roll-over the
95 * filter using minimum-sized, 60byte, transactions might manage to send
96 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
97 * two minute window to send invs to us.
99 * Decreasing the false positive rate is fairly cheap, so we pick one in a
100 * million to make it highly unlikely for users to have issues with this
103 * Memory used: 1.3 MB
105 std::unique_ptr
<CRollingBloomFilter
> recentRejects
;
106 uint256 hashRecentRejectsChainTip
;
108 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
111 const CBlockIndex
* pindex
; //!< Optional.
112 bool fValidatedHeaders
; //!< Whether this block has validated headers at the time of request.
113 std::unique_ptr
<PartiallyDownloadedBlock
> partialBlock
; //!< Optional, used for CMPCTBLOCK downloads
115 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> > mapBlocksInFlight
;
117 /** Stack of nodes which we have set to announce using compact blocks */
118 std::list
<NodeId
> lNodesAnnouncingHeaderAndIDs
;
120 /** Number of preferable block download peers. */
121 int nPreferredDownload
= 0;
123 /** Number of peers from which we're downloading blocks. */
124 int nPeersWithValidatedDownloads
= 0;
126 /** Number of outbound peers with m_chain_sync.m_protect. */
127 int g_outbound_peers_with_protect_from_disconnect
= 0;
129 /** When our tip was last updated. */
130 int64_t g_last_tip_update
= 0;
132 /** Relay map, protected by cs_main. */
133 typedef std::map
<uint256
, CTransactionRef
> MapRelay
;
135 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
136 std::deque
<std::pair
<int64_t, MapRelay::iterator
>> vRelayExpiration
;
141 struct CBlockReject
{
142 unsigned char chRejectCode
;
143 std::string strRejectReason
;
148 * Maintain validation-specific state about nodes, protected by cs_main, instead
149 * by CNode's own locks. This simplifies asynchronous operation, where
150 * processing of incoming data is done after the ProcessMessage call returns,
151 * and we're no longer holding the node's locks.
154 //! The peer's address
155 const CService address
;
156 //! Whether we have a fully established connection.
157 bool fCurrentlyConnected
;
158 //! Accumulated misbehaviour score for this peer.
160 //! Whether this peer should be disconnected and banned (unless whitelisted).
162 //! String name of this peer (debugging/logging purposes).
163 const std::string name
;
164 //! List of asynchronously-determined block rejections to notify this peer about.
165 std::vector
<CBlockReject
> rejects
;
166 //! The best known block we know this peer has announced.
167 const CBlockIndex
*pindexBestKnownBlock
;
168 //! The hash of the last unknown block this peer has announced.
169 uint256 hashLastUnknownBlock
;
170 //! The last full block we both have.
171 const CBlockIndex
*pindexLastCommonBlock
;
172 //! The best header we have sent our peer.
173 const CBlockIndex
*pindexBestHeaderSent
;
174 //! Length of current-streak of unconnecting headers announcements
175 int nUnconnectingHeaders
;
176 //! Whether we've started headers synchronization with this peer.
178 //! When to potentially disconnect peer for stalling headers download
179 int64_t nHeadersSyncTimeout
;
180 //! Since when we're stalling block download progress (in microseconds), or 0.
181 int64_t nStallingSince
;
182 std::list
<QueuedBlock
> vBlocksInFlight
;
183 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
184 int64_t nDownloadingSince
;
186 int nBlocksInFlightValidHeaders
;
187 //! Whether we consider this a preferred download peer.
188 bool fPreferredDownload
;
189 //! Whether this peer wants invs or headers (when possible) for block announcements.
191 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
192 bool fPreferHeaderAndIDs
;
194 * Whether this peer will send us cmpctblocks if we request them.
195 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
196 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
198 bool fProvidesHeaderAndIDs
;
199 //! Whether this peer can give us witnesses
201 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
202 bool fWantsCmpctWitness
;
204 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
205 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
207 bool fSupportsDesiredCmpctVersion
;
209 /** State used to enforce CHAIN_SYNC_TIMEOUT
210 * Only in effect for outbound, non-manual connections, with
212 * Algorithm: if a peer's best known block has less work than our tip,
213 * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
214 * - If at timeout their best known block now has more work than our tip
215 * when the timeout was set, then either reset the timeout or clear it
216 * (after comparing against our current tip's work)
217 * - If at timeout their best known block still has less work than our
218 * tip did when the timeout was set, then send a getheaders message,
219 * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
220 * If their best known block is still behind when that new timeout is
221 * reached, disconnect.
223 struct ChainSyncTimeoutState
{
224 //! A timeout used for checking whether our peer has sufficiently synced
226 //! A header with the work we require on our peer's chain
227 const CBlockIndex
* m_work_header
;
228 //! After timeout is reached, set to true after sending getheaders
229 bool m_sent_getheaders
;
230 //! Whether this peer is protected from disconnection due to a bad/slow chain
234 ChainSyncTimeoutState m_chain_sync
;
236 //! Time of last new block announcement
237 int64_t m_last_block_announcement
;
239 CNodeState(CAddress addrIn
, std::string addrNameIn
) : address(addrIn
), name(addrNameIn
) {
240 fCurrentlyConnected
= false;
243 pindexBestKnownBlock
= nullptr;
244 hashLastUnknownBlock
.SetNull();
245 pindexLastCommonBlock
= nullptr;
246 pindexBestHeaderSent
= nullptr;
247 nUnconnectingHeaders
= 0;
248 fSyncStarted
= false;
249 nHeadersSyncTimeout
= 0;
251 nDownloadingSince
= 0;
253 nBlocksInFlightValidHeaders
= 0;
254 fPreferredDownload
= false;
255 fPreferHeaders
= false;
256 fPreferHeaderAndIDs
= false;
257 fProvidesHeaderAndIDs
= false;
258 fHaveWitness
= false;
259 fWantsCmpctWitness
= false;
260 fSupportsDesiredCmpctVersion
= false;
261 m_chain_sync
= { 0, nullptr, false, false };
262 m_last_block_announcement
= 0;
266 /** Map maintaining per-node state. Requires cs_main. */
267 std::map
<NodeId
, CNodeState
> mapNodeState
;
270 CNodeState
*State(NodeId pnode
) {
271 std::map
<NodeId
, CNodeState
>::iterator it
= mapNodeState
.find(pnode
);
272 if (it
== mapNodeState
.end())
277 void UpdatePreferredDownload(CNode
* node
, CNodeState
* state
)
279 nPreferredDownload
-= state
->fPreferredDownload
;
281 // Whether this node should be marked as a preferred download node.
282 state
->fPreferredDownload
= (!node
->fInbound
|| node
->fWhitelisted
) && !node
->fOneShot
&& !node
->fClient
;
284 nPreferredDownload
+= state
->fPreferredDownload
;
287 void PushNodeVersion(CNode
*pnode
, CConnman
* connman
, int64_t nTime
)
289 ServiceFlags nLocalNodeServices
= pnode
->GetLocalServices();
290 uint64_t nonce
= pnode
->GetLocalNonce();
291 int nNodeStartingHeight
= pnode
->GetMyStartingHeight();
292 NodeId nodeid
= pnode
->GetId();
293 CAddress addr
= pnode
->addr
;
295 CAddress addrYou
= (addr
.IsRoutable() && !IsProxy(addr
) ? addr
: CAddress(CService(), addr
.nServices
));
296 CAddress addrMe
= CAddress(CService(), nLocalNodeServices
);
298 connman
->PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERSION
, PROTOCOL_VERSION
, (uint64_t)nLocalNodeServices
, nTime
, addrYou
, addrMe
,
299 nonce
, strSubVersion
, nNodeStartingHeight
, ::fRelayTxes
));
302 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), addrYou
.ToString(), nodeid
);
304 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), nodeid
);
309 // Returns a bool indicating whether we requested this block.
310 // Also used if a block was /not/ received and timed out or started with another peer
311 bool MarkBlockAsReceived(const uint256
& hash
) {
312 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
313 if (itInFlight
!= mapBlocksInFlight
.end()) {
314 CNodeState
*state
= State(itInFlight
->second
.first
);
315 assert(state
!= nullptr);
316 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
317 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
318 // Last validated block on the queue was received.
319 nPeersWithValidatedDownloads
--;
321 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
322 // First block on the queue was received, update the start download time for the next one
323 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
325 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
326 state
->nBlocksInFlight
--;
327 state
->nStallingSince
= 0;
328 mapBlocksInFlight
.erase(itInFlight
);
335 // returns false, still setting pit, if the block was already in flight from the same peer
336 // pit will only be valid as long as the same cs_main lock is being held
337 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const CBlockIndex
* pindex
= nullptr, std::list
<QueuedBlock
>::iterator
** pit
= nullptr) {
338 CNodeState
*state
= State(nodeid
);
339 assert(state
!= nullptr);
341 // Short-circuit most stuff in case its from the same node
342 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
343 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
345 *pit
= &itInFlight
->second
.second
;
350 // Make sure it's not listed somewhere already.
351 MarkBlockAsReceived(hash
);
353 std::list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
354 {hash
, pindex
, pindex
!= nullptr, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : nullptr)});
355 state
->nBlocksInFlight
++;
356 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
357 if (state
->nBlocksInFlight
== 1) {
358 // We're starting a block download (batch) from this peer.
359 state
->nDownloadingSince
= GetTimeMicros();
361 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= nullptr) {
362 nPeersWithValidatedDownloads
++;
364 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
366 *pit
= &itInFlight
->second
.second
;
370 /** Check whether the last unknown block a peer advertised is not yet known. */
371 void ProcessBlockAvailability(NodeId nodeid
) {
372 CNodeState
*state
= State(nodeid
);
373 assert(state
!= nullptr);
375 if (!state
->hashLastUnknownBlock
.IsNull()) {
376 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
377 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
378 if (state
->pindexBestKnownBlock
== nullptr || itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
379 state
->pindexBestKnownBlock
= itOld
->second
;
380 state
->hashLastUnknownBlock
.SetNull();
385 /** Update tracking information about which blocks a peer is assumed to have. */
386 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
387 CNodeState
*state
= State(nodeid
);
388 assert(state
!= nullptr);
390 ProcessBlockAvailability(nodeid
);
392 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
393 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
394 // An actually better block was announced.
395 if (state
->pindexBestKnownBlock
== nullptr || it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
396 state
->pindexBestKnownBlock
= it
->second
;
398 // An unknown block was announced; just assume that the latest one is the best one.
399 state
->hashLastUnknownBlock
= hash
;
403 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid
, CConnman
* connman
) {
404 AssertLockHeld(cs_main
);
405 CNodeState
* nodestate
= State(nodeid
);
406 if (!nodestate
|| !nodestate
->fSupportsDesiredCmpctVersion
) {
407 // Never ask from peers who can't provide witnesses.
410 if (nodestate
->fProvidesHeaderAndIDs
) {
411 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
413 lNodesAnnouncingHeaderAndIDs
.erase(it
);
414 lNodesAnnouncingHeaderAndIDs
.push_back(nodeid
);
418 connman
->ForNode(nodeid
, [connman
](CNode
* pfrom
){
419 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
420 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
421 // As per BIP152, we only get 3 of our peers to announce
422 // blocks using compact encodings.
423 connman
->ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [connman
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
424 connman
->PushMessage(pnodeStop
, CNetMsgMaker(pnodeStop
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion
));
427 lNodesAnnouncingHeaderAndIDs
.pop_front();
429 connman
->PushMessage(pfrom
, CNetMsgMaker(pfrom
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion
));
430 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
436 bool TipMayBeStale(const Consensus::Params
&consensusParams
)
438 AssertLockHeld(cs_main
);
439 if (g_last_tip_update
== 0) {
440 g_last_tip_update
= GetTime();
442 return g_last_tip_update
< GetTime() - consensusParams
.nPowTargetSpacing
* 3 && mapBlocksInFlight
.empty();
446 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
448 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
452 bool PeerHasHeader(CNodeState
*state
, const CBlockIndex
*pindex
)
454 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
456 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
461 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
462 * at most count entries. */
463 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<const CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
467 vBlocks
.reserve(vBlocks
.size() + count
);
468 CNodeState
*state
= State(nodeid
);
469 assert(state
!= nullptr);
471 // Make sure pindexBestKnownBlock is up to date, we'll need it.
472 ProcessBlockAvailability(nodeid
);
474 if (state
->pindexBestKnownBlock
== nullptr || state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
|| state
->pindexBestKnownBlock
->nChainWork
< nMinimumChainWork
) {
475 // This peer has nothing interesting.
479 if (state
->pindexLastCommonBlock
== nullptr) {
480 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
481 // Guessing wrong in either direction is not a problem.
482 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
485 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
486 // of its current tip anymore. Go back enough to fix that.
487 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
488 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
491 std::vector
<const CBlockIndex
*> vToFetch
;
492 const CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
493 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
494 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
495 // download that next block if the window were 1 larger.
496 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
497 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
498 NodeId waitingfor
= -1;
499 while (pindexWalk
->nHeight
< nMaxHeight
) {
500 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
501 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
502 // as iterating over ~100 CBlockIndex* entries anyway.
503 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
504 vToFetch
.resize(nToFetch
);
505 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
506 vToFetch
[nToFetch
- 1] = pindexWalk
;
507 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
508 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
511 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
512 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
513 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
514 // already part of our chain (and therefore don't need it even if pruned).
515 for (const CBlockIndex
* pindex
: vToFetch
) {
516 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
517 // We consider the chain that this peer is on invalid.
520 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
521 // We wouldn't download this block or its descendants from this peer.
524 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
525 if (pindex
->nChainTx
)
526 state
->pindexLastCommonBlock
= pindex
;
527 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
528 // The block is not already downloaded, and not yet in flight.
529 if (pindex
->nHeight
> nWindowEnd
) {
530 // We reached the end of the window.
531 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
532 // We aren't able to fetch anything, but we would be if the download window was one larger.
533 nodeStaller
= waitingfor
;
537 vBlocks
.push_back(pindex
);
538 if (vBlocks
.size() == count
) {
541 } else if (waitingfor
== -1) {
542 // This is the first already-in-flight block.
543 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
551 // This function is used for testing the stale tip eviction logic, see
553 void UpdateLastBlockAnnounceTime(NodeId node
, int64_t time_in_seconds
)
556 CNodeState
*state
= State(node
);
557 if (state
) state
->m_last_block_announcement
= time_in_seconds
;
560 // Returns true for outbound peers, excluding manual connections, feelers, and
562 bool IsOutboundDisconnectionCandidate(const CNode
*node
)
564 return !(node
->fInbound
|| node
->m_manual_connection
|| node
->fFeeler
|| node
->fOneShot
);
567 void PeerLogicValidation::InitializeNode(CNode
*pnode
) {
568 CAddress addr
= pnode
->addr
;
569 std::string addrName
= pnode
->GetAddrName();
570 NodeId nodeid
= pnode
->GetId();
573 mapNodeState
.emplace_hint(mapNodeState
.end(), std::piecewise_construct
, std::forward_as_tuple(nodeid
), std::forward_as_tuple(addr
, std::move(addrName
)));
576 PushNodeVersion(pnode
, connman
, GetTime());
579 void PeerLogicValidation::FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
580 fUpdateConnectionTime
= false;
582 CNodeState
*state
= State(nodeid
);
583 assert(state
!= nullptr);
585 if (state
->fSyncStarted
)
588 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
589 fUpdateConnectionTime
= true;
592 for (const QueuedBlock
& entry
: state
->vBlocksInFlight
) {
593 mapBlocksInFlight
.erase(entry
.hash
);
595 EraseOrphansFor(nodeid
);
596 nPreferredDownload
-= state
->fPreferredDownload
;
597 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
598 assert(nPeersWithValidatedDownloads
>= 0);
599 g_outbound_peers_with_protect_from_disconnect
-= state
->m_chain_sync
.m_protect
;
600 assert(g_outbound_peers_with_protect_from_disconnect
>= 0);
602 mapNodeState
.erase(nodeid
);
604 if (mapNodeState
.empty()) {
605 // Do a consistency check after the last peer is removed.
606 assert(mapBlocksInFlight
.empty());
607 assert(nPreferredDownload
== 0);
608 assert(nPeersWithValidatedDownloads
== 0);
609 assert(g_outbound_peers_with_protect_from_disconnect
== 0);
611 LogPrint(BCLog::NET
, "Cleared nodestate for peer=%d\n", nodeid
);
614 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
616 CNodeState
*state
= State(nodeid
);
617 if (state
== nullptr)
619 stats
.nMisbehavior
= state
->nMisbehavior
;
620 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
621 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
622 for (const QueuedBlock
& queue
: state
->vBlocksInFlight
) {
624 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
629 //////////////////////////////////////////////////////////////////////////////
631 // mapOrphanTransactions
634 void AddToCompactExtraTransactions(const CTransactionRef
& tx
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
636 size_t max_extra_txn
= gArgs
.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
);
637 if (max_extra_txn
<= 0)
639 if (!vExtraTxnForCompact
.size())
640 vExtraTxnForCompact
.resize(max_extra_txn
);
641 vExtraTxnForCompact
[vExtraTxnForCompactIt
] = std::make_pair(tx
->GetWitnessHash(), tx
);
642 vExtraTxnForCompactIt
= (vExtraTxnForCompactIt
+ 1) % max_extra_txn
;
645 bool AddOrphanTx(const CTransactionRef
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
647 const uint256
& hash
= tx
->GetHash();
648 if (mapOrphanTransactions
.count(hash
))
651 // Ignore big transactions, to avoid a
652 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
653 // large transaction with a missing parent then we assume
654 // it will rebroadcast it later, after the parent transaction(s)
655 // have been mined or received.
656 // 100 orphans, each of which is at most 99,999 bytes big is
657 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
658 unsigned int sz
= GetTransactionWeight(*tx
);
659 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
661 LogPrint(BCLog::MEMPOOL
, "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
665 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
667 for (const CTxIn
& txin
: tx
->vin
) {
668 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
671 AddToCompactExtraTransactions(tx
);
673 LogPrint(BCLog::MEMPOOL
, "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
674 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
678 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
680 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
681 if (it
== mapOrphanTransactions
.end())
683 for (const CTxIn
& txin
: it
->second
.tx
->vin
)
685 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
686 if (itPrev
== mapOrphanTransactionsByPrev
.end())
688 itPrev
->second
.erase(it
);
689 if (itPrev
->second
.empty())
690 mapOrphanTransactionsByPrev
.erase(itPrev
);
692 mapOrphanTransactions
.erase(it
);
696 void EraseOrphansFor(NodeId peer
)
699 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
700 while (iter
!= mapOrphanTransactions
.end())
702 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
703 if (maybeErase
->second
.fromPeer
== peer
)
705 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
708 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx from peer=%d\n", nErased
, peer
);
712 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
714 unsigned int nEvicted
= 0;
715 static int64_t nNextSweep
;
716 int64_t nNow
= GetTime();
717 if (nNextSweep
<= nNow
) {
718 // Sweep out expired orphan pool entries:
720 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
721 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
722 while (iter
!= mapOrphanTransactions
.end())
724 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
725 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
726 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
728 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
731 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
732 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
733 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx due to expiration\n", nErased
);
735 while (mapOrphanTransactions
.size() > nMaxOrphans
)
737 // Evict a random orphan:
738 uint256 randomhash
= GetRandHash();
739 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
740 if (it
== mapOrphanTransactions
.end())
741 it
= mapOrphanTransactions
.begin();
742 EraseOrphanTx(it
->first
);
749 void Misbehaving(NodeId pnode
, int howmuch
)
754 CNodeState
*state
= State(pnode
);
755 if (state
== nullptr)
758 state
->nMisbehavior
+= howmuch
;
759 int banscore
= gArgs
.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
760 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
762 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
763 state
->fShouldBan
= true;
765 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
775 //////////////////////////////////////////////////////////////////////////////
777 // blockchain -> download logic notification
780 // To prevent fingerprinting attacks, only send blocks/headers outside of the
781 // active chain if they are no more than a month older (both in time, and in
782 // best equivalent proof of work) than the best header chain we know about and
783 // we fully-validated them at some point.
784 static bool BlockRequestAllowed(const CBlockIndex
* pindex
, const Consensus::Params
& consensusParams
)
786 AssertLockHeld(cs_main
);
787 if (chainActive
.Contains(pindex
)) return true;
788 return pindex
->IsValid(BLOCK_VALID_SCRIPTS
) && (pindexBestHeader
!= nullptr) &&
789 (pindexBestHeader
->GetBlockTime() - pindex
->GetBlockTime() < STALE_RELAY_AGE_LIMIT
) &&
790 (GetBlockProofEquivalentTime(*pindexBestHeader
, *pindex
, *pindexBestHeader
, consensusParams
) < STALE_RELAY_AGE_LIMIT
);
793 PeerLogicValidation::PeerLogicValidation(CConnman
* connmanIn
, CScheduler
&scheduler
) : connman(connmanIn
), m_stale_tip_check_time(0) {
794 // Initialize global variables that cannot be constructed at startup.
795 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
797 const Consensus::Params
& consensusParams
= Params().GetConsensus();
798 // Stale tip checking and peer eviction are on two different timers, but we
799 // don't want them to get out of sync due to drift in the scheduler, so we
800 // combine them in one function and schedule at the quicker (peer-eviction)
802 static_assert(EXTRA_PEER_CHECK_INTERVAL
< STALE_CHECK_INTERVAL
, "peer eviction timer should be less than stale tip check timer");
803 scheduler
.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers
, this, consensusParams
), EXTRA_PEER_CHECK_INTERVAL
* 1000);
806 void PeerLogicValidation::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
* pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
809 std::vector
<uint256
> vOrphanErase
;
811 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
812 const CTransaction
& tx
= *ptx
;
814 // Which orphan pool entries must we evict?
815 for (const auto& txin
: tx
.vin
) {
816 auto itByPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
817 if (itByPrev
== mapOrphanTransactionsByPrev
.end()) continue;
818 for (auto mi
= itByPrev
->second
.begin(); mi
!= itByPrev
->second
.end(); ++mi
) {
819 const CTransaction
& orphanTx
= *(*mi
)->second
.tx
;
820 const uint256
& orphanHash
= orphanTx
.GetHash();
821 vOrphanErase
.push_back(orphanHash
);
826 // Erase orphan transactions include or precluded by this block
827 if (vOrphanErase
.size()) {
829 for (uint256
&orphanHash
: vOrphanErase
) {
830 nErased
+= EraseOrphanTx(orphanHash
);
832 LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx included or conflicted by block\n", nErased
);
835 g_last_tip_update
= GetTime();
838 // All of the following cache a recent block, and are protected by cs_most_recent_block
839 static CCriticalSection cs_most_recent_block
;
840 static std::shared_ptr
<const CBlock
> most_recent_block
;
841 static std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> most_recent_compact_block
;
842 static uint256 most_recent_block_hash
;
843 static bool fWitnessesPresentInMostRecentCompactBlock
;
845 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex
*pindex
, const std::shared_ptr
<const CBlock
>& pblock
) {
846 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> pcmpctblock
= std::make_shared
<const CBlockHeaderAndShortTxIDs
> (*pblock
, true);
847 const CNetMsgMaker
msgMaker(PROTOCOL_VERSION
);
851 static int nHighestFastAnnounce
= 0;
852 if (pindex
->nHeight
<= nHighestFastAnnounce
)
854 nHighestFastAnnounce
= pindex
->nHeight
;
856 bool fWitnessEnabled
= IsWitnessEnabled(pindex
->pprev
, Params().GetConsensus());
857 uint256
hashBlock(pblock
->GetHash());
860 LOCK(cs_most_recent_block
);
861 most_recent_block_hash
= hashBlock
;
862 most_recent_block
= pblock
;
863 most_recent_compact_block
= pcmpctblock
;
864 fWitnessesPresentInMostRecentCompactBlock
= fWitnessEnabled
;
867 connman
->ForEachNode([this, &pcmpctblock
, pindex
, &msgMaker
, fWitnessEnabled
, &hashBlock
](CNode
* pnode
) {
868 // TODO: Avoid the repeated-serialization here
869 if (pnode
->nVersion
< INVALID_CB_NO_BAN_VERSION
|| pnode
->fDisconnect
)
871 ProcessBlockAvailability(pnode
->GetId());
872 CNodeState
&state
= *State(pnode
->GetId());
873 // If the peer has, or we announced to them the previous block already,
874 // but we don't think they have this one, go ahead and announce it
875 if (state
.fPreferHeaderAndIDs
&& (!fWitnessEnabled
|| state
.fWantsCmpctWitness
) &&
876 !PeerHasHeader(&state
, pindex
) && PeerHasHeader(&state
, pindex
->pprev
)) {
878 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
879 hashBlock
.ToString(), pnode
->GetId());
880 connman
->PushMessage(pnode
, msgMaker
.Make(NetMsgType::CMPCTBLOCK
, *pcmpctblock
));
881 state
.pindexBestHeaderSent
= pindex
;
886 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex
*pindexNew
, const CBlockIndex
*pindexFork
, bool fInitialDownload
) {
887 const int nNewHeight
= pindexNew
->nHeight
;
888 connman
->SetBestHeight(nNewHeight
);
890 if (!fInitialDownload
) {
891 // Find the hashes of all blocks that weren't previously in the best chain.
892 std::vector
<uint256
> vHashes
;
893 const CBlockIndex
*pindexToAnnounce
= pindexNew
;
894 while (pindexToAnnounce
!= pindexFork
) {
895 vHashes
.push_back(pindexToAnnounce
->GetBlockHash());
896 pindexToAnnounce
= pindexToAnnounce
->pprev
;
897 if (vHashes
.size() == MAX_BLOCKS_TO_ANNOUNCE
) {
898 // Limit announcements in case of a huge reorganization.
899 // Rely on the peer's synchronization mechanism in that case.
903 // Relay inventory, but don't relay old inventory during initial block download.
904 connman
->ForEachNode([nNewHeight
, &vHashes
](CNode
* pnode
) {
905 if (nNewHeight
> (pnode
->nStartingHeight
!= -1 ? pnode
->nStartingHeight
- 2000 : 0)) {
906 for (const uint256
& hash
: reverse_iterate(vHashes
)) {
907 pnode
->PushBlockHash(hash
);
911 connman
->WakeMessageHandler();
914 nTimeBestReceived
= GetTime();
917 void PeerLogicValidation::BlockChecked(const CBlock
& block
, const CValidationState
& state
) {
920 const uint256
hash(block
.GetHash());
921 std::map
<uint256
, std::pair
<NodeId
, bool>>::iterator it
= mapBlockSource
.find(hash
);
924 if (state
.IsInvalid(nDoS
)) {
925 // Don't send reject message with code 0 or an internal reject code.
926 if (it
!= mapBlockSource
.end() && State(it
->second
.first
) && state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) {
927 CBlockReject reject
= {(unsigned char)state
.GetRejectCode(), state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), hash
};
928 State(it
->second
.first
)->rejects
.push_back(reject
);
929 if (nDoS
> 0 && it
->second
.second
)
930 Misbehaving(it
->second
.first
, nDoS
);
934 // 1. The block is valid
935 // 2. We're not in initial block download
936 // 3. This is currently the best block we're aware of. We haven't updated
937 // the tip yet so we have no way to check this directly here. Instead we
938 // just check that there are currently no other blocks in flight.
939 else if (state
.IsValid() &&
940 !IsInitialBlockDownload() &&
941 mapBlocksInFlight
.count(hash
) == mapBlocksInFlight
.size()) {
942 if (it
!= mapBlockSource
.end()) {
943 MaybeSetPeerAsAnnouncingHeaderAndIDs(it
->second
.first
, connman
);
946 if (it
!= mapBlockSource
.end())
947 mapBlockSource
.erase(it
);
950 //////////////////////////////////////////////////////////////////////////////
956 bool static AlreadyHave(const CInv
& inv
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
963 assert(recentRejects
);
964 if (chainActive
.Tip()->GetBlockHash() != hashRecentRejectsChainTip
)
966 // If the chain tip has changed previously rejected transactions
967 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
968 // or a double-spend. Reset the rejects filter and give those
969 // txs a second chance.
970 hashRecentRejectsChainTip
= chainActive
.Tip()->GetBlockHash();
971 recentRejects
->reset();
974 return recentRejects
->contains(inv
.hash
) ||
975 mempool
.exists(inv
.hash
) ||
976 mapOrphanTransactions
.count(inv
.hash
) ||
977 pcoinsTip
->HaveCoinInCache(COutPoint(inv
.hash
, 0)) || // Best effort: only try output 0 and 1
978 pcoinsTip
->HaveCoinInCache(COutPoint(inv
.hash
, 1));
981 case MSG_WITNESS_BLOCK
:
982 return mapBlockIndex
.count(inv
.hash
);
984 // Don't know what it is, just say we already got one
988 static void RelayTransaction(const CTransaction
& tx
, CConnman
* connman
)
990 CInv
inv(MSG_TX
, tx
.GetHash());
991 connman
->ForEachNode([&inv
](CNode
* pnode
)
993 pnode
->PushInventory(inv
);
997 static void RelayAddress(const CAddress
& addr
, bool fReachable
, CConnman
* connman
)
999 unsigned int nRelayNodes
= fReachable
? 2 : 1; // limited relaying of addresses outside our network(s)
1001 // Relay to a limited number of other nodes
1002 // Use deterministic randomness to send to the same nodes for 24 hours
1003 // at a time so the addrKnowns of the chosen nodes prevent repeats
1004 uint64_t hashAddr
= addr
.GetHash();
1005 const CSipHasher hasher
= connman
->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY
).Write(hashAddr
<< 32).Write((GetTime() + hashAddr
) / (24*60*60));
1006 FastRandomContext insecure_rand
;
1008 std::array
<std::pair
<uint64_t, CNode
*>,2> best
{{{0, nullptr}, {0, nullptr}}};
1009 assert(nRelayNodes
<= best
.size());
1011 auto sortfunc
= [&best
, &hasher
, nRelayNodes
](CNode
* pnode
) {
1012 if (pnode
->nVersion
>= CADDR_TIME_VERSION
) {
1013 uint64_t hashKey
= CSipHasher(hasher
).Write(pnode
->GetId()).Finalize();
1014 for (unsigned int i
= 0; i
< nRelayNodes
; i
++) {
1015 if (hashKey
> best
[i
].first
) {
1016 std::copy(best
.begin() + i
, best
.begin() + nRelayNodes
- 1, best
.begin() + i
+ 1);
1017 best
[i
] = std::make_pair(hashKey
, pnode
);
1024 auto pushfunc
= [&addr
, &best
, nRelayNodes
, &insecure_rand
] {
1025 for (unsigned int i
= 0; i
< nRelayNodes
&& best
[i
].first
!= 0; i
++) {
1026 best
[i
].second
->PushAddress(addr
, insecure_rand
);
1030 connman
->ForEachNodeThen(std::move(sortfunc
), std::move(pushfunc
));
1033 void static ProcessGetData(CNode
* pfrom
, const Consensus::Params
& consensusParams
, CConnman
* connman
, const std::atomic
<bool>& interruptMsgProc
)
1035 std::deque
<CInv
>::iterator it
= pfrom
->vRecvGetData
.begin();
1036 std::vector
<CInv
> vNotFound
;
1037 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1040 while (it
!= pfrom
->vRecvGetData
.end()) {
1041 // Don't bother if send buffer is too full to respond anyway
1042 if (pfrom
->fPauseSend
)
1045 const CInv
&inv
= *it
;
1047 if (interruptMsgProc
)
1052 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1055 BlockMap::iterator mi
= mapBlockIndex
.find(inv
.hash
);
1056 std::shared_ptr
<const CBlock
> a_recent_block
;
1057 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> a_recent_compact_block
;
1058 bool fWitnessesPresentInARecentCompactBlock
;
1060 LOCK(cs_most_recent_block
);
1061 a_recent_block
= most_recent_block
;
1062 a_recent_compact_block
= most_recent_compact_block
;
1063 fWitnessesPresentInARecentCompactBlock
= fWitnessesPresentInMostRecentCompactBlock
;
1065 if (mi
!= mapBlockIndex
.end())
1067 if (mi
->second
->nChainTx
&& !mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) &&
1068 mi
->second
->IsValid(BLOCK_VALID_TREE
)) {
1069 // If we have the block and all of its parents, but have not yet validated it,
1070 // we might be in the middle of connecting it (ie in the unlock of cs_main
1071 // before ActivateBestChain but after AcceptBlock).
1072 // In this case, we need to run ActivateBestChain prior to checking the relay
1073 // conditions below.
1074 CValidationState dummy
;
1075 ActivateBestChain(dummy
, Params(), a_recent_block
);
1077 send
= BlockRequestAllowed(mi
->second
, consensusParams
);
1079 LogPrint(BCLog::NET
, "%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
1082 // disconnect node in case we have reached the outbound limit for serving historical blocks
1083 // never disconnect whitelisted nodes
1084 if (send
&& connman
->OutboundTargetReached(true) && ( ((pindexBestHeader
!= nullptr) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > HISTORICAL_BLOCK_AGE
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
1086 LogPrint(BCLog::NET
, "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
1089 pfrom
->fDisconnect
= true;
1092 // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold
1093 if (send
&& !pfrom
->fWhitelisted
&& (
1094 (((pfrom
->GetLocalServices() & NODE_NETWORK_LIMITED
) == NODE_NETWORK_LIMITED
) && ((pfrom
->GetLocalServices() & NODE_NETWORK
) != NODE_NETWORK
) && (chainActive
.Tip()->nHeight
- mi
->second
->nHeight
> (int)NODE_NETWORK_LIMITED_MIN_BLOCKS
+ 2 /* add two blocks buffer extension for possible races */) )
1096 LogPrint(BCLog::NET
, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom
->GetId());
1098 //disconnect node and prevent it from stalling (would otherwise wait for the missing block)
1099 pfrom
->fDisconnect
= true;
1102 // Pruned nodes may have deleted the block, so check whether
1103 // it's available before trying to send.
1104 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
1106 std::shared_ptr
<const CBlock
> pblock
;
1107 if (a_recent_block
&& a_recent_block
->GetHash() == (*mi
).second
->GetBlockHash()) {
1108 pblock
= a_recent_block
;
1110 // Send block from disk
1111 std::shared_ptr
<CBlock
> pblockRead
= std::make_shared
<CBlock
>();
1112 if (!ReadBlockFromDisk(*pblockRead
, (*mi
).second
, consensusParams
))
1113 assert(!"cannot load block from disk");
1114 pblock
= pblockRead
;
1116 if (inv
.type
== MSG_BLOCK
)
1117 connman
->PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, *pblock
));
1118 else if (inv
.type
== MSG_WITNESS_BLOCK
)
1119 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::BLOCK
, *pblock
));
1120 else if (inv
.type
== MSG_FILTERED_BLOCK
)
1122 bool sendMerkleBlock
= false;
1123 CMerkleBlock merkleBlock
;
1125 LOCK(pfrom
->cs_filter
);
1126 if (pfrom
->pfilter
) {
1127 sendMerkleBlock
= true;
1128 merkleBlock
= CMerkleBlock(*pblock
, *pfrom
->pfilter
);
1131 if (sendMerkleBlock
) {
1132 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::MERKLEBLOCK
, merkleBlock
));
1133 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1134 // This avoids hurting performance by pointlessly requiring a round-trip
1135 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1136 // they must either disconnect and retry or request the full block.
1137 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1138 // however we MUST always provide at least what the remote peer needs
1139 typedef std::pair
<unsigned int, uint256
> PairType
;
1140 for (PairType
& pair
: merkleBlock
.vMatchedTxn
)
1141 connman
->PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, *pblock
->vtx
[pair
.first
]));
1146 else if (inv
.type
== MSG_CMPCT_BLOCK
)
1148 // If a peer is asking for old blocks, we're almost guaranteed
1149 // they won't have a useful mempool to match against a compact block,
1150 // and we don't feel like constructing the object for them, so
1151 // instead we respond with the full, non-compact block.
1152 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
1153 int nSendFlags
= fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1154 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
1155 if ((fPeerWantsWitness
|| !fWitnessesPresentInARecentCompactBlock
) && a_recent_compact_block
&& a_recent_compact_block
->header
.GetHash() == mi
->second
->GetBlockHash()) {
1156 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *a_recent_compact_block
));
1158 CBlockHeaderAndShortTxIDs
cmpctblock(*pblock
, fPeerWantsWitness
);
1159 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
1162 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCK
, *pblock
));
1166 // Trigger the peer node to send a getblocks request for the next batch of inventory
1167 if (inv
.hash
== pfrom
->hashContinue
)
1169 // Bypass PushInventory, this must send even if redundant,
1170 // and we want it right after the last block so they don't
1171 // wait for other stuff first.
1172 std::vector
<CInv
> vInv
;
1173 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
1174 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::INV
, vInv
));
1175 pfrom
->hashContinue
.SetNull();
1179 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
1181 // Send stream from relay memory
1183 auto mi
= mapRelay
.find(inv
.hash
);
1184 int nSendFlags
= (inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0);
1185 if (mi
!= mapRelay
.end()) {
1186 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *mi
->second
));
1188 } else if (pfrom
->timeLastMempoolReq
) {
1189 auto txinfo
= mempool
.info(inv
.hash
);
1190 // To protect privacy, do not answer getdata using the mempool when
1191 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1192 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
1193 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *txinfo
.tx
));
1198 vNotFound
.push_back(inv
);
1202 // Track requests for our stuff.
1203 GetMainSignals().Inventory(inv
.hash
);
1205 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1210 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
1212 if (!vNotFound
.empty()) {
1213 // Let the peer know that we didn't find what it asked for, so it doesn't
1214 // have to wait around forever. Currently only SPV clients actually care
1215 // about this message: it's needed when they are recursively walking the
1216 // dependencies of relevant unconfirmed transactions. SPV clients want to
1217 // do that because they want to know about (and store and rebroadcast and
1218 // risk analyze) the dependencies of transactions relevant to them, without
1219 // having to download the entire memory pool.
1220 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::NOTFOUND
, vNotFound
));
1224 uint32_t GetFetchFlags(CNode
* pfrom
) {
1225 uint32_t nFetchFlags
= 0;
1226 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
1227 nFetchFlags
|= MSG_WITNESS_FLAG
;
1232 inline void static SendBlockTransactions(const CBlock
& block
, const BlockTransactionsRequest
& req
, CNode
* pfrom
, CConnman
* connman
) {
1233 BlockTransactions
resp(req
);
1234 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
1235 if (req
.indexes
[i
] >= block
.vtx
.size()) {
1237 Misbehaving(pfrom
->GetId(), 100);
1238 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->GetId());
1241 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
1244 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1245 int nSendFlags
= State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1246 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCKTXN
, resp
));
1249 bool static ProcessHeadersMessage(CNode
*pfrom
, CConnman
*connman
, const std::vector
<CBlockHeader
>& headers
, const CChainParams
& chainparams
, bool punish_duplicate_invalid
)
1251 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1252 size_t nCount
= headers
.size();
1255 // Nothing interesting. Stop asking this peers for more headers.
1259 bool received_new_header
= false;
1260 const CBlockIndex
*pindexLast
= nullptr;
1263 CNodeState
*nodestate
= State(pfrom
->GetId());
1265 // If this looks like it could be a block announcement (nCount <
1266 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1268 // - Send a getheaders message in response to try to connect the chain.
1269 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1270 // don't connect before giving DoS points
1271 // - Once a headers message is received that is valid and does connect,
1272 // nUnconnectingHeaders gets reset back to 0.
1273 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
1274 nodestate
->nUnconnectingHeaders
++;
1275 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
1276 LogPrint(BCLog::NET
, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1277 headers
[0].GetHash().ToString(),
1278 headers
[0].hashPrevBlock
.ToString(),
1279 pindexBestHeader
->nHeight
,
1280 pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
1281 // Set hashLastUnknownBlock for this peer, so that if we
1282 // eventually get the headers - even from a different peer -
1283 // we can use this peer to download.
1284 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
1286 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
1287 Misbehaving(pfrom
->GetId(), 20);
1292 uint256 hashLastBlock
;
1293 for (const CBlockHeader
& header
: headers
) {
1294 if (!hashLastBlock
.IsNull() && header
.hashPrevBlock
!= hashLastBlock
) {
1295 Misbehaving(pfrom
->GetId(), 20);
1296 return error("non-continuous headers sequence");
1298 hashLastBlock
= header
.GetHash();
1301 // If we don't have the last header, then they'll have given us
1302 // something new (if these headers are valid).
1303 if (mapBlockIndex
.find(hashLastBlock
) == mapBlockIndex
.end()) {
1304 received_new_header
= true;
1308 CValidationState state
;
1309 CBlockHeader first_invalid_header
;
1310 if (!ProcessNewBlockHeaders(headers
, state
, chainparams
, &pindexLast
, &first_invalid_header
)) {
1312 if (state
.IsInvalid(nDoS
)) {
1315 Misbehaving(pfrom
->GetId(), nDoS
);
1317 if (punish_duplicate_invalid
&& mapBlockIndex
.find(first_invalid_header
.GetHash()) != mapBlockIndex
.end()) {
1318 // Goal: don't allow outbound peers to use up our outbound
1319 // connection slots if they are on incompatible chains.
1321 // We ask the caller to set punish_invalid appropriately based
1322 // on the peer and the method of header delivery (compact
1323 // blocks are allowed to be invalid in some circumstances,
1325 // Here, we try to detect the narrow situation that we have a
1326 // valid block header (ie it was valid at the time the header
1327 // was received, and hence stored in mapBlockIndex) but know the
1328 // block is invalid, and that a peer has announced that same
1329 // block as being on its active chain.
1330 // Disconnect the peer in such a situation.
1332 // Note: if the header that is invalid was not accepted to our
1333 // mapBlockIndex at all, that may also be grounds for
1334 // disconnecting the peer, as the chain they are on is likely
1335 // to be incompatible. However, there is a circumstance where
1336 // that does not hold: if the header's timestamp is more than
1337 // 2 hours ahead of our current time. In that case, the header
1338 // may become valid in the future, and we don't want to
1339 // disconnect a peer merely for serving us one too-far-ahead
1340 // block header, to prevent an attacker from splitting the
1341 // network by mining a block right at the 2 hour boundary.
1343 // TODO: update the DoS logic (or, rather, rewrite the
1344 // DoS-interface between validation and net_processing) so that
1345 // the interface is cleaner, and so that we disconnect on all the
1346 // reasons that a peer's headers chain is incompatible
1347 // with ours (eg block->nVersion softforks, MTP violations,
1348 // etc), and not just the duplicate-invalid case.
1349 pfrom
->fDisconnect
= true;
1351 return error("invalid header received");
1357 CNodeState
*nodestate
= State(pfrom
->GetId());
1358 if (nodestate
->nUnconnectingHeaders
> 0) {
1359 LogPrint(BCLog::NET
, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
1361 nodestate
->nUnconnectingHeaders
= 0;
1364 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
1366 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1367 // because it is set in UpdateBlockAvailability. Some nullptr checks
1368 // are still present, however, as belt-and-suspenders.
1370 if (received_new_header
&& pindexLast
->nChainWork
> chainActive
.Tip()->nChainWork
) {
1371 nodestate
->m_last_block_announcement
= GetTime();
1374 if (nCount
== MAX_HEADERS_RESULTS
) {
1375 // Headers message had its maximum size; the peer may have more headers.
1376 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1377 // from there instead.
1378 LogPrint(BCLog::NET
, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->GetId(), pfrom
->nStartingHeight
);
1379 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256()));
1382 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
1383 // If this set of headers is valid and ends in a block with at least as
1384 // much work as our tip, download as much as possible.
1385 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
1386 std::vector
<const CBlockIndex
*> vToFetch
;
1387 const CBlockIndex
*pindexWalk
= pindexLast
;
1388 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1389 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
1390 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
1391 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
1392 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
1393 // We don't have this block, and it's not yet in flight.
1394 vToFetch
.push_back(pindexWalk
);
1396 pindexWalk
= pindexWalk
->pprev
;
1398 // If pindexWalk still isn't on our main chain, we're looking at a
1399 // very large reorg at a time we think we're close to caught up to
1400 // the main chain -- this shouldn't really happen. Bail out on the
1401 // direct fetch and rely on parallel download instead.
1402 if (!chainActive
.Contains(pindexWalk
)) {
1403 LogPrint(BCLog::NET
, "Large reorg, won't direct fetch to %s (%d)\n",
1404 pindexLast
->GetBlockHash().ToString(),
1405 pindexLast
->nHeight
);
1407 std::vector
<CInv
> vGetData
;
1408 // Download as much as possible, from earliest to latest.
1409 for (const CBlockIndex
*pindex
: reverse_iterate(vToFetch
)) {
1410 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
1411 // Can't download any more from this peer
1414 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1415 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
1416 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
);
1417 LogPrint(BCLog::NET
, "Requesting block %s from peer=%d\n",
1418 pindex
->GetBlockHash().ToString(), pfrom
->GetId());
1420 if (vGetData
.size() > 1) {
1421 LogPrint(BCLog::NET
, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1422 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
1424 if (vGetData
.size() > 0) {
1425 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
1426 // In any case, we want to download using a compact block, not a regular one
1427 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
1429 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
1433 // If we're in IBD, we want outbound peers that will serve us a useful
1434 // chain. Disconnect peers that are on chains with insufficient work.
1435 if (IsInitialBlockDownload() && nCount
!= MAX_HEADERS_RESULTS
) {
1436 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1437 // headers to fetch from this peer.
1438 if (nodestate
->pindexBestKnownBlock
&& nodestate
->pindexBestKnownBlock
->nChainWork
< nMinimumChainWork
) {
1439 // This peer has too little work on their headers chain to help
1440 // us sync -- disconnect if using an outbound slot (unless
1441 // whitelisted or addnode).
1442 // Note: We compare their tip to nMinimumChainWork (rather than
1443 // chainActive.Tip()) because we won't start block download
1444 // until we have a headers chain that has at least
1445 // nMinimumChainWork, even if a peer has a chain past our tip,
1446 // as an anti-DoS measure.
1447 if (IsOutboundDisconnectionCandidate(pfrom
)) {
1448 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom
->GetId());
1449 pfrom
->fDisconnect
= true;
1454 if (!pfrom
->fDisconnect
&& IsOutboundDisconnectionCandidate(pfrom
) && nodestate
->pindexBestKnownBlock
!= nullptr) {
1455 // If this is an outbound peer, check to see if we should protect
1456 // it from the bad/lagging chain logic.
1457 if (g_outbound_peers_with_protect_from_disconnect
< MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
&& nodestate
->pindexBestKnownBlock
->nChainWork
>= chainActive
.Tip()->nChainWork
&& !nodestate
->m_chain_sync
.m_protect
) {
1458 LogPrint(BCLog::NET
, "Protecting outbound peer=%d from eviction\n", pfrom
->GetId());
1459 nodestate
->m_chain_sync
.m_protect
= true;
1460 ++g_outbound_peers_with_protect_from_disconnect
;
1468 bool static ProcessMessage(CNode
* pfrom
, const std::string
& strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
* connman
, const std::atomic
<bool>& interruptMsgProc
)
1470 LogPrint(BCLog::NET
, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->GetId());
1471 if (gArgs
.IsArgSet("-dropmessagestest") && GetRand(gArgs
.GetArg("-dropmessagestest", 0)) == 0)
1473 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1478 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
1479 (strCommand
== NetMsgType::FILTERLOAD
||
1480 strCommand
== NetMsgType::FILTERADD
))
1482 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
1484 Misbehaving(pfrom
->GetId(), 100);
1487 pfrom
->fDisconnect
= true;
1492 if (strCommand
== NetMsgType::REJECT
)
1494 if (LogAcceptCategory(BCLog::NET
)) {
1496 std::string strMsg
; unsigned char ccode
; std::string strReason
;
1497 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
1499 std::ostringstream ss
;
1500 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
1502 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
1506 ss
<< ": hash " << hash
.ToString();
1508 LogPrint(BCLog::NET
, "Reject %s\n", SanitizeString(ss
.str()));
1509 } catch (const std::ios_base::failure
&) {
1510 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1511 LogPrint(BCLog::NET
, "Unparseable reject message received\n");
1516 else if (strCommand
== NetMsgType::VERSION
)
1518 // Each connection can only send one version message
1519 if (pfrom
->nVersion
!= 0)
1521 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, std::string("Duplicate version message")));
1523 Misbehaving(pfrom
->GetId(), 1);
1530 uint64_t nNonce
= 1;
1531 uint64_t nServiceInt
;
1532 ServiceFlags nServices
;
1535 std::string strSubVer
;
1536 std::string cleanSubVer
;
1537 int nStartingHeight
= -1;
1540 vRecv
>> nVersion
>> nServiceInt
>> nTime
>> addrMe
;
1541 nSendVersion
= std::min(nVersion
, PROTOCOL_VERSION
);
1542 nServices
= ServiceFlags(nServiceInt
);
1543 if (!pfrom
->fInbound
)
1545 connman
->SetServices(pfrom
->addr
, nServices
);
1547 if (!pfrom
->fInbound
&& !pfrom
->fFeeler
&& !pfrom
->m_manual_connection
&& !HasAllDesirableServiceFlags(nServices
))
1549 LogPrint(BCLog::NET
, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->GetId(), nServices
, GetDesirableServiceFlags(nServices
));
1550 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
1551 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices
))));
1552 pfrom
->fDisconnect
= true;
1556 if (nServices
& ((1 << 7) | (1 << 5))) {
1557 if (GetTime() < 1533096000) {
1558 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1559 // These bits have been used as a flag to indicate that a node is running incompatible
1560 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1561 // based on these service bits, at least for a while.
1562 pfrom
->fDisconnect
= true;
1567 if (nVersion
< MIN_PEER_PROTO_VERSION
)
1569 // disconnect from peers older than this proto version
1570 LogPrint(BCLog::NET
, "peer=%d using obsolete version %i; disconnecting\n", pfrom
->GetId(), nVersion
);
1571 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
1572 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
)));
1573 pfrom
->fDisconnect
= true;
1577 if (nVersion
== 10300)
1580 vRecv
>> addrFrom
>> nNonce
;
1581 if (!vRecv
.empty()) {
1582 vRecv
>> LIMITED_STRING(strSubVer
, MAX_SUBVERSION_LENGTH
);
1583 cleanSubVer
= SanitizeString(strSubVer
);
1585 if (!vRecv
.empty()) {
1586 vRecv
>> nStartingHeight
;
1590 // Disconnect if we connected to ourself
1591 if (pfrom
->fInbound
&& !connman
->CheckIncomingNonce(nNonce
))
1593 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
1594 pfrom
->fDisconnect
= true;
1598 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
1603 // Be shy and don't send version until we hear
1604 if (pfrom
->fInbound
)
1605 PushNodeVersion(pfrom
, connman
, GetAdjustedTime());
1607 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERACK
));
1609 pfrom
->nServices
= nServices
;
1610 pfrom
->SetAddrLocal(addrMe
);
1612 LOCK(pfrom
->cs_SubVer
);
1613 pfrom
->strSubVer
= strSubVer
;
1614 pfrom
->cleanSubVer
= cleanSubVer
;
1616 pfrom
->nStartingHeight
= nStartingHeight
;
1617 pfrom
->fClient
= !(nServices
& NODE_NETWORK
);
1619 LOCK(pfrom
->cs_filter
);
1620 pfrom
->fRelayTxes
= fRelay
; // set to true after we get the first filter* message
1624 pfrom
->SetSendVersion(nSendVersion
);
1625 pfrom
->nVersion
= nVersion
;
1627 if((nServices
& NODE_WITNESS
))
1630 State(pfrom
->GetId())->fHaveWitness
= true;
1633 // Potentially mark this peer as a preferred download peer.
1636 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
1639 if (!pfrom
->fInbound
)
1641 // Advertise our address
1642 if (fListen
&& !IsInitialBlockDownload())
1644 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
1645 FastRandomContext insecure_rand
;
1646 if (addr
.IsRoutable())
1648 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1649 pfrom
->PushAddress(addr
, insecure_rand
);
1650 } else if (IsPeerAddrLocalGood(pfrom
)) {
1652 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1653 pfrom
->PushAddress(addr
, insecure_rand
);
1657 // Get recent addresses
1658 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
->GetAddressCount() < 1000)
1660 connman
->PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make(NetMsgType::GETADDR
));
1661 pfrom
->fGetAddr
= true;
1663 connman
->MarkAddressGood(pfrom
->addr
);
1666 std::string remoteAddr
;
1668 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
1670 LogPrint(BCLog::NET
, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1671 cleanSubVer
, pfrom
->nVersion
,
1672 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->GetId(),
1675 int64_t nTimeOffset
= nTime
- GetTime();
1676 pfrom
->nTimeOffset
= nTimeOffset
;
1677 AddTimeData(pfrom
->addr
, nTimeOffset
);
1679 // If the peer is old enough to have the old alert system, send it the final alert.
1680 if (pfrom
->nVersion
<= 70012) {
1681 CDataStream
finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK
, PROTOCOL_VERSION
);
1682 connman
->PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make("alert", finalAlert
));
1685 // Feeler connections exist only to verify if address is online.
1686 if (pfrom
->fFeeler
) {
1687 assert(pfrom
->fInbound
== false);
1688 pfrom
->fDisconnect
= true;
1694 else if (pfrom
->nVersion
== 0)
1696 // Must have a version message before anything else
1698 Misbehaving(pfrom
->GetId(), 1);
1702 // At this point, the outgoing message serialization version can't change.
1703 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1705 if (strCommand
== NetMsgType::VERACK
)
1707 pfrom
->SetRecvVersion(std::min(pfrom
->nVersion
.load(), PROTOCOL_VERSION
));
1709 if (!pfrom
->fInbound
) {
1710 // Mark this node as currently connected, so we update its timestamp later.
1712 State(pfrom
->GetId())->fCurrentlyConnected
= true;
1713 LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n",
1714 pfrom
->nVersion
.load(), pfrom
->nStartingHeight
, pfrom
->GetId(),
1715 (fLogIPs
? strprintf(", peeraddr=%s", pfrom
->addr
.ToString()) : ""));
1718 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
1719 // Tell our peer we prefer to receive headers rather than inv's
1720 // We send this to non-NODE NETWORK peers as well, because even
1721 // non-NODE NETWORK peers can announce blocks (such as pruning
1723 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDHEADERS
));
1725 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
1726 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1727 // However, we do not request new block announcements using
1728 // cmpctblock messages.
1729 // We send this to non-NODE NETWORK peers as well, because
1730 // they may wish to request compact blocks from us
1731 bool fAnnounceUsingCMPCTBLOCK
= false;
1732 uint64_t nCMPCTBLOCKVersion
= 2;
1733 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1734 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1735 nCMPCTBLOCKVersion
= 1;
1736 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1738 pfrom
->fSuccessfullyConnected
= true;
1741 else if (!pfrom
->fSuccessfullyConnected
)
1743 // Must have a verack message before anything else
1745 Misbehaving(pfrom
->GetId(), 1);
1749 else if (strCommand
== NetMsgType::ADDR
)
1751 std::vector
<CAddress
> vAddr
;
1754 // Don't want addr from older versions unless seeding
1755 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
->GetAddressCount() > 1000)
1757 if (vAddr
.size() > 1000)
1760 Misbehaving(pfrom
->GetId(), 20);
1761 return error("message addr size() = %u", vAddr
.size());
1764 // Store the new addresses
1765 std::vector
<CAddress
> vAddrOk
;
1766 int64_t nNow
= GetAdjustedTime();
1767 int64_t nSince
= nNow
- 10 * 60;
1768 for (CAddress
& addr
: vAddr
)
1770 if (interruptMsgProc
)
1773 // We only bother storing full nodes, though this may include
1774 // things which we would not make an outbound connection to, in
1775 // part because we may make feeler connections to them.
1776 if (!MayHaveUsefulAddressDB(addr
.nServices
))
1779 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
1780 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
1781 pfrom
->AddAddressKnown(addr
);
1782 bool fReachable
= IsReachable(addr
);
1783 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
1785 // Relay to a limited number of other nodes
1786 RelayAddress(addr
, fReachable
, connman
);
1788 // Do not store addresses outside our network
1790 vAddrOk
.push_back(addr
);
1792 connman
->AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
1793 if (vAddr
.size() < 1000)
1794 pfrom
->fGetAddr
= false;
1795 if (pfrom
->fOneShot
)
1796 pfrom
->fDisconnect
= true;
1799 else if (strCommand
== NetMsgType::SENDHEADERS
)
1802 State(pfrom
->GetId())->fPreferHeaders
= true;
1805 else if (strCommand
== NetMsgType::SENDCMPCT
)
1807 bool fAnnounceUsingCMPCTBLOCK
= false;
1808 uint64_t nCMPCTBLOCKVersion
= 0;
1809 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
1810 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
1812 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1813 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
1814 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
1815 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
1817 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
1818 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
1819 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
1820 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1821 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
1823 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
1829 else if (strCommand
== NetMsgType::INV
)
1831 std::vector
<CInv
> vInv
;
1833 if (vInv
.size() > MAX_INV_SZ
)
1836 Misbehaving(pfrom
->GetId(), 20);
1837 return error("message inv size() = %u", vInv
.size());
1840 bool fBlocksOnly
= !fRelayTxes
;
1842 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1843 if (pfrom
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
1844 fBlocksOnly
= false;
1848 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1850 for (CInv
&inv
: vInv
)
1852 if (interruptMsgProc
)
1855 bool fAlreadyHave
= AlreadyHave(inv
);
1856 LogPrint(BCLog::NET
, "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->GetId());
1858 if (inv
.type
== MSG_TX
) {
1859 inv
.type
|= nFetchFlags
;
1862 if (inv
.type
== MSG_BLOCK
) {
1863 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
1864 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
1865 // We used to request the full block here, but since headers-announcements are now the
1866 // primary method of announcement on the network, and since, in the case that a node
1867 // fell back to inv we probably have a reorg which we should get the headers for first,
1868 // we now only provide a getheaders response here. When we receive the headers, we will
1869 // then ask for the blocks we need.
1870 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
));
1871 LogPrint(BCLog::NET
, "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->GetId());
1876 pfrom
->AddInventoryKnown(inv
);
1878 LogPrint(BCLog::NET
, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->GetId());
1879 } else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload()) {
1884 // Track requests for our stuff
1885 GetMainSignals().Inventory(inv
.hash
);
1890 else if (strCommand
== NetMsgType::GETDATA
)
1892 std::vector
<CInv
> vInv
;
1894 if (vInv
.size() > MAX_INV_SZ
)
1897 Misbehaving(pfrom
->GetId(), 20);
1898 return error("message getdata size() = %u", vInv
.size());
1901 LogPrint(BCLog::NET
, "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->GetId());
1903 if (vInv
.size() > 0) {
1904 LogPrint(BCLog::NET
, "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->GetId());
1907 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
1908 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1912 else if (strCommand
== NetMsgType::GETBLOCKS
)
1914 CBlockLocator locator
;
1916 vRecv
>> locator
>> hashStop
;
1918 // We might have announced the currently-being-connected tip using a
1919 // compact block, which resulted in the peer sending a getblocks
1920 // request, which we would otherwise respond to without the new block.
1921 // To avoid this situation we simply verify that we are on our best
1922 // known chain now. This is super overkill, but we handle it better
1923 // for getheaders requests, and there are no known nodes which support
1924 // compact blocks but still use getblocks to request blocks.
1926 std::shared_ptr
<const CBlock
> a_recent_block
;
1928 LOCK(cs_most_recent_block
);
1929 a_recent_block
= most_recent_block
;
1931 CValidationState dummy
;
1932 ActivateBestChain(dummy
, Params(), a_recent_block
);
1937 // Find the last block the caller has in the main chain
1938 const CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1940 // Send the rest of the chain
1942 pindex
= chainActive
.Next(pindex
);
1944 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());
1945 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1947 if (pindex
->GetBlockHash() == hashStop
)
1949 LogPrint(BCLog::NET
, " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1952 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1953 // for some reasonable time window (1 hour) that block relay might require.
1954 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
1955 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
1957 LogPrint(BCLog::NET
, " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1960 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
1963 // When this block is requested, we'll send an inv that'll
1964 // trigger the peer to getblocks the next batch of inventory.
1965 LogPrint(BCLog::NET
, " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1966 pfrom
->hashContinue
= pindex
->GetBlockHash();
1973 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
1975 BlockTransactionsRequest req
;
1978 std::shared_ptr
<const CBlock
> recent_block
;
1980 LOCK(cs_most_recent_block
);
1981 if (most_recent_block_hash
== req
.blockhash
)
1982 recent_block
= most_recent_block
;
1983 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1986 SendBlockTransactions(*recent_block
, req
, pfrom
, connman
);
1992 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
1993 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
1994 LogPrint(BCLog::NET
, "Peer %d sent us a getblocktxn for a block we don't have", pfrom
->GetId());
1998 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
1999 // If an older block is requested (should never happen in practice,
2000 // but can happen in tests) send a block response instead of a
2001 // blocktxn response. Sending a full block response instead of a
2002 // small blocktxn response is preferable in the case where a peer
2003 // might maliciously send lots of getblocktxn requests to trigger
2004 // expensive disk reads, because it will require the peer to
2005 // actually receive all the data read from disk over the network.
2006 LogPrint(BCLog::NET
, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->GetId(), MAX_BLOCKTXN_DEPTH
);
2008 inv
.type
= State(pfrom
->GetId())->fWantsCmpctWitness
? MSG_WITNESS_BLOCK
: MSG_BLOCK
;
2009 inv
.hash
= req
.blockhash
;
2010 pfrom
->vRecvGetData
.push_back(inv
);
2011 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2016 bool ret
= ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus());
2019 SendBlockTransactions(block
, req
, pfrom
, connman
);
2023 else if (strCommand
== NetMsgType::GETHEADERS
)
2025 CBlockLocator locator
;
2027 vRecv
>> locator
>> hashStop
;
2030 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
2031 LogPrint(BCLog::NET
, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->GetId());
2035 CNodeState
*nodestate
= State(pfrom
->GetId());
2036 const CBlockIndex
* pindex
= nullptr;
2037 if (locator
.IsNull())
2039 // If locator is null, return the hashStop block
2040 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
2041 if (mi
== mapBlockIndex
.end())
2043 pindex
= (*mi
).second
;
2045 if (!BlockRequestAllowed(pindex
, chainparams
.GetConsensus())) {
2046 LogPrint(BCLog::NET
, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__
, pfrom
->GetId());
2052 // Find the last block the caller has in the main chain
2053 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
2055 pindex
= chainActive
.Next(pindex
);
2058 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2059 std::vector
<CBlock
> vHeaders
;
2060 int nLimit
= MAX_HEADERS_RESULTS
;
2061 LogPrint(BCLog::NET
, "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->GetId());
2062 for (; pindex
; pindex
= chainActive
.Next(pindex
))
2064 vHeaders
.push_back(pindex
->GetBlockHeader());
2065 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
2068 // pindex can be nullptr either if we sent chainActive.Tip() OR
2069 // if our peer has chainActive.Tip() (and thus we are sending an empty
2070 // headers message). In both cases it's safe to update
2071 // pindexBestHeaderSent to be our tip.
2073 // It is important that we simply reset the BestHeaderSent value here,
2074 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2075 // the currently-being-connected tip using a compact block, which
2076 // resulted in the peer sending a headers request, which we respond to
2077 // without the new block. By resetting the BestHeaderSent, we ensure we
2078 // will re-announce the new block via headers (or compact blocks again)
2079 // in the SendMessages logic.
2080 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
2081 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
2085 else if (strCommand
== NetMsgType::TX
)
2087 // Stop processing the transaction early if
2088 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2089 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !gArgs
.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
2091 LogPrint(BCLog::NET
, "transaction sent in violation of protocol peer=%d\n", pfrom
->GetId());
2095 std::deque
<COutPoint
> vWorkQueue
;
2096 std::vector
<uint256
> vEraseQueue
;
2097 CTransactionRef ptx
;
2099 const CTransaction
& tx
= *ptx
;
2101 CInv
inv(MSG_TX
, tx
.GetHash());
2102 pfrom
->AddInventoryKnown(inv
);
2106 bool fMissingInputs
= false;
2107 CValidationState state
;
2109 pfrom
->setAskFor
.erase(inv
.hash
);
2110 mapAlreadyAskedFor
.erase(inv
.hash
);
2112 std::list
<CTransactionRef
> lRemovedTxn
;
2114 if (!AlreadyHave(inv
) &&
2115 AcceptToMemoryPool(mempool
, state
, ptx
, &fMissingInputs
, &lRemovedTxn
, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2116 mempool
.check(pcoinsTip
.get());
2117 RelayTransaction(tx
, connman
);
2118 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
2119 vWorkQueue
.emplace_back(inv
.hash
, i
);
2122 pfrom
->nLastTXTime
= GetTime();
2124 LogPrint(BCLog::MEMPOOL
, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2126 tx
.GetHash().ToString(),
2127 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
2129 // Recursively process any orphan transactions that depended on this one
2130 std::set
<NodeId
> setMisbehaving
;
2131 while (!vWorkQueue
.empty()) {
2132 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
2133 vWorkQueue
.pop_front();
2134 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
2136 for (auto mi
= itByPrev
->second
.begin();
2137 mi
!= itByPrev
->second
.end();
2140 const CTransactionRef
& porphanTx
= (*mi
)->second
.tx
;
2141 const CTransaction
& orphanTx
= *porphanTx
;
2142 const uint256
& orphanHash
= orphanTx
.GetHash();
2143 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
2144 bool fMissingInputs2
= false;
2145 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2146 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2147 // anyone relaying LegitTxX banned)
2148 CValidationState stateDummy
;
2151 if (setMisbehaving
.count(fromPeer
))
2153 if (AcceptToMemoryPool(mempool
, stateDummy
, porphanTx
, &fMissingInputs2
, &lRemovedTxn
, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2154 LogPrint(BCLog::MEMPOOL
, " accepted orphan tx %s\n", orphanHash
.ToString());
2155 RelayTransaction(orphanTx
, connman
);
2156 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
2157 vWorkQueue
.emplace_back(orphanHash
, i
);
2159 vEraseQueue
.push_back(orphanHash
);
2161 else if (!fMissingInputs2
)
2164 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
2166 // Punish peer that gave us an invalid orphan tx
2167 Misbehaving(fromPeer
, nDos
);
2168 setMisbehaving
.insert(fromPeer
);
2169 LogPrint(BCLog::MEMPOOL
, " invalid orphan tx %s\n", orphanHash
.ToString());
2171 // Has inputs but not accepted to mempool
2172 // Probably non-standard or insufficient fee
2173 LogPrint(BCLog::MEMPOOL
, " removed orphan tx %s\n", orphanHash
.ToString());
2174 vEraseQueue
.push_back(orphanHash
);
2175 if (!orphanTx
.HasWitness() && !stateDummy
.CorruptionPossible()) {
2176 // Do not use rejection cache for witness transactions or
2177 // witness-stripped transactions, as they can have been malleated.
2178 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2179 assert(recentRejects
);
2180 recentRejects
->insert(orphanHash
);
2183 mempool
.check(pcoinsTip
.get());
2187 for (uint256 hash
: vEraseQueue
)
2188 EraseOrphanTx(hash
);
2190 else if (fMissingInputs
)
2192 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
2193 for (const CTxIn
& txin
: tx
.vin
) {
2194 if (recentRejects
->contains(txin
.prevout
.hash
)) {
2195 fRejectedParents
= true;
2199 if (!fRejectedParents
) {
2200 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
2201 for (const CTxIn
& txin
: tx
.vin
) {
2202 CInv
_inv(MSG_TX
| nFetchFlags
, txin
.prevout
.hash
);
2203 pfrom
->AddInventoryKnown(_inv
);
2204 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
2206 AddOrphanTx(ptx
, pfrom
->GetId());
2208 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2209 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, gArgs
.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
2210 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
2212 LogPrint(BCLog::MEMPOOL
, "mapOrphan overflow, removed %u tx\n", nEvicted
);
2215 LogPrint(BCLog::MEMPOOL
, "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
2216 // We will continue to reject this tx since it has rejected
2217 // parents so avoid re-requesting it from other peers.
2218 recentRejects
->insert(tx
.GetHash());
2221 if (!tx
.HasWitness() && !state
.CorruptionPossible()) {
2222 // Do not use rejection cache for witness transactions or
2223 // witness-stripped transactions, as they can have been malleated.
2224 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2225 assert(recentRejects
);
2226 recentRejects
->insert(tx
.GetHash());
2227 if (RecursiveDynamicUsage(*ptx
) < 100000) {
2228 AddToCompactExtraTransactions(ptx
);
2230 } else if (tx
.HasWitness() && RecursiveDynamicUsage(*ptx
) < 100000) {
2231 AddToCompactExtraTransactions(ptx
);
2234 if (pfrom
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
2235 // Always relay transactions received from whitelisted peers, even
2236 // if they were already in the mempool or rejected from it due
2237 // to policy, allowing the node to function as a gateway for
2238 // nodes hidden behind it.
2240 // Never relay transactions that we would assign a non-zero DoS
2241 // score for, as we expect peers to do the same with us in that
2244 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
2245 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->GetId());
2246 RelayTransaction(tx
, connman
);
2248 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->GetId(), FormatStateMessage(state
));
2253 for (const CTransactionRef
& removedTx
: lRemovedTxn
)
2254 AddToCompactExtraTransactions(removedTx
);
2257 if (state
.IsInvalid(nDoS
))
2259 LogPrint(BCLog::MEMPOOLREJ
, "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
2261 FormatStateMessage(state
));
2262 if (state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
2263 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
2264 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
));
2266 Misbehaving(pfrom
->GetId(), nDoS
);
2272 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2274 CBlockHeaderAndShortTxIDs cmpctblock
;
2275 vRecv
>> cmpctblock
;
2277 bool received_new_header
= false;
2282 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
2283 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2284 if (!IsInitialBlockDownload())
2285 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
2289 if (mapBlockIndex
.find(cmpctblock
.header
.GetHash()) == mapBlockIndex
.end()) {
2290 received_new_header
= true;
2294 const CBlockIndex
*pindex
= nullptr;
2295 CValidationState state
;
2296 if (!ProcessNewBlockHeaders({cmpctblock
.header
}, state
, chainparams
, &pindex
)) {
2298 if (state
.IsInvalid(nDoS
)) {
2300 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->GetId());
2302 Misbehaving(pfrom
->GetId(), nDoS
);
2304 LogPrint(BCLog::NET
, "Peer %d sent us invalid header via cmpctblock\n", pfrom
->GetId());
2310 // When we succeed in decoding a block's txids from a cmpctblock
2311 // message we typically jump to the BLOCKTXN handling code, with a
2312 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2313 // completing processing of the putative block (without cs_main).
2314 bool fProcessBLOCKTXN
= false;
2315 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2317 // If we end up treating this as a plain headers message, call that as well
2319 bool fRevertToHeaderProcessing
= false;
2321 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2323 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2324 bool fBlockReconstructed
= false;
2328 // If AcceptBlockHeader returned true, it set pindex
2330 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
2332 CNodeState
*nodestate
= State(pfrom
->GetId());
2334 // If this was a new header with more work than our tip, update the
2335 // peer's last block announcement time
2336 if (received_new_header
&& pindex
->nChainWork
> chainActive
.Tip()->nChainWork
) {
2337 nodestate
->m_last_block_announcement
= GetTime();
2340 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
2341 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
2343 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
2346 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
2347 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
2348 if (fAlreadyInFlight
) {
2349 // We requested this block for some reason, but our mempool will probably be useless
2350 // so we just grab the block via normal getdata
2351 std::vector
<CInv
> vInv(1);
2352 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2353 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2358 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2359 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
2362 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
2363 // Don't bother trying to process compact blocks from v1 peers
2364 // after segwit activates.
2368 // We want to be a bit conservative just to be extra careful about DoS
2369 // possibilities in compact block processing...
2370 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
2371 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
2372 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
2373 std::list
<QueuedBlock
>::iterator
* queuedBlockIt
= nullptr;
2374 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
, &queuedBlockIt
)) {
2375 if (!(*queuedBlockIt
)->partialBlock
)
2376 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
2378 // The block was already in flight using compact blocks from the same peer
2379 LogPrint(BCLog::NET
, "Peer sent us compact block we were already syncing!\n");
2384 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
2385 ReadStatus status
= partialBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2386 if (status
== READ_STATUS_INVALID
) {
2387 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
2388 Misbehaving(pfrom
->GetId(), 100);
2389 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->GetId());
2391 } else if (status
== READ_STATUS_FAILED
) {
2392 // Duplicate txindexes, the block is now in-flight, so just request it
2393 std::vector
<CInv
> vInv(1);
2394 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2395 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2399 BlockTransactionsRequest req
;
2400 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
2401 if (!partialBlock
.IsTxAvailable(i
))
2402 req
.indexes
.push_back(i
);
2404 if (req
.indexes
.empty()) {
2405 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2406 BlockTransactions txn
;
2407 txn
.blockhash
= cmpctblock
.header
.GetHash();
2409 fProcessBLOCKTXN
= true;
2411 req
.blockhash
= pindex
->GetBlockHash();
2412 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETBLOCKTXN
, req
));
2415 // This block is either already in flight from a different
2416 // peer, or this peer has too many blocks outstanding to
2418 // Optimistically try to reconstruct anyway since we might be
2419 // able to without any round trips.
2420 PartiallyDownloadedBlock
tempBlock(&mempool
);
2421 ReadStatus status
= tempBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2422 if (status
!= READ_STATUS_OK
) {
2423 // TODO: don't ignore failures
2426 std::vector
<CTransactionRef
> dummy
;
2427 status
= tempBlock
.FillBlock(*pblock
, dummy
);
2428 if (status
== READ_STATUS_OK
) {
2429 fBlockReconstructed
= true;
2433 if (fAlreadyInFlight
) {
2434 // We requested this block, but its far into the future, so our
2435 // mempool will probably be useless - request the block normally
2436 std::vector
<CInv
> vInv(1);
2437 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2438 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2441 // If this was an announce-cmpctblock, we want the same treatment as a header message
2442 fRevertToHeaderProcessing
= true;
2447 if (fProcessBLOCKTXN
)
2448 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2450 if (fRevertToHeaderProcessing
) {
2451 // Headers received from HB compact block peers are permitted to be
2452 // relayed before full validation (see BIP 152), so we don't want to disconnect
2453 // the peer if the header turns out to be for an invalid block.
2454 // Note that if a peer tries to build on an invalid chain, that
2455 // will be detected and the peer will be banned.
2456 return ProcessHeadersMessage(pfrom
, connman
, {cmpctblock
.header
}, chainparams
, /*punish_duplicate_invalid=*/false);
2459 if (fBlockReconstructed
) {
2460 // If we got here, we were able to optimistically reconstruct a
2461 // block that is in flight from some other peer.
2464 mapBlockSource
.emplace(pblock
->GetHash(), std::make_pair(pfrom
->GetId(), false));
2466 bool fNewBlock
= false;
2467 // Setting fForceProcessing to true means that we bypass some of
2468 // our anti-DoS protections in AcceptBlock, which filters
2469 // unrequested blocks that might be trying to waste our resources
2470 // (eg disk space). Because we only try to reconstruct blocks when
2471 // we're close to caught up (via the CanDirectFetch() requirement
2472 // above, combined with the behavior of not requesting blocks until
2473 // we have a chain with at least nMinimumChainWork), and we ignore
2474 // compact blocks with less work than our tip, it is safe to treat
2475 // reconstructed compact blocks as having been requested.
2476 ProcessNewBlock(chainparams
, pblock
, /*fForceProcessing=*/true, &fNewBlock
);
2478 pfrom
->nLastBlockTime
= GetTime();
2481 mapBlockSource
.erase(pblock
->GetHash());
2483 LOCK(cs_main
); // hold cs_main for CBlockIndex::IsValid()
2484 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
)) {
2485 // Clear download state for this block, which is in
2486 // process from some other peer. We do this after calling
2487 // ProcessNewBlock so that a malleated cmpctblock announcement
2488 // can't be used to interfere with block relay.
2489 MarkBlockAsReceived(pblock
->GetHash());
2495 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2497 BlockTransactions resp
;
2500 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2501 bool fBlockRead
= false;
2505 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
2506 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
2507 it
->second
.first
!= pfrom
->GetId()) {
2508 LogPrint(BCLog::NET
, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->GetId());
2512 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
2513 ReadStatus status
= partialBlock
.FillBlock(*pblock
, resp
.txn
);
2514 if (status
== READ_STATUS_INVALID
) {
2515 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
2516 Misbehaving(pfrom
->GetId(), 100);
2517 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->GetId());
2519 } else if (status
== READ_STATUS_FAILED
) {
2520 // Might have collided, fall back to getdata now :(
2521 std::vector
<CInv
> invs
;
2522 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), resp
.blockhash
));
2523 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, invs
));
2525 // Block is either okay, or possibly we received
2526 // READ_STATUS_CHECKBLOCK_FAILED.
2527 // Note that CheckBlock can only fail for one of a few reasons:
2528 // 1. bad-proof-of-work (impossible here, because we've already
2529 // accepted the header)
2530 // 2. merkleroot doesn't match the transactions given (already
2531 // caught in FillBlock with READ_STATUS_FAILED, so
2533 // 3. the block is otherwise invalid (eg invalid coinbase,
2534 // block is too big, too many legacy sigops, etc).
2535 // So if CheckBlock failed, #3 is the only possibility.
2536 // Under BIP 152, we don't DoS-ban unless proof of work is
2537 // invalid (we don't require all the stateless checks to have
2538 // been run). This is handled below, so just treat this as
2539 // though the block was successfully read, and rely on the
2540 // handling in ProcessNewBlock to ensure the block index is
2541 // updated, reject messages go out, etc.
2542 MarkBlockAsReceived(resp
.blockhash
); // it is now an empty pointer
2544 // mapBlockSource is only used for sending reject messages and DoS scores,
2545 // so the race between here and cs_main in ProcessNewBlock is fine.
2546 // BIP 152 permits peers to relay compact blocks after validating
2547 // the header only; we should not punish peers if the block turns
2548 // out to be invalid.
2549 mapBlockSource
.emplace(resp
.blockhash
, std::make_pair(pfrom
->GetId(), false));
2551 } // Don't hold cs_main when we call into ProcessNewBlock
2553 bool fNewBlock
= false;
2554 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2555 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2556 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2557 // disk-space attacks), but this should be safe due to the
2558 // protections in the compact block handler -- see related comment
2559 // in compact block optimistic reconstruction handling.
2560 ProcessNewBlock(chainparams
, pblock
, /*fForceProcessing=*/true, &fNewBlock
);
2562 pfrom
->nLastBlockTime
= GetTime();
2565 mapBlockSource
.erase(pblock
->GetHash());
2571 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
2573 std::vector
<CBlockHeader
> headers
;
2575 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2576 unsigned int nCount
= ReadCompactSize(vRecv
);
2577 if (nCount
> MAX_HEADERS_RESULTS
) {
2579 Misbehaving(pfrom
->GetId(), 20);
2580 return error("headers message size = %u", nCount
);
2582 headers
.resize(nCount
);
2583 for (unsigned int n
= 0; n
< nCount
; n
++) {
2584 vRecv
>> headers
[n
];
2585 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
2588 // Headers received via a HEADERS message should be valid, and reflect
2589 // the chain the peer is on. If we receive a known-invalid header,
2590 // disconnect the peer if it is using one of our outbound connection
2592 bool should_punish
= !pfrom
->fInbound
&& !pfrom
->m_manual_connection
;
2593 return ProcessHeadersMessage(pfrom
, connman
, headers
, chainparams
, should_punish
);
2596 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2598 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2601 LogPrint(BCLog::NET
, "received block %s peer=%d\n", pblock
->GetHash().ToString(), pfrom
->GetId());
2603 bool forceProcessing
= false;
2604 const uint256
hash(pblock
->GetHash());
2607 // Also always process if we requested the block explicitly, as we may
2608 // need it even though it is not a candidate for a new best tip.
2609 forceProcessing
|= MarkBlockAsReceived(hash
);
2610 // mapBlockSource is only used for sending reject messages and DoS scores,
2611 // so the race between here and cs_main in ProcessNewBlock is fine.
2612 mapBlockSource
.emplace(hash
, std::make_pair(pfrom
->GetId(), true));
2614 bool fNewBlock
= false;
2615 ProcessNewBlock(chainparams
, pblock
, forceProcessing
, &fNewBlock
);
2617 pfrom
->nLastBlockTime
= GetTime();
2620 mapBlockSource
.erase(pblock
->GetHash());
2625 else if (strCommand
== NetMsgType::GETADDR
)
2627 // This asymmetric behavior for inbound and outbound connections was introduced
2628 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2629 // to users' AddrMan and later request them by sending getaddr messages.
2630 // Making nodes which are behind NAT and can only make outgoing connections ignore
2631 // the getaddr message mitigates the attack.
2632 if (!pfrom
->fInbound
) {
2633 LogPrint(BCLog::NET
, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->GetId());
2637 // Only send one GetAddr response per connection to reduce resource waste
2638 // and discourage addr stamping of INV announcements.
2639 if (pfrom
->fSentAddr
) {
2640 LogPrint(BCLog::NET
, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->GetId());
2643 pfrom
->fSentAddr
= true;
2645 pfrom
->vAddrToSend
.clear();
2646 std::vector
<CAddress
> vAddr
= connman
->GetAddresses();
2647 FastRandomContext insecure_rand
;
2648 for (const CAddress
&addr
: vAddr
)
2649 pfrom
->PushAddress(addr
, insecure_rand
);
2653 else if (strCommand
== NetMsgType::MEMPOOL
)
2655 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
2657 LogPrint(BCLog::NET
, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
2658 pfrom
->fDisconnect
= true;
2662 if (connman
->OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
2664 LogPrint(BCLog::NET
, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
2665 pfrom
->fDisconnect
= true;
2669 LOCK(pfrom
->cs_inventory
);
2670 pfrom
->fSendMempool
= true;
2674 else if (strCommand
== NetMsgType::PING
)
2676 if (pfrom
->nVersion
> BIP0031_VERSION
)
2680 // Echo the message back with the nonce. This allows for two useful features:
2682 // 1) A remote node can quickly check if the connection is operational
2683 // 2) Remote nodes can measure the latency of the network thread. If this node
2684 // is overloaded it won't respond to pings quickly and the remote node can
2685 // avoid sending us more work, like chain download requests.
2687 // The nonce stops the remote getting confused between different pings: without
2688 // it, if the remote node sends a ping once per second and this node takes 5
2689 // seconds to respond to each, the 5th ping the remote sends would appear to
2690 // return very quickly.
2691 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::PONG
, nonce
));
2696 else if (strCommand
== NetMsgType::PONG
)
2698 int64_t pingUsecEnd
= nTimeReceived
;
2700 size_t nAvail
= vRecv
.in_avail();
2701 bool bPingFinished
= false;
2702 std::string sProblem
;
2704 if (nAvail
>= sizeof(nonce
)) {
2707 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2708 if (pfrom
->nPingNonceSent
!= 0) {
2709 if (nonce
== pfrom
->nPingNonceSent
) {
2710 // Matching pong received, this ping is no longer outstanding
2711 bPingFinished
= true;
2712 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
2713 if (pingUsecTime
> 0) {
2714 // Successful ping time measurement, replace previous
2715 pfrom
->nPingUsecTime
= pingUsecTime
;
2716 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
.load(), pingUsecTime
);
2718 // This should never happen
2719 sProblem
= "Timing mishap";
2722 // Nonce mismatches are normal when pings are overlapping
2723 sProblem
= "Nonce mismatch";
2725 // This is most likely a bug in another implementation somewhere; cancel this ping
2726 bPingFinished
= true;
2727 sProblem
= "Nonce zero";
2731 sProblem
= "Unsolicited pong without ping";
2734 // This is most likely a bug in another implementation somewhere; cancel this ping
2735 bPingFinished
= true;
2736 sProblem
= "Short payload";
2739 if (!(sProblem
.empty())) {
2740 LogPrint(BCLog::NET
, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2743 pfrom
->nPingNonceSent
,
2747 if (bPingFinished
) {
2748 pfrom
->nPingNonceSent
= 0;
2753 else if (strCommand
== NetMsgType::FILTERLOAD
)
2755 CBloomFilter filter
;
2758 if (!filter
.IsWithinSizeConstraints())
2760 // There is no excuse for sending a too-large filter
2762 Misbehaving(pfrom
->GetId(), 100);
2766 LOCK(pfrom
->cs_filter
);
2767 pfrom
->pfilter
.reset(new CBloomFilter(filter
));
2768 pfrom
->pfilter
->UpdateEmptyFull();
2769 pfrom
->fRelayTxes
= true;
2774 else if (strCommand
== NetMsgType::FILTERADD
)
2776 std::vector
<unsigned char> vData
;
2779 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2780 // and thus, the maximum size any matched object can have) in a filteradd message
2782 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
2785 LOCK(pfrom
->cs_filter
);
2786 if (pfrom
->pfilter
) {
2787 pfrom
->pfilter
->insert(vData
);
2794 Misbehaving(pfrom
->GetId(), 100);
2799 else if (strCommand
== NetMsgType::FILTERCLEAR
)
2801 LOCK(pfrom
->cs_filter
);
2802 if (pfrom
->GetLocalServices() & NODE_BLOOM
) {
2803 pfrom
->pfilter
.reset(new CBloomFilter());
2805 pfrom
->fRelayTxes
= true;
2808 else if (strCommand
== NetMsgType::FEEFILTER
) {
2809 CAmount newFeeFilter
= 0;
2810 vRecv
>> newFeeFilter
;
2811 if (MoneyRange(newFeeFilter
)) {
2813 LOCK(pfrom
->cs_feeFilter
);
2814 pfrom
->minFeeFilter
= newFeeFilter
;
2816 LogPrint(BCLog::NET
, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->GetId());
2820 else if (strCommand
== NetMsgType::NOTFOUND
) {
2821 // We do not care about the NOTFOUND message, but logging an Unknown Command
2822 // message would be undesirable as we transmit it ourselves.
2826 // Ignore unknown commands for extensibility
2827 LogPrint(BCLog::NET
, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->GetId());
2835 static bool SendRejectsAndCheckIfBanned(CNode
* pnode
, CConnman
* connman
)
2837 AssertLockHeld(cs_main
);
2838 CNodeState
&state
= *State(pnode
->GetId());
2840 for (const CBlockReject
& reject
: state
.rejects
) {
2841 connman
->PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, (std::string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
));
2843 state
.rejects
.clear();
2845 if (state
.fShouldBan
) {
2846 state
.fShouldBan
= false;
2847 if (pnode
->fWhitelisted
)
2848 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode
->addr
.ToString());
2849 else if (pnode
->m_manual_connection
)
2850 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode
->addr
.ToString());
2852 pnode
->fDisconnect
= true;
2853 if (pnode
->addr
.IsLocal())
2854 LogPrintf("Warning: not banning local peer %s!\n", pnode
->addr
.ToString());
2857 connman
->Ban(pnode
->addr
, BanReasonNodeMisbehaving
);
2865 bool PeerLogicValidation::ProcessMessages(CNode
* pfrom
, std::atomic
<bool>& interruptMsgProc
)
2867 const CChainParams
& chainparams
= Params();
2870 // (4) message start
2876 bool fMoreWork
= false;
2878 if (!pfrom
->vRecvGetData
.empty())
2879 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2881 if (pfrom
->fDisconnect
)
2884 // this maintains the order of responses
2885 if (!pfrom
->vRecvGetData
.empty()) return true;
2887 // Don't bother if send buffer is too full to respond anyway
2888 if (pfrom
->fPauseSend
)
2891 std::list
<CNetMessage
> msgs
;
2893 LOCK(pfrom
->cs_vProcessMsg
);
2894 if (pfrom
->vProcessMsg
.empty())
2896 // Just take one message
2897 msgs
.splice(msgs
.begin(), pfrom
->vProcessMsg
, pfrom
->vProcessMsg
.begin());
2898 pfrom
->nProcessQueueSize
-= msgs
.front().vRecv
.size() + CMessageHeader::HEADER_SIZE
;
2899 pfrom
->fPauseRecv
= pfrom
->nProcessQueueSize
> connman
->GetReceiveFloodSize();
2900 fMoreWork
= !pfrom
->vProcessMsg
.empty();
2902 CNetMessage
& msg(msgs
.front());
2904 msg
.SetVersion(pfrom
->GetRecvVersion());
2905 // Scan for message start
2906 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
2907 LogPrint(BCLog::NET
, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->GetId());
2908 pfrom
->fDisconnect
= true;
2913 CMessageHeader
& hdr
= msg
.hdr
;
2914 if (!hdr
.IsValid(chainparams
.MessageStart()))
2916 LogPrint(BCLog::NET
, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->GetId());
2919 std::string strCommand
= hdr
.GetCommand();
2922 unsigned int nMessageSize
= hdr
.nMessageSize
;
2925 CDataStream
& vRecv
= msg
.vRecv
;
2926 const uint256
& hash
= msg
.GetMessageHash();
2927 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
2929 LogPrint(BCLog::NET
, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
2930 SanitizeString(strCommand
), nMessageSize
,
2931 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
2932 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
2940 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
, interruptMsgProc
);
2941 if (interruptMsgProc
)
2943 if (!pfrom
->vRecvGetData
.empty())
2946 catch (const std::ios_base::failure
& e
)
2948 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, std::string("error parsing message")));
2949 if (strstr(e
.what(), "end of data"))
2951 // Allow exceptions from under-length message on vRecv
2952 LogPrint(BCLog::NET
, "%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2954 else if (strstr(e
.what(), "size too large"))
2956 // Allow exceptions from over-long size
2957 LogPrint(BCLog::NET
, "%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2959 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
2961 // Allow exceptions from non-canonical encoding
2962 LogPrint(BCLog::NET
, "%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2966 PrintExceptionContinue(&e
, "ProcessMessages()");
2969 catch (const std::exception
& e
) {
2970 PrintExceptionContinue(&e
, "ProcessMessages()");
2972 PrintExceptionContinue(nullptr, "ProcessMessages()");
2976 LogPrint(BCLog::NET
, "%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->GetId());
2980 SendRejectsAndCheckIfBanned(pfrom
, connman
);
2985 void PeerLogicValidation::ConsiderEviction(CNode
*pto
, int64_t time_in_seconds
)
2987 AssertLockHeld(cs_main
);
2989 CNodeState
&state
= *State(pto
->GetId());
2990 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
2992 if (!state
.m_chain_sync
.m_protect
&& IsOutboundDisconnectionCandidate(pto
) && state
.fSyncStarted
) {
2993 // This is an outbound peer subject to disconnection if they don't
2994 // announce a block with as much work as the current tip within
2995 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
2996 // their chain has more work than ours, we should sync to it,
2997 // unless it's invalid, in which case we should find that out and
2998 // disconnect from them elsewhere).
2999 if (state
.pindexBestKnownBlock
!= nullptr && state
.pindexBestKnownBlock
->nChainWork
>= chainActive
.Tip()->nChainWork
) {
3000 if (state
.m_chain_sync
.m_timeout
!= 0) {
3001 state
.m_chain_sync
.m_timeout
= 0;
3002 state
.m_chain_sync
.m_work_header
= nullptr;
3003 state
.m_chain_sync
.m_sent_getheaders
= false;
3005 } else if (state
.m_chain_sync
.m_timeout
== 0 || (state
.m_chain_sync
.m_work_header
!= nullptr && state
.pindexBestKnownBlock
!= nullptr && state
.pindexBestKnownBlock
->nChainWork
>= state
.m_chain_sync
.m_work_header
->nChainWork
)) {
3006 // Our best block known by this peer is behind our tip, and we're either noticing
3007 // that for the first time, OR this peer was able to catch up to some earlier point
3008 // where we checked against our tip.
3009 // Either way, set a new timeout based on current tip.
3010 state
.m_chain_sync
.m_timeout
= time_in_seconds
+ CHAIN_SYNC_TIMEOUT
;
3011 state
.m_chain_sync
.m_work_header
= chainActive
.Tip();
3012 state
.m_chain_sync
.m_sent_getheaders
= false;
3013 } else if (state
.m_chain_sync
.m_timeout
> 0 && time_in_seconds
> state
.m_chain_sync
.m_timeout
) {
3014 // No evidence yet that our peer has synced to a chain with work equal to that
3015 // of our tip, when we first detected it was behind. Send a single getheaders
3016 // message to give the peer a chance to update us.
3017 if (state
.m_chain_sync
.m_sent_getheaders
) {
3018 // They've run out of time to catch up!
3019 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto
->GetId(), state
.pindexBestKnownBlock
!= nullptr ? state
.pindexBestKnownBlock
->GetBlockHash().ToString() : "<none>");
3020 pto
->fDisconnect
= true;
3022 assert(state
.m_chain_sync
.m_work_header
);
3023 LogPrint(BCLog::NET
, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto
->GetId(), state
.pindexBestKnownBlock
!= nullptr ? state
.pindexBestKnownBlock
->GetBlockHash().ToString() : "<none>", state
.m_chain_sync
.m_work_header
->GetBlockHash().ToString());
3024 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(state
.m_chain_sync
.m_work_header
->pprev
), uint256()));
3025 state
.m_chain_sync
.m_sent_getheaders
= true;
3026 constexpr int64_t HEADERS_RESPONSE_TIME
= 120; // 2 minutes
3027 // Bump the timeout to allow a response, which could clear the timeout
3028 // (if the response shows the peer has synced), reset the timeout (if
3029 // the peer syncs to the required work but not to our tip), or result
3030 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3031 // has not sufficiently progressed)
3032 state
.m_chain_sync
.m_timeout
= time_in_seconds
+ HEADERS_RESPONSE_TIME
;
3038 void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds
)
3040 // Check whether we have too many outbound peers
3041 int extra_peers
= connman
->GetExtraOutboundCount();
3042 if (extra_peers
> 0) {
3043 // If we have more outbound peers than we target, disconnect one.
3044 // Pick the outbound peer that least recently announced
3045 // us a new block, with ties broken by choosing the more recent
3046 // connection (higher node id)
3047 NodeId worst_peer
= -1;
3048 int64_t oldest_block_announcement
= std::numeric_limits
<int64_t>::max();
3052 connman
->ForEachNode([&](CNode
* pnode
) {
3053 // Ignore non-outbound peers, or nodes marked for disconnect already
3054 if (!IsOutboundDisconnectionCandidate(pnode
) || pnode
->fDisconnect
) return;
3055 CNodeState
*state
= State(pnode
->GetId());
3056 if (state
== nullptr) return; // shouldn't be possible, but just in case
3057 // Don't evict our protected peers
3058 if (state
->m_chain_sync
.m_protect
) return;
3059 if (state
->m_last_block_announcement
< oldest_block_announcement
|| (state
->m_last_block_announcement
== oldest_block_announcement
&& pnode
->GetId() > worst_peer
)) {
3060 worst_peer
= pnode
->GetId();
3061 oldest_block_announcement
= state
->m_last_block_announcement
;
3064 if (worst_peer
!= -1) {
3065 bool disconnected
= connman
->ForNode(worst_peer
, [&](CNode
*pnode
) {
3066 // Only disconnect a peer that has been connected to us for
3067 // some reasonable fraction of our check-frequency, to give
3068 // it time for new information to have arrived.
3069 // Also don't disconnect any peer we're trying to download a
3071 CNodeState
&state
= *State(pnode
->GetId());
3072 if (time_in_seconds
- pnode
->nTimeConnected
> MINIMUM_CONNECT_TIME
&& state
.nBlocksInFlight
== 0) {
3073 LogPrint(BCLog::NET
, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode
->GetId(), oldest_block_announcement
);
3074 pnode
->fDisconnect
= true;
3077 LogPrint(BCLog::NET
, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode
->GetId(), pnode
->nTimeConnected
, state
.nBlocksInFlight
);
3082 // If we disconnected an extra peer, that means we successfully
3083 // connected to at least one peer after the last time we
3084 // detected a stale tip. Don't try any more extra peers until
3085 // we next detect a stale tip, to limit the load we put on the
3086 // network from these extra connections.
3087 connman
->SetTryNewOutboundPeer(false);
3093 void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params
&consensusParams
)
3095 if (connman
== nullptr) return;
3097 int64_t time_in_seconds
= GetTime();
3099 EvictExtraOutboundPeers(time_in_seconds
);
3101 if (time_in_seconds
> m_stale_tip_check_time
) {
3103 // Check whether our tip is stale, and if so, allow using an extra
3105 if (TipMayBeStale(consensusParams
)) {
3106 LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds
- g_last_tip_update
);
3107 connman
->SetTryNewOutboundPeer(true);
3108 } else if (connman
->GetTryNewOutboundPeer()) {
3109 connman
->SetTryNewOutboundPeer(false);
3111 m_stale_tip_check_time
= time_in_seconds
+ STALE_CHECK_INTERVAL
;
3115 class CompareInvMempoolOrder
3119 explicit CompareInvMempoolOrder(CTxMemPool
*_mempool
)
3124 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
3126 /* As std::make_heap produces a max-heap, we want the entries with the
3127 * fewest ancestors/highest fee to sort later. */
3128 return mp
->CompareDepthAndScore(*b
, *a
);
3132 bool PeerLogicValidation::SendMessages(CNode
* pto
, std::atomic
<bool>& interruptMsgProc
)
3134 const Consensus::Params
& consensusParams
= Params().GetConsensus();
3136 // Don't send anything until the version handshake is complete
3137 if (!pto
->fSuccessfullyConnected
|| pto
->fDisconnect
)
3140 // If we get here, the outgoing message serialization version is set and can't change.
3141 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
3146 bool pingSend
= false;
3147 if (pto
->fPingQueued
) {
3148 // RPC ping request by user
3151 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
3152 // Ping automatically sent as a latency probe & keepalive.
3157 while (nonce
== 0) {
3158 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
3160 pto
->fPingQueued
= false;
3161 pto
->nPingUsecStart
= GetTimeMicros();
3162 if (pto
->nVersion
> BIP0031_VERSION
) {
3163 pto
->nPingNonceSent
= nonce
;
3164 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
, nonce
));
3166 // Peer is too old to support ping command with nonce, pong will never arrive.
3167 pto
->nPingNonceSent
= 0;
3168 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
));
3172 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3176 if (SendRejectsAndCheckIfBanned(pto
, connman
))
3178 CNodeState
&state
= *State(pto
->GetId());
3180 // Address refresh broadcast
3181 int64_t nNow
= GetTimeMicros();
3182 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
3183 AdvertiseLocal(pto
);
3184 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
3190 if (pto
->nNextAddrSend
< nNow
) {
3191 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
3192 std::vector
<CAddress
> vAddr
;
3193 vAddr
.reserve(pto
->vAddrToSend
.size());
3194 for (const CAddress
& addr
: pto
->vAddrToSend
)
3196 if (!pto
->addrKnown
.contains(addr
.GetKey()))
3198 pto
->addrKnown
.insert(addr
.GetKey());
3199 vAddr
.push_back(addr
);
3200 // receiver rejects addr messages larger than 1000
3201 if (vAddr
.size() >= 1000)
3203 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
3208 pto
->vAddrToSend
.clear();
3210 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
3211 // we only send the big addr message once
3212 if (pto
->vAddrToSend
.capacity() > 40)
3213 pto
->vAddrToSend
.shrink_to_fit();
3217 if (pindexBestHeader
== nullptr)
3218 pindexBestHeader
= chainActive
.Tip();
3219 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.
3220 if (!state
.fSyncStarted
&& !pto
->fClient
&& !fImporting
&& !fReindex
) {
3221 // Only actively request headers from a single peer, unless we're close to today.
3222 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3223 state
.fSyncStarted
= true;
3224 state
.nHeadersSyncTimeout
= GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE
+ HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
* (GetAdjustedTime() - pindexBestHeader
->GetBlockTime())/(consensusParams
.nPowTargetSpacing
);
3226 const CBlockIndex
*pindexStart
= pindexBestHeader
;
3227 /* If possible, start at the block preceding the currently
3228 best known header. This ensures that we always get a
3229 non-empty list of headers back as long as the peer
3230 is up-to-date. With a non-empty response, we can initialise
3231 the peer's known best block. This wouldn't be possible
3232 if we requested starting at pindexBestHeader and
3233 got back an empty response. */
3234 if (pindexStart
->pprev
)
3235 pindexStart
= pindexStart
->pprev
;
3236 LogPrint(BCLog::NET
, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->GetId(), pto
->nStartingHeight
);
3237 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256()));
3241 // Resend wallet transactions that haven't gotten in a block yet
3242 // Except during reindex, importing and IBD, when old wallet
3243 // transactions become unconfirmed and spams other nodes.
3244 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
3246 GetMainSignals().Broadcast(nTimeBestReceived
, connman
);
3250 // Try sending block announcements via headers
3253 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3254 // list of block hashes we're relaying, and our peer wants
3255 // headers announcements, then find the first header
3256 // not yet known to our peer but would connect, and send.
3257 // If no header would connect, or if we have too many
3258 // blocks, or if the peer doesn't want headers, just
3259 // add all to the inv queue.
3260 LOCK(pto
->cs_inventory
);
3261 std::vector
<CBlock
> vHeaders
;
3262 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
3263 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
3264 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
3265 const CBlockIndex
*pBestIndex
= nullptr; // last header queued for delivery
3266 ProcessBlockAvailability(pto
->GetId()); // ensure pindexBestKnownBlock is up-to-date
3268 if (!fRevertToInv
) {
3269 bool fFoundStartingHeader
= false;
3270 // Try to find first header that our peer doesn't have, and
3271 // then send all headers past that one. If we come across any
3272 // headers that aren't on chainActive, give up.
3273 for (const uint256
&hash
: pto
->vBlockHashesToAnnounce
) {
3274 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
3275 assert(mi
!= mapBlockIndex
.end());
3276 const CBlockIndex
*pindex
= mi
->second
;
3277 if (chainActive
[pindex
->nHeight
] != pindex
) {
3278 // Bail out if we reorged away from this block
3279 fRevertToInv
= true;
3282 if (pBestIndex
!= nullptr && pindex
->pprev
!= pBestIndex
) {
3283 // This means that the list of blocks to announce don't
3284 // connect to each other.
3285 // This shouldn't really be possible to hit during
3286 // regular operation (because reorgs should take us to
3287 // a chain that has some block not on the prior chain,
3288 // which should be caught by the prior check), but one
3289 // way this could happen is by using invalidateblock /
3290 // reconsiderblock repeatedly on the tip, causing it to
3291 // be added multiple times to vBlockHashesToAnnounce.
3292 // Robustly deal with this rare situation by reverting
3294 fRevertToInv
= true;
3297 pBestIndex
= pindex
;
3298 if (fFoundStartingHeader
) {
3299 // add this to the headers message
3300 vHeaders
.push_back(pindex
->GetBlockHeader());
3301 } else if (PeerHasHeader(&state
, pindex
)) {
3302 continue; // keep looking for the first new block
3303 } else if (pindex
->pprev
== nullptr || PeerHasHeader(&state
, pindex
->pprev
)) {
3304 // Peer doesn't have this header but they do have the prior one.
3305 // Start sending headers.
3306 fFoundStartingHeader
= true;
3307 vHeaders
.push_back(pindex
->GetBlockHeader());
3309 // Peer doesn't have this header or the prior one -- nothing will
3310 // connect, so bail out.
3311 fRevertToInv
= true;
3316 if (!fRevertToInv
&& !vHeaders
.empty()) {
3317 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
3318 // We only send up to 1 block as header-and-ids, as otherwise
3319 // probably means we're doing an initial-ish-sync or they're slow
3320 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", __func__
,
3321 vHeaders
.front().GetHash().ToString(), pto
->GetId());
3323 int nSendFlags
= state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
3325 bool fGotBlockFromCache
= false;
3327 LOCK(cs_most_recent_block
);
3328 if (most_recent_block_hash
== pBestIndex
->GetBlockHash()) {
3329 if (state
.fWantsCmpctWitness
|| !fWitnessesPresentInMostRecentCompactBlock
)
3330 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *most_recent_compact_block
));
3332 CBlockHeaderAndShortTxIDs
cmpctblock(*most_recent_block
, state
.fWantsCmpctWitness
);
3333 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3335 fGotBlockFromCache
= true;
3338 if (!fGotBlockFromCache
) {
3340 bool ret
= ReadBlockFromDisk(block
, pBestIndex
, consensusParams
);
3342 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
3343 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3345 state
.pindexBestHeaderSent
= pBestIndex
;
3346 } else if (state
.fPreferHeaders
) {
3347 if (vHeaders
.size() > 1) {
3348 LogPrint(BCLog::NET
, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
3350 vHeaders
.front().GetHash().ToString(),
3351 vHeaders
.back().GetHash().ToString(), pto
->GetId());
3353 LogPrint(BCLog::NET
, "%s: sending header %s to peer=%d\n", __func__
,
3354 vHeaders
.front().GetHash().ToString(), pto
->GetId());
3356 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
3357 state
.pindexBestHeaderSent
= pBestIndex
;
3359 fRevertToInv
= true;
3362 // If falling back to using an inv, just try to inv the tip.
3363 // The last entry in vBlockHashesToAnnounce was our tip at some point
3365 if (!pto
->vBlockHashesToAnnounce
.empty()) {
3366 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
3367 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
3368 assert(mi
!= mapBlockIndex
.end());
3369 const CBlockIndex
*pindex
= mi
->second
;
3371 // Warn if we're announcing a block that is not on the main chain.
3372 // This should be very rare and could be optimized out.
3373 // Just log for now.
3374 if (chainActive
[pindex
->nHeight
] != pindex
) {
3375 LogPrint(BCLog::NET
, "Announcing block %s not on main chain (tip=%s)\n",
3376 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
3379 // If the peer's chain has this block, don't inv it back.
3380 if (!PeerHasHeader(&state
, pindex
)) {
3381 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
3382 LogPrint(BCLog::NET
, "%s: sending inv peer=%d hash=%s\n", __func__
,
3383 pto
->GetId(), hashToAnnounce
.ToString());
3387 pto
->vBlockHashesToAnnounce
.clear();
3391 // Message: inventory
3393 std::vector
<CInv
> vInv
;
3395 LOCK(pto
->cs_inventory
);
3396 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
3399 for (const uint256
& hash
: pto
->vInventoryBlockToSend
) {
3400 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
3401 if (vInv
.size() == MAX_INV_SZ
) {
3402 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3406 pto
->vInventoryBlockToSend
.clear();
3408 // Check whether periodic sends should happen
3409 bool fSendTrickle
= pto
->fWhitelisted
;
3410 if (pto
->nNextInvSend
< nNow
) {
3411 fSendTrickle
= true;
3412 // Use half the delay for outbound peers, as there is less privacy concern for them.
3413 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
3416 // Time to send but the peer has requested we not relay transactions.
3418 LOCK(pto
->cs_filter
);
3419 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
3422 // Respond to BIP35 mempool requests
3423 if (fSendTrickle
&& pto
->fSendMempool
) {
3424 auto vtxinfo
= mempool
.infoAll();
3425 pto
->fSendMempool
= false;
3426 CAmount filterrate
= 0;
3428 LOCK(pto
->cs_feeFilter
);
3429 filterrate
= pto
->minFeeFilter
;
3432 LOCK(pto
->cs_filter
);
3434 for (const auto& txinfo
: vtxinfo
) {
3435 const uint256
& hash
= txinfo
.tx
->GetHash();
3436 CInv
inv(MSG_TX
, hash
);
3437 pto
->setInventoryTxToSend
.erase(hash
);
3439 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
3443 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3445 pto
->filterInventoryKnown
.insert(hash
);
3446 vInv
.push_back(inv
);
3447 if (vInv
.size() == MAX_INV_SZ
) {
3448 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3452 pto
->timeLastMempoolReq
= GetTime();
3455 // Determine transactions to relay
3457 // Produce a vector with all candidates for sending
3458 std::vector
<std::set
<uint256
>::iterator
> vInvTx
;
3459 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
3460 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
3461 vInvTx
.push_back(it
);
3463 CAmount filterrate
= 0;
3465 LOCK(pto
->cs_feeFilter
);
3466 filterrate
= pto
->minFeeFilter
;
3468 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3469 // A heap is used so that not all items need sorting if only a few are being sent.
3470 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
3471 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3472 // No reason to drain out at many times the network's capacity,
3473 // especially since we have many peers and some will draw much shorter delays.
3474 unsigned int nRelayedTransactions
= 0;
3475 LOCK(pto
->cs_filter
);
3476 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
3477 // Fetch the top element from the heap
3478 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3479 std::set
<uint256
>::iterator it
= vInvTx
.back();
3482 // Remove it from the to-be-sent set
3483 pto
->setInventoryTxToSend
.erase(it
);
3484 // Check if not in the filter already
3485 if (pto
->filterInventoryKnown
.contains(hash
)) {
3488 // Not in the mempool anymore? don't bother sending it.
3489 auto txinfo
= mempool
.info(hash
);
3493 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
3496 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3498 vInv
.push_back(CInv(MSG_TX
, hash
));
3499 nRelayedTransactions
++;
3501 // Expire old relay messages
3502 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
3504 mapRelay
.erase(vRelayExpiration
.front().second
);
3505 vRelayExpiration
.pop_front();
3508 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
3510 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
3513 if (vInv
.size() == MAX_INV_SZ
) {
3514 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3517 pto
->filterInventoryKnown
.insert(hash
);
3522 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3524 // Detect whether we're stalling
3525 nNow
= GetTimeMicros();
3526 if (state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
3527 // Stalling only triggers when the block download window cannot move. During normal steady state,
3528 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3529 // should only happen during initial block download.
3530 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->GetId());
3531 pto
->fDisconnect
= true;
3534 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3535 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3536 // We compensate for other peers to prevent killing off peers due to our own downstream link
3537 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3538 // to unreasonably increase our timeout.
3539 if (state
.vBlocksInFlight
.size() > 0) {
3540 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
3541 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
3542 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
3543 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->GetId());
3544 pto
->fDisconnect
= true;
3548 // Check for headers sync timeouts
3549 if (state
.fSyncStarted
&& state
.nHeadersSyncTimeout
< std::numeric_limits
<int64_t>::max()) {
3550 // Detect whether this is a stalling initial-headers-sync peer
3551 if (pindexBestHeader
->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3552 if (nNow
> state
.nHeadersSyncTimeout
&& nSyncStarted
== 1 && (nPreferredDownload
- state
.fPreferredDownload
>= 1)) {
3553 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3554 // and we have others we could be using instead.
3555 // Note: If all our peers are inbound, then we won't
3556 // disconnect our sync peer for stalling; we have bigger
3557 // problems if we can't get any outbound peers.
3558 if (!pto
->fWhitelisted
) {
3559 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto
->GetId());
3560 pto
->fDisconnect
= true;
3563 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto
->GetId());
3564 // Reset the headers sync state so that we have a
3565 // chance to try downloading from a different peer.
3566 // Note: this will also result in at least one more
3567 // getheaders message to be sent to
3568 // this peer (eventually).
3569 state
.fSyncStarted
= false;
3571 state
.nHeadersSyncTimeout
= 0;
3575 // After we've caught up once, reset the timeout so we can't trigger
3576 // disconnect later.
3577 state
.nHeadersSyncTimeout
= std::numeric_limits
<int64_t>::max();
3581 // Check that outbound peers have reasonable chains
3582 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3583 ConsiderEviction(pto
, GetTime());
3586 // Message: getdata (blocks)
3588 std::vector
<CInv
> vGetData
;
3589 if (!pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
3590 std::vector
<const CBlockIndex
*> vToDownload
;
3591 NodeId staller
= -1;
3592 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
3593 for (const CBlockIndex
*pindex
: vToDownload
) {
3594 uint32_t nFetchFlags
= GetFetchFlags(pto
);
3595 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
3596 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), pindex
);
3597 LogPrint(BCLog::NET
, "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
3598 pindex
->nHeight
, pto
->GetId());
3600 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
3601 if (State(staller
)->nStallingSince
== 0) {
3602 State(staller
)->nStallingSince
= nNow
;
3603 LogPrint(BCLog::NET
, "Stall started peer=%d\n", staller
);
3609 // Message: getdata (non-blocks)
3611 while (!pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
3613 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
3614 if (!AlreadyHave(inv
))
3616 LogPrint(BCLog::NET
, "Requesting %s peer=%d\n", inv
.ToString(), pto
->GetId());
3617 vGetData
.push_back(inv
);
3618 if (vGetData
.size() >= 1000)
3620 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3624 //If we're not going to ask, don't expect a response.
3625 pto
->setAskFor
.erase(inv
.hash
);
3627 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
3629 if (!vGetData
.empty())
3630 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3633 // Message: feefilter
3635 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3636 if (pto
->nVersion
>= FEEFILTER_VERSION
&& gArgs
.GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
3637 !(pto
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
3638 CAmount currentFilter
= mempool
.GetMinFee(gArgs
.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
3639 int64_t timeNow
= GetTimeMicros();
3640 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
3641 static CFeeRate
default_feerate(DEFAULT_MIN_RELAY_TX_FEE
);
3642 static FeeFilterRounder
filterRounder(default_feerate
);
3643 CAmount filterToSend
= filterRounder
.round(currentFilter
);
3644 // We always have a fee filter of at least minRelayTxFee
3645 filterToSend
= std::max(filterToSend
, ::minRelayTxFee
.GetFeePerK());
3646 if (filterToSend
!= pto
->lastSentFeeFilter
) {
3647 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::FEEFILTER
, filterToSend
));
3648 pto
->lastSentFeeFilter
= filterToSend
;
3650 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
3652 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3653 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3654 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
3655 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
3656 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
3663 class CNetProcessingCleanup
3666 CNetProcessingCleanup() {}
3667 ~CNetProcessingCleanup() {
3668 // orphan transactions
3669 mapOrphanTransactions
.clear();
3670 mapOrphanTransactionsByPrev
.clear();
3672 } instance_of_cnetprocessingcleanup
;