1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "net_processing.h"
9 #include "arith_uint256.h"
10 #include "blockencodings.h"
11 #include "chainparams.h"
12 #include "consensus/validation.h"
15 #include "validation.h"
16 #include "merkleblock.h"
18 #include "netmessagemaker.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
25 #include "reverse_iterator.h"
26 #include "scheduler.h"
27 #include "tinyformat.h"
28 #include "txmempool.h"
29 #include "ui_interface.h"
31 #include "utilmoneystr.h"
32 #include "utilstrencodings.h"
33 #include "validationinterface.h"
36 # error "Bitcoin cannot be compiled without assertions."
39 std::atomic
<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
41 struct IteratorComparator
44 bool operator()(const I
& a
, const I
& b
)
51 // When modifying, adapt the copy of this definition in tests/DoS_tests.
56 std::map
<uint256
, COrphanTx
> mapOrphanTransactions
GUARDED_BY(cs_main
);
57 std::map
<COutPoint
, std::set
<std::map
<uint256
, COrphanTx
>::iterator
, IteratorComparator
>> mapOrphanTransactionsByPrev
GUARDED_BY(cs_main
);
58 void EraseOrphansFor(NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
);
60 static size_t vExtraTxnForCompactIt
= 0;
61 static std::vector
<std::pair
<uint256
, CTransactionRef
>> vExtraTxnForCompact
GUARDED_BY(cs_main
);
63 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY
= 0x3cac0035b5866b90ULL
; // SHA256("main address relay")[0:8]
65 /// Age after which a stale block will no longer be served if requested as
66 /// protection against fingerprinting. Set to one month, denominated in seconds.
67 static const int STALE_RELAY_AGE_LIMIT
= 30 * 24 * 60 * 60;
69 /// Age after which a block is considered historical for purposes of rate
70 /// limiting block relay. Set to one week, denominated in seconds.
71 static const int HISTORICAL_BLOCK_AGE
= 7 * 24 * 60 * 60;
75 /** Number of nodes with fSyncStarted. */
79 * Sources of received blocks, saved to be able to send them reject
80 * messages or ban them when processing happens afterwards. Protected by
82 * Set mapBlockSource[hash].second to false if the node should not be
83 * punished if the block is invalid.
85 std::map
<uint256
, std::pair
<NodeId
, bool>> mapBlockSource
;
88 * Filter for transactions that were recently rejected by
89 * AcceptToMemoryPool. These are not rerequested until the chain tip
90 * changes, at which point the entire filter is reset. Protected by
93 * Without this filter we'd be re-requesting txs from each of our peers,
94 * increasing bandwidth consumption considerably. For instance, with 100
95 * peers, half of which relay a tx we don't accept, that might be a 50x
96 * bandwidth increase. A flooding attacker attempting to roll-over the
97 * filter using minimum-sized, 60byte, transactions might manage to send
98 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
99 * two minute window to send invs to us.
101 * Decreasing the false positive rate is fairly cheap, so we pick one in a
102 * million to make it highly unlikely for users to have issues with this
105 * Memory used: 1.3 MB
107 std::unique_ptr
<CRollingBloomFilter
> recentRejects
;
108 uint256 hashRecentRejectsChainTip
;
110 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
113 const CBlockIndex
* pindex
; //!< Optional.
114 bool fValidatedHeaders
; //!< Whether this block has validated headers at the time of request.
115 std::unique_ptr
<PartiallyDownloadedBlock
> partialBlock
; //!< Optional, used for CMPCTBLOCK downloads
117 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> > mapBlocksInFlight
;
119 /** Stack of nodes which we have set to announce using compact blocks */
120 std::list
<NodeId
> lNodesAnnouncingHeaderAndIDs
;
122 /** Number of preferable block download peers. */
123 int nPreferredDownload
= 0;
125 /** Number of peers from which we're downloading blocks. */
126 int nPeersWithValidatedDownloads
= 0;
128 /** Number of outbound peers with m_chain_sync.m_protect. */
129 int g_outbound_peers_with_protect_from_disconnect
= 0;
131 /** When our tip was last updated. */
132 int64_t g_last_tip_update
= 0;
134 /** Relay map, protected by cs_main. */
135 typedef std::map
<uint256
, CTransactionRef
> MapRelay
;
137 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
138 std::deque
<std::pair
<int64_t, MapRelay::iterator
>> vRelayExpiration
;
143 struct CBlockReject
{
144 unsigned char chRejectCode
;
145 std::string strRejectReason
;
150 * Maintain validation-specific state about nodes, protected by cs_main, instead
151 * by CNode's own locks. This simplifies asynchronous operation, where
152 * processing of incoming data is done after the ProcessMessage call returns,
153 * and we're no longer holding the node's locks.
156 //! The peer's address
157 const CService address
;
158 //! Whether we have a fully established connection.
159 bool fCurrentlyConnected
;
160 //! Accumulated misbehaviour score for this peer.
162 //! Whether this peer should be disconnected and banned (unless whitelisted).
164 //! String name of this peer (debugging/logging purposes).
165 const std::string name
;
166 //! List of asynchronously-determined block rejections to notify this peer about.
167 std::vector
<CBlockReject
> rejects
;
168 //! The best known block we know this peer has announced.
169 const CBlockIndex
*pindexBestKnownBlock
;
170 //! The hash of the last unknown block this peer has announced.
171 uint256 hashLastUnknownBlock
;
172 //! The last full block we both have.
173 const CBlockIndex
*pindexLastCommonBlock
;
174 //! The best header we have sent our peer.
175 const CBlockIndex
*pindexBestHeaderSent
;
176 //! Length of current-streak of unconnecting headers announcements
177 int nUnconnectingHeaders
;
178 //! Whether we've started headers synchronization with this peer.
180 //! When to potentially disconnect peer for stalling headers download
181 int64_t nHeadersSyncTimeout
;
182 //! Since when we're stalling block download progress (in microseconds), or 0.
183 int64_t nStallingSince
;
184 std::list
<QueuedBlock
> vBlocksInFlight
;
185 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
186 int64_t nDownloadingSince
;
188 int nBlocksInFlightValidHeaders
;
189 //! Whether we consider this a preferred download peer.
190 bool fPreferredDownload
;
191 //! Whether this peer wants invs or headers (when possible) for block announcements.
193 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
194 bool fPreferHeaderAndIDs
;
196 * Whether this peer will send us cmpctblocks if we request them.
197 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
198 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
200 bool fProvidesHeaderAndIDs
;
201 //! Whether this peer can give us witnesses
203 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
204 bool fWantsCmpctWitness
;
206 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
207 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
209 bool fSupportsDesiredCmpctVersion
;
211 /** State used to enforce CHAIN_SYNC_TIMEOUT
212 * Only in effect for outbound, non-manual connections, with
214 * Algorithm: if a peer's best known block has less work than our tip,
215 * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
216 * - If at timeout their best known block now has more work than our tip
217 * when the timeout was set, then either reset the timeout or clear it
218 * (after comparing against our current tip's work)
219 * - If at timeout their best known block still has less work than our
220 * tip did when the timeout was set, then send a getheaders message,
221 * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future.
222 * If their best known block is still behind when that new timeout is
223 * reached, disconnect.
225 struct ChainSyncTimeoutState
{
226 //! A timeout used for checking whether our peer has sufficiently synced
228 //! A header with the work we require on our peer's chain
229 const CBlockIndex
* m_work_header
;
230 //! After timeout is reached, set to true after sending getheaders
231 bool m_sent_getheaders
;
232 //! Whether this peer is protected from disconnection due to a bad/slow chain
236 ChainSyncTimeoutState m_chain_sync
;
238 //! Time of last new block announcement
239 int64_t m_last_block_announcement
;
241 CNodeState(CAddress addrIn
, std::string addrNameIn
) : address(addrIn
), name(addrNameIn
) {
242 fCurrentlyConnected
= false;
245 pindexBestKnownBlock
= nullptr;
246 hashLastUnknownBlock
.SetNull();
247 pindexLastCommonBlock
= nullptr;
248 pindexBestHeaderSent
= nullptr;
249 nUnconnectingHeaders
= 0;
250 fSyncStarted
= false;
251 nHeadersSyncTimeout
= 0;
253 nDownloadingSince
= 0;
255 nBlocksInFlightValidHeaders
= 0;
256 fPreferredDownload
= false;
257 fPreferHeaders
= false;
258 fPreferHeaderAndIDs
= false;
259 fProvidesHeaderAndIDs
= false;
260 fHaveWitness
= false;
261 fWantsCmpctWitness
= false;
262 fSupportsDesiredCmpctVersion
= false;
263 m_chain_sync
= { 0, nullptr, false, false };
264 m_last_block_announcement
= 0;
268 /** Map maintaining per-node state. Requires cs_main. */
269 std::map
<NodeId
, CNodeState
> mapNodeState
;
272 CNodeState
*State(NodeId pnode
) {
273 std::map
<NodeId
, CNodeState
>::iterator it
= mapNodeState
.find(pnode
);
274 if (it
== mapNodeState
.end())
279 void UpdatePreferredDownload(CNode
* node
, CNodeState
* state
)
281 nPreferredDownload
-= state
->fPreferredDownload
;
283 // Whether this node should be marked as a preferred download node.
284 state
->fPreferredDownload
= (!node
->fInbound
|| node
->fWhitelisted
) && !node
->fOneShot
&& !node
->fClient
;
286 nPreferredDownload
+= state
->fPreferredDownload
;
289 void PushNodeVersion(CNode
*pnode
, CConnman
* connman
, int64_t nTime
)
291 ServiceFlags nLocalNodeServices
= pnode
->GetLocalServices();
292 uint64_t nonce
= pnode
->GetLocalNonce();
293 int nNodeStartingHeight
= pnode
->GetMyStartingHeight();
294 NodeId nodeid
= pnode
->GetId();
295 CAddress addr
= pnode
->addr
;
297 CAddress addrYou
= (addr
.IsRoutable() && !IsProxy(addr
) ? addr
: CAddress(CService(), addr
.nServices
));
298 CAddress addrMe
= CAddress(CService(), nLocalNodeServices
);
300 connman
->PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERSION
, PROTOCOL_VERSION
, (uint64_t)nLocalNodeServices
, nTime
, addrYou
, addrMe
,
301 nonce
, strSubVersion
, nNodeStartingHeight
, ::fRelayTxes
));
304 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), addrYou
.ToString(), nodeid
);
306 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), nodeid
);
311 // Returns a bool indicating whether we requested this block.
312 // Also used if a block was /not/ received and timed out or started with another peer
313 bool MarkBlockAsReceived(const uint256
& hash
) {
314 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
315 if (itInFlight
!= mapBlocksInFlight
.end()) {
316 CNodeState
*state
= State(itInFlight
->second
.first
);
317 assert(state
!= nullptr);
318 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
319 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
320 // Last validated block on the queue was received.
321 nPeersWithValidatedDownloads
--;
323 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
324 // First block on the queue was received, update the start download time for the next one
325 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
327 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
328 state
->nBlocksInFlight
--;
329 state
->nStallingSince
= 0;
330 mapBlocksInFlight
.erase(itInFlight
);
337 // returns false, still setting pit, if the block was already in flight from the same peer
338 // pit will only be valid as long as the same cs_main lock is being held
339 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const CBlockIndex
* pindex
= nullptr, std::list
<QueuedBlock
>::iterator
** pit
= nullptr) {
340 CNodeState
*state
= State(nodeid
);
341 assert(state
!= nullptr);
343 // Short-circuit most stuff in case its from the same node
344 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
345 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
347 *pit
= &itInFlight
->second
.second
;
352 // Make sure it's not listed somewhere already.
353 MarkBlockAsReceived(hash
);
355 std::list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
356 {hash
, pindex
, pindex
!= nullptr, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : nullptr)});
357 state
->nBlocksInFlight
++;
358 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
359 if (state
->nBlocksInFlight
== 1) {
360 // We're starting a block download (batch) from this peer.
361 state
->nDownloadingSince
= GetTimeMicros();
363 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= nullptr) {
364 nPeersWithValidatedDownloads
++;
366 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
368 *pit
= &itInFlight
->second
.second
;
372 /** Check whether the last unknown block a peer advertised is not yet known. */
373 void ProcessBlockAvailability(NodeId nodeid
) {
374 CNodeState
*state
= State(nodeid
);
375 assert(state
!= nullptr);
377 if (!state
->hashLastUnknownBlock
.IsNull()) {
378 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
379 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
380 if (state
->pindexBestKnownBlock
== nullptr || itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
381 state
->pindexBestKnownBlock
= itOld
->second
;
382 state
->hashLastUnknownBlock
.SetNull();
387 /** Update tracking information about which blocks a peer is assumed to have. */
388 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
389 CNodeState
*state
= State(nodeid
);
390 assert(state
!= nullptr);
392 ProcessBlockAvailability(nodeid
);
394 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
395 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
396 // An actually better block was announced.
397 if (state
->pindexBestKnownBlock
== nullptr || it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
398 state
->pindexBestKnownBlock
= it
->second
;
400 // An unknown block was announced; just assume that the latest one is the best one.
401 state
->hashLastUnknownBlock
= hash
;
405 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid
, CConnman
* connman
) {
406 AssertLockHeld(cs_main
);
407 CNodeState
* nodestate
= State(nodeid
);
408 if (!nodestate
|| !nodestate
->fSupportsDesiredCmpctVersion
) {
409 // Never ask from peers who can't provide witnesses.
412 if (nodestate
->fProvidesHeaderAndIDs
) {
413 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
415 lNodesAnnouncingHeaderAndIDs
.erase(it
);
416 lNodesAnnouncingHeaderAndIDs
.push_back(nodeid
);
420 connman
->ForNode(nodeid
, [connman
](CNode
* pfrom
){
421 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
422 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
423 // As per BIP152, we only get 3 of our peers to announce
424 // blocks using compact encodings.
425 connman
->ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [connman
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
426 connman
->PushMessage(pnodeStop
, CNetMsgMaker(pnodeStop
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion
));
429 lNodesAnnouncingHeaderAndIDs
.pop_front();
431 connman
->PushMessage(pfrom
, CNetMsgMaker(pfrom
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion
));
432 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
438 bool TipMayBeStale(const Consensus::Params
&consensusParams
)
440 AssertLockHeld(cs_main
);
441 if (g_last_tip_update
== 0) {
442 g_last_tip_update
= GetTime();
444 return g_last_tip_update
< GetTime() - consensusParams
.nPowTargetSpacing
* 3 && mapBlocksInFlight
.empty();
448 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
450 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
454 bool PeerHasHeader(CNodeState
*state
, const CBlockIndex
*pindex
)
456 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
458 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
463 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
464 * at most count entries. */
465 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<const CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
469 vBlocks
.reserve(vBlocks
.size() + count
);
470 CNodeState
*state
= State(nodeid
);
471 assert(state
!= nullptr);
473 // Make sure pindexBestKnownBlock is up to date, we'll need it.
474 ProcessBlockAvailability(nodeid
);
476 if (state
->pindexBestKnownBlock
== nullptr || state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
|| state
->pindexBestKnownBlock
->nChainWork
< nMinimumChainWork
) {
477 // This peer has nothing interesting.
481 if (state
->pindexLastCommonBlock
== nullptr) {
482 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
483 // Guessing wrong in either direction is not a problem.
484 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
487 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
488 // of its current tip anymore. Go back enough to fix that.
489 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
490 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
493 std::vector
<const CBlockIndex
*> vToFetch
;
494 const CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
495 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
496 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
497 // download that next block if the window were 1 larger.
498 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
499 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
500 NodeId waitingfor
= -1;
501 while (pindexWalk
->nHeight
< nMaxHeight
) {
502 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
503 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
504 // as iterating over ~100 CBlockIndex* entries anyway.
505 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
506 vToFetch
.resize(nToFetch
);
507 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
508 vToFetch
[nToFetch
- 1] = pindexWalk
;
509 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
510 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
513 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
514 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
515 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
516 // already part of our chain (and therefore don't need it even if pruned).
517 for (const CBlockIndex
* pindex
: vToFetch
) {
518 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
519 // We consider the chain that this peer is on invalid.
522 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
523 // We wouldn't download this block or its descendants from this peer.
526 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
527 if (pindex
->nChainTx
)
528 state
->pindexLastCommonBlock
= pindex
;
529 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
530 // The block is not already downloaded, and not yet in flight.
531 if (pindex
->nHeight
> nWindowEnd
) {
532 // We reached the end of the window.
533 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
534 // We aren't able to fetch anything, but we would be if the download window was one larger.
535 nodeStaller
= waitingfor
;
539 vBlocks
.push_back(pindex
);
540 if (vBlocks
.size() == count
) {
543 } else if (waitingfor
== -1) {
544 // This is the first already-in-flight block.
545 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
553 // This function is used for testing the stale tip eviction logic, see
555 void UpdateLastBlockAnnounceTime(NodeId node
, int64_t time_in_seconds
)
558 CNodeState
*state
= State(node
);
559 if (state
) state
->m_last_block_announcement
= time_in_seconds
;
562 // Returns true for outbound peers, excluding manual connections, feelers, and
564 bool IsOutboundDisconnectionCandidate(const CNode
*node
)
566 return !(node
->fInbound
|| node
->m_manual_connection
|| node
->fFeeler
|| node
->fOneShot
);
569 void PeerLogicValidation::InitializeNode(CNode
*pnode
) {
570 CAddress addr
= pnode
->addr
;
571 std::string addrName
= pnode
->GetAddrName();
572 NodeId nodeid
= pnode
->GetId();
575 mapNodeState
.emplace_hint(mapNodeState
.end(), std::piecewise_construct
, std::forward_as_tuple(nodeid
), std::forward_as_tuple(addr
, std::move(addrName
)));
578 PushNodeVersion(pnode
, connman
, GetTime());
581 void PeerLogicValidation::FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
582 fUpdateConnectionTime
= false;
584 CNodeState
*state
= State(nodeid
);
585 assert(state
!= nullptr);
587 if (state
->fSyncStarted
)
590 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
591 fUpdateConnectionTime
= true;
594 for (const QueuedBlock
& entry
: state
->vBlocksInFlight
) {
595 mapBlocksInFlight
.erase(entry
.hash
);
597 EraseOrphansFor(nodeid
);
598 nPreferredDownload
-= state
->fPreferredDownload
;
599 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
600 assert(nPeersWithValidatedDownloads
>= 0);
601 g_outbound_peers_with_protect_from_disconnect
-= state
->m_chain_sync
.m_protect
;
602 assert(g_outbound_peers_with_protect_from_disconnect
>= 0);
604 mapNodeState
.erase(nodeid
);
606 if (mapNodeState
.empty()) {
607 // Do a consistency check after the last peer is removed.
608 assert(mapBlocksInFlight
.empty());
609 assert(nPreferredDownload
== 0);
610 assert(nPeersWithValidatedDownloads
== 0);
611 assert(g_outbound_peers_with_protect_from_disconnect
== 0);
613 LogPrint(BCLog::NET
, "Cleared nodestate for peer=%d\n", nodeid
);
616 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
618 CNodeState
*state
= State(nodeid
);
619 if (state
== nullptr)
621 stats
.nMisbehavior
= state
->nMisbehavior
;
622 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
623 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
624 for (const QueuedBlock
& queue
: state
->vBlocksInFlight
) {
626 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
631 //////////////////////////////////////////////////////////////////////////////
633 // mapOrphanTransactions
636 void AddToCompactExtraTransactions(const CTransactionRef
& tx
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
638 size_t max_extra_txn
= gArgs
.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
);
639 if (max_extra_txn
<= 0)
641 if (!vExtraTxnForCompact
.size())
642 vExtraTxnForCompact
.resize(max_extra_txn
);
643 vExtraTxnForCompact
[vExtraTxnForCompactIt
] = std::make_pair(tx
->GetWitnessHash(), tx
);
644 vExtraTxnForCompactIt
= (vExtraTxnForCompactIt
+ 1) % max_extra_txn
;
647 bool AddOrphanTx(const CTransactionRef
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
649 const uint256
& hash
= tx
->GetHash();
650 if (mapOrphanTransactions
.count(hash
))
653 // Ignore big transactions, to avoid a
654 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
655 // large transaction with a missing parent then we assume
656 // it will rebroadcast it later, after the parent transaction(s)
657 // have been mined or received.
658 // 100 orphans, each of which is at most 99,999 bytes big is
659 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
660 unsigned int sz
= GetTransactionWeight(*tx
);
661 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
663 LogPrint(BCLog::MEMPOOL
, "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
667 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
669 for (const CTxIn
& txin
: tx
->vin
) {
670 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
673 AddToCompactExtraTransactions(tx
);
675 LogPrint(BCLog::MEMPOOL
, "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
676 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
680 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
682 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
683 if (it
== mapOrphanTransactions
.end())
685 for (const CTxIn
& txin
: it
->second
.tx
->vin
)
687 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
688 if (itPrev
== mapOrphanTransactionsByPrev
.end())
690 itPrev
->second
.erase(it
);
691 if (itPrev
->second
.empty())
692 mapOrphanTransactionsByPrev
.erase(itPrev
);
694 mapOrphanTransactions
.erase(it
);
698 void EraseOrphansFor(NodeId peer
)
701 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
702 while (iter
!= mapOrphanTransactions
.end())
704 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
705 if (maybeErase
->second
.fromPeer
== peer
)
707 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
710 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx from peer=%d\n", nErased
, peer
);
714 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
716 unsigned int nEvicted
= 0;
717 static int64_t nNextSweep
;
718 int64_t nNow
= GetTime();
719 if (nNextSweep
<= nNow
) {
720 // Sweep out expired orphan pool entries:
722 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
723 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
724 while (iter
!= mapOrphanTransactions
.end())
726 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
727 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
728 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
730 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
733 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
734 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
735 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx due to expiration\n", nErased
);
737 while (mapOrphanTransactions
.size() > nMaxOrphans
)
739 // Evict a random orphan:
740 uint256 randomhash
= GetRandHash();
741 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
742 if (it
== mapOrphanTransactions
.end())
743 it
= mapOrphanTransactions
.begin();
744 EraseOrphanTx(it
->first
);
751 void Misbehaving(NodeId pnode
, int howmuch
)
756 CNodeState
*state
= State(pnode
);
757 if (state
== nullptr)
760 state
->nMisbehavior
+= howmuch
;
761 int banscore
= gArgs
.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
762 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
764 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
765 state
->fShouldBan
= true;
767 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
777 //////////////////////////////////////////////////////////////////////////////
779 // blockchain -> download logic notification
782 // To prevent fingerprinting attacks, only send blocks/headers outside of the
783 // active chain if they are no more than a month older (both in time, and in
784 // best equivalent proof of work) than the best header chain we know about.
785 static bool StaleBlockRequestAllowed(const CBlockIndex
* pindex
, const Consensus::Params
& consensusParams
)
787 AssertLockHeld(cs_main
);
788 return (pindexBestHeader
!= nullptr) &&
789 (pindexBestHeader
->GetBlockTime() - pindex
->GetBlockTime() < STALE_RELAY_AGE_LIMIT
) &&
790 (GetBlockProofEquivalentTime(*pindexBestHeader
, *pindex
, *pindexBestHeader
, consensusParams
) < STALE_RELAY_AGE_LIMIT
);
793 PeerLogicValidation::PeerLogicValidation(CConnman
* connmanIn
, CScheduler
&scheduler
) : connman(connmanIn
), m_stale_tip_check_time(0) {
794 // Initialize global variables that cannot be constructed at startup.
795 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
797 const Consensus::Params
& consensusParams
= Params().GetConsensus();
798 // Stale tip checking and peer eviction are on two different timers, but we
799 // don't want them to get out of sync due to drift in the scheduler, so we
800 // combine them in one function and schedule at the quicker (peer-eviction)
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 if (chainActive
.Contains(mi
->second
)) {
1080 send
= mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) &&
1081 StaleBlockRequestAllowed(mi
->second
, consensusParams
);
1083 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
1087 // disconnect node in case we have reached the outbound limit for serving historical blocks
1088 // never disconnect whitelisted nodes
1089 if (send
&& connman
->OutboundTargetReached(true) && ( ((pindexBestHeader
!= nullptr) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > HISTORICAL_BLOCK_AGE
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
1091 LogPrint(BCLog::NET
, "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
1094 pfrom
->fDisconnect
= true;
1097 // Pruned nodes may have deleted the block, so check whether
1098 // it's available before trying to send.
1099 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
1101 std::shared_ptr
<const CBlock
> pblock
;
1102 if (a_recent_block
&& a_recent_block
->GetHash() == (*mi
).second
->GetBlockHash()) {
1103 pblock
= a_recent_block
;
1105 // Send block from disk
1106 std::shared_ptr
<CBlock
> pblockRead
= std::make_shared
<CBlock
>();
1107 if (!ReadBlockFromDisk(*pblockRead
, (*mi
).second
, consensusParams
))
1108 assert(!"cannot load block from disk");
1109 pblock
= pblockRead
;
1111 if (inv
.type
== MSG_BLOCK
)
1112 connman
->PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, *pblock
));
1113 else if (inv
.type
== MSG_WITNESS_BLOCK
)
1114 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::BLOCK
, *pblock
));
1115 else if (inv
.type
== MSG_FILTERED_BLOCK
)
1117 bool sendMerkleBlock
= false;
1118 CMerkleBlock merkleBlock
;
1120 LOCK(pfrom
->cs_filter
);
1121 if (pfrom
->pfilter
) {
1122 sendMerkleBlock
= true;
1123 merkleBlock
= CMerkleBlock(*pblock
, *pfrom
->pfilter
);
1126 if (sendMerkleBlock
) {
1127 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::MERKLEBLOCK
, merkleBlock
));
1128 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1129 // This avoids hurting performance by pointlessly requiring a round-trip
1130 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1131 // they must either disconnect and retry or request the full block.
1132 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1133 // however we MUST always provide at least what the remote peer needs
1134 typedef std::pair
<unsigned int, uint256
> PairType
;
1135 for (PairType
& pair
: merkleBlock
.vMatchedTxn
)
1136 connman
->PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, *pblock
->vtx
[pair
.first
]));
1141 else if (inv
.type
== MSG_CMPCT_BLOCK
)
1143 // If a peer is asking for old blocks, we're almost guaranteed
1144 // they won't have a useful mempool to match against a compact block,
1145 // and we don't feel like constructing the object for them, so
1146 // instead we respond with the full, non-compact block.
1147 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
1148 int nSendFlags
= fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1149 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
1150 if ((fPeerWantsWitness
|| !fWitnessesPresentInARecentCompactBlock
) && a_recent_compact_block
&& a_recent_compact_block
->header
.GetHash() == mi
->second
->GetBlockHash()) {
1151 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *a_recent_compact_block
));
1153 CBlockHeaderAndShortTxIDs
cmpctblock(*pblock
, fPeerWantsWitness
);
1154 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
1157 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCK
, *pblock
));
1161 // Trigger the peer node to send a getblocks request for the next batch of inventory
1162 if (inv
.hash
== pfrom
->hashContinue
)
1164 // Bypass PushInventory, this must send even if redundant,
1165 // and we want it right after the last block so they don't
1166 // wait for other stuff first.
1167 std::vector
<CInv
> vInv
;
1168 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
1169 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::INV
, vInv
));
1170 pfrom
->hashContinue
.SetNull();
1174 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
1176 // Send stream from relay memory
1178 auto mi
= mapRelay
.find(inv
.hash
);
1179 int nSendFlags
= (inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0);
1180 if (mi
!= mapRelay
.end()) {
1181 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *mi
->second
));
1183 } else if (pfrom
->timeLastMempoolReq
) {
1184 auto txinfo
= mempool
.info(inv
.hash
);
1185 // To protect privacy, do not answer getdata using the mempool when
1186 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1187 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
1188 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *txinfo
.tx
));
1193 vNotFound
.push_back(inv
);
1197 // Track requests for our stuff.
1198 GetMainSignals().Inventory(inv
.hash
);
1200 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1205 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
1207 if (!vNotFound
.empty()) {
1208 // Let the peer know that we didn't find what it asked for, so it doesn't
1209 // have to wait around forever. Currently only SPV clients actually care
1210 // about this message: it's needed when they are recursively walking the
1211 // dependencies of relevant unconfirmed transactions. SPV clients want to
1212 // do that because they want to know about (and store and rebroadcast and
1213 // risk analyze) the dependencies of transactions relevant to them, without
1214 // having to download the entire memory pool.
1215 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::NOTFOUND
, vNotFound
));
1219 uint32_t GetFetchFlags(CNode
* pfrom
) {
1220 uint32_t nFetchFlags
= 0;
1221 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
1222 nFetchFlags
|= MSG_WITNESS_FLAG
;
1227 inline void static SendBlockTransactions(const CBlock
& block
, const BlockTransactionsRequest
& req
, CNode
* pfrom
, CConnman
* connman
) {
1228 BlockTransactions
resp(req
);
1229 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
1230 if (req
.indexes
[i
] >= block
.vtx
.size()) {
1232 Misbehaving(pfrom
->GetId(), 100);
1233 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->GetId());
1236 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
1239 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1240 int nSendFlags
= State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1241 connman
->PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCKTXN
, resp
));
1244 bool static ProcessHeadersMessage(CNode
*pfrom
, CConnman
*connman
, const std::vector
<CBlockHeader
>& headers
, const CChainParams
& chainparams
, bool punish_duplicate_invalid
)
1246 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1247 size_t nCount
= headers
.size();
1250 // Nothing interesting. Stop asking this peers for more headers.
1254 bool received_new_header
= false;
1255 const CBlockIndex
*pindexLast
= nullptr;
1258 CNodeState
*nodestate
= State(pfrom
->GetId());
1260 // If this looks like it could be a block announcement (nCount <
1261 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
1263 // - Send a getheaders message in response to try to connect the chain.
1264 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
1265 // don't connect before giving DoS points
1266 // - Once a headers message is received that is valid and does connect,
1267 // nUnconnectingHeaders gets reset back to 0.
1268 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
1269 nodestate
->nUnconnectingHeaders
++;
1270 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
1271 LogPrint(BCLog::NET
, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
1272 headers
[0].GetHash().ToString(),
1273 headers
[0].hashPrevBlock
.ToString(),
1274 pindexBestHeader
->nHeight
,
1275 pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
1276 // Set hashLastUnknownBlock for this peer, so that if we
1277 // eventually get the headers - even from a different peer -
1278 // we can use this peer to download.
1279 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
1281 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
1282 Misbehaving(pfrom
->GetId(), 20);
1287 uint256 hashLastBlock
;
1288 for (const CBlockHeader
& header
: headers
) {
1289 if (!hashLastBlock
.IsNull() && header
.hashPrevBlock
!= hashLastBlock
) {
1290 Misbehaving(pfrom
->GetId(), 20);
1291 return error("non-continuous headers sequence");
1293 hashLastBlock
= header
.GetHash();
1296 // If we don't have the last header, then they'll have given us
1297 // something new (if these headers are valid).
1298 if (mapBlockIndex
.find(hashLastBlock
) == mapBlockIndex
.end()) {
1299 received_new_header
= true;
1303 CValidationState state
;
1304 CBlockHeader first_invalid_header
;
1305 if (!ProcessNewBlockHeaders(headers
, state
, chainparams
, &pindexLast
, &first_invalid_header
)) {
1307 if (state
.IsInvalid(nDoS
)) {
1310 Misbehaving(pfrom
->GetId(), nDoS
);
1312 if (punish_duplicate_invalid
&& mapBlockIndex
.find(first_invalid_header
.GetHash()) != mapBlockIndex
.end()) {
1313 // Goal: don't allow outbound peers to use up our outbound
1314 // connection slots if they are on incompatible chains.
1316 // We ask the caller to set punish_invalid appropriately based
1317 // on the peer and the method of header delivery (compact
1318 // blocks are allowed to be invalid in some circumstances,
1320 // Here, we try to detect the narrow situation that we have a
1321 // valid block header (ie it was valid at the time the header
1322 // was received, and hence stored in mapBlockIndex) but know the
1323 // block is invalid, and that a peer has announced that same
1324 // block as being on its active chain.
1325 // Disconnect the peer in such a situation.
1327 // Note: if the header that is invalid was not accepted to our
1328 // mapBlockIndex at all, that may also be grounds for
1329 // disconnecting the peer, as the chain they are on is likely
1330 // to be incompatible. However, there is a circumstance where
1331 // that does not hold: if the header's timestamp is more than
1332 // 2 hours ahead of our current time. In that case, the header
1333 // may become valid in the future, and we don't want to
1334 // disconnect a peer merely for serving us one too-far-ahead
1335 // block header, to prevent an attacker from splitting the
1336 // network by mining a block right at the 2 hour boundary.
1338 // TODO: update the DoS logic (or, rather, rewrite the
1339 // DoS-interface between validation and net_processing) so that
1340 // the interface is cleaner, and so that we disconnect on all the
1341 // reasons that a peer's headers chain is incompatible
1342 // with ours (eg block->nVersion softforks, MTP violations,
1343 // etc), and not just the duplicate-invalid case.
1344 pfrom
->fDisconnect
= true;
1346 return error("invalid header received");
1352 CNodeState
*nodestate
= State(pfrom
->GetId());
1353 if (nodestate
->nUnconnectingHeaders
> 0) {
1354 LogPrint(BCLog::NET
, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->GetId(), nodestate
->nUnconnectingHeaders
);
1356 nodestate
->nUnconnectingHeaders
= 0;
1359 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
1361 // From here, pindexBestKnownBlock should be guaranteed to be non-null,
1362 // because it is set in UpdateBlockAvailability. Some nullptr checks
1363 // are still present, however, as belt-and-suspenders.
1365 if (received_new_header
&& pindexLast
->nChainWork
> chainActive
.Tip()->nChainWork
) {
1366 nodestate
->m_last_block_announcement
= GetTime();
1369 if (nCount
== MAX_HEADERS_RESULTS
) {
1370 // Headers message had its maximum size; the peer may have more headers.
1371 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
1372 // from there instead.
1373 LogPrint(BCLog::NET
, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->GetId(), pfrom
->nStartingHeight
);
1374 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256()));
1377 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
1378 // If this set of headers is valid and ends in a block with at least as
1379 // much work as our tip, download as much as possible.
1380 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
1381 std::vector
<const CBlockIndex
*> vToFetch
;
1382 const CBlockIndex
*pindexWalk
= pindexLast
;
1383 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
1384 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
1385 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
1386 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
1387 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
1388 // We don't have this block, and it's not yet in flight.
1389 vToFetch
.push_back(pindexWalk
);
1391 pindexWalk
= pindexWalk
->pprev
;
1393 // If pindexWalk still isn't on our main chain, we're looking at a
1394 // very large reorg at a time we think we're close to caught up to
1395 // the main chain -- this shouldn't really happen. Bail out on the
1396 // direct fetch and rely on parallel download instead.
1397 if (!chainActive
.Contains(pindexWalk
)) {
1398 LogPrint(BCLog::NET
, "Large reorg, won't direct fetch to %s (%d)\n",
1399 pindexLast
->GetBlockHash().ToString(),
1400 pindexLast
->nHeight
);
1402 std::vector
<CInv
> vGetData
;
1403 // Download as much as possible, from earliest to latest.
1404 for (const CBlockIndex
*pindex
: reverse_iterate(vToFetch
)) {
1405 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
1406 // Can't download any more from this peer
1409 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1410 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
1411 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
);
1412 LogPrint(BCLog::NET
, "Requesting block %s from peer=%d\n",
1413 pindex
->GetBlockHash().ToString(), pfrom
->GetId());
1415 if (vGetData
.size() > 1) {
1416 LogPrint(BCLog::NET
, "Downloading blocks toward %s (%d) via headers direct fetch\n",
1417 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
1419 if (vGetData
.size() > 0) {
1420 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
1421 // In any case, we want to download using a compact block, not a regular one
1422 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
1424 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
1428 // If we're in IBD, we want outbound peers that will serve us a useful
1429 // chain. Disconnect peers that are on chains with insufficient work.
1430 if (IsInitialBlockDownload() && nCount
!= MAX_HEADERS_RESULTS
) {
1431 // When nCount < MAX_HEADERS_RESULTS, we know we have no more
1432 // headers to fetch from this peer.
1433 if (nodestate
->pindexBestKnownBlock
&& nodestate
->pindexBestKnownBlock
->nChainWork
< nMinimumChainWork
) {
1434 // This peer has too little work on their headers chain to help
1435 // us sync -- disconnect if using an outbound slot (unless
1436 // whitelisted or addnode).
1437 // Note: We compare their tip to nMinimumChainWork (rather than
1438 // chainActive.Tip()) because we won't start block download
1439 // until we have a headers chain that has at least
1440 // nMinimumChainWork, even if a peer has a chain past our tip,
1441 // as an anti-DoS measure.
1442 if (IsOutboundDisconnectionCandidate(pfrom
)) {
1443 LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom
->GetId());
1444 pfrom
->fDisconnect
= true;
1449 if (!pfrom
->fDisconnect
&& IsOutboundDisconnectionCandidate(pfrom
) && nodestate
->pindexBestKnownBlock
!= nullptr) {
1450 // If this is an outbound peer, check to see if we should protect
1451 // it from the bad/lagging chain logic.
1452 if (g_outbound_peers_with_protect_from_disconnect
< MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT
&& nodestate
->pindexBestKnownBlock
->nChainWork
>= chainActive
.Tip()->nChainWork
&& !nodestate
->m_chain_sync
.m_protect
) {
1453 LogPrint(BCLog::NET
, "Protecting outbound peer=%d from eviction\n", pfrom
->GetId());
1454 nodestate
->m_chain_sync
.m_protect
= true;
1455 ++g_outbound_peers_with_protect_from_disconnect
;
1463 bool static ProcessMessage(CNode
* pfrom
, const std::string
& strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
* connman
, const std::atomic
<bool>& interruptMsgProc
)
1465 LogPrint(BCLog::NET
, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->GetId());
1466 if (gArgs
.IsArgSet("-dropmessagestest") && GetRand(gArgs
.GetArg("-dropmessagestest", 0)) == 0)
1468 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1473 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
1474 (strCommand
== NetMsgType::FILTERLOAD
||
1475 strCommand
== NetMsgType::FILTERADD
))
1477 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
1479 Misbehaving(pfrom
->GetId(), 100);
1482 pfrom
->fDisconnect
= true;
1487 if (strCommand
== NetMsgType::REJECT
)
1489 if (LogAcceptCategory(BCLog::NET
)) {
1491 std::string strMsg
; unsigned char ccode
; std::string strReason
;
1492 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
1494 std::ostringstream ss
;
1495 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
1497 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
1501 ss
<< ": hash " << hash
.ToString();
1503 LogPrint(BCLog::NET
, "Reject %s\n", SanitizeString(ss
.str()));
1504 } catch (const std::ios_base::failure
&) {
1505 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1506 LogPrint(BCLog::NET
, "Unparseable reject message received\n");
1511 else if (strCommand
== NetMsgType::VERSION
)
1513 // Each connection can only send one version message
1514 if (pfrom
->nVersion
!= 0)
1516 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, std::string("Duplicate version message")));
1518 Misbehaving(pfrom
->GetId(), 1);
1525 uint64_t nNonce
= 1;
1526 uint64_t nServiceInt
;
1527 ServiceFlags nServices
;
1530 std::string strSubVer
;
1531 std::string cleanSubVer
;
1532 int nStartingHeight
= -1;
1535 vRecv
>> nVersion
>> nServiceInt
>> nTime
>> addrMe
;
1536 nSendVersion
= std::min(nVersion
, PROTOCOL_VERSION
);
1537 nServices
= ServiceFlags(nServiceInt
);
1538 if (!pfrom
->fInbound
)
1540 connman
->SetServices(pfrom
->addr
, nServices
);
1542 if (!pfrom
->fInbound
&& !pfrom
->fFeeler
&& !pfrom
->m_manual_connection
&& !HasAllDesirableServiceFlags(nServices
))
1544 LogPrint(BCLog::NET
, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->GetId(), nServices
, GetDesirableServiceFlags(nServices
));
1545 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
1546 strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices
))));
1547 pfrom
->fDisconnect
= true;
1551 if (nServices
& ((1 << 7) | (1 << 5))) {
1552 if (GetTime() < 1533096000) {
1553 // Immediately disconnect peers that use service bits 6 or 8 until August 1st, 2018
1554 // These bits have been used as a flag to indicate that a node is running incompatible
1555 // consensus rules instead of changing the network magic, so we're stuck disconnecting
1556 // based on these service bits, at least for a while.
1557 pfrom
->fDisconnect
= true;
1562 if (nVersion
< MIN_PEER_PROTO_VERSION
)
1564 // disconnect from peers older than this proto version
1565 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom
->GetId(), nVersion
);
1566 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
1567 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
)));
1568 pfrom
->fDisconnect
= true;
1572 if (nVersion
== 10300)
1575 vRecv
>> addrFrom
>> nNonce
;
1576 if (!vRecv
.empty()) {
1577 vRecv
>> LIMITED_STRING(strSubVer
, MAX_SUBVERSION_LENGTH
);
1578 cleanSubVer
= SanitizeString(strSubVer
);
1580 if (!vRecv
.empty()) {
1581 vRecv
>> nStartingHeight
;
1585 // Disconnect if we connected to ourself
1586 if (pfrom
->fInbound
&& !connman
->CheckIncomingNonce(nNonce
))
1588 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
1589 pfrom
->fDisconnect
= true;
1593 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
1598 // Be shy and don't send version until we hear
1599 if (pfrom
->fInbound
)
1600 PushNodeVersion(pfrom
, connman
, GetAdjustedTime());
1602 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERACK
));
1604 pfrom
->nServices
= nServices
;
1605 pfrom
->SetAddrLocal(addrMe
);
1607 LOCK(pfrom
->cs_SubVer
);
1608 pfrom
->strSubVer
= strSubVer
;
1609 pfrom
->cleanSubVer
= cleanSubVer
;
1611 pfrom
->nStartingHeight
= nStartingHeight
;
1612 pfrom
->fClient
= !(nServices
& NODE_NETWORK
);
1614 LOCK(pfrom
->cs_filter
);
1615 pfrom
->fRelayTxes
= fRelay
; // set to true after we get the first filter* message
1619 pfrom
->SetSendVersion(nSendVersion
);
1620 pfrom
->nVersion
= nVersion
;
1622 if((nServices
& NODE_WITNESS
))
1625 State(pfrom
->GetId())->fHaveWitness
= true;
1628 // Potentially mark this peer as a preferred download peer.
1631 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
1634 if (!pfrom
->fInbound
)
1636 // Advertise our address
1637 if (fListen
&& !IsInitialBlockDownload())
1639 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
1640 FastRandomContext insecure_rand
;
1641 if (addr
.IsRoutable())
1643 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1644 pfrom
->PushAddress(addr
, insecure_rand
);
1645 } else if (IsPeerAddrLocalGood(pfrom
)) {
1647 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1648 pfrom
->PushAddress(addr
, insecure_rand
);
1652 // Get recent addresses
1653 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
->GetAddressCount() < 1000)
1655 connman
->PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make(NetMsgType::GETADDR
));
1656 pfrom
->fGetAddr
= true;
1658 connman
->MarkAddressGood(pfrom
->addr
);
1661 std::string remoteAddr
;
1663 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
1665 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1666 cleanSubVer
, pfrom
->nVersion
,
1667 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->GetId(),
1670 int64_t nTimeOffset
= nTime
- GetTime();
1671 pfrom
->nTimeOffset
= nTimeOffset
;
1672 AddTimeData(pfrom
->addr
, nTimeOffset
);
1674 // If the peer is old enough to have the old alert system, send it the final alert.
1675 if (pfrom
->nVersion
<= 70012) {
1676 CDataStream
finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK
, PROTOCOL_VERSION
);
1677 connman
->PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make("alert", finalAlert
));
1680 // Feeler connections exist only to verify if address is online.
1681 if (pfrom
->fFeeler
) {
1682 assert(pfrom
->fInbound
== false);
1683 pfrom
->fDisconnect
= true;
1689 else if (pfrom
->nVersion
== 0)
1691 // Must have a version message before anything else
1693 Misbehaving(pfrom
->GetId(), 1);
1697 // At this point, the outgoing message serialization version can't change.
1698 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1700 if (strCommand
== NetMsgType::VERACK
)
1702 pfrom
->SetRecvVersion(std::min(pfrom
->nVersion
.load(), PROTOCOL_VERSION
));
1704 if (!pfrom
->fInbound
) {
1705 // Mark this node as currently connected, so we update its timestamp later.
1707 State(pfrom
->GetId())->fCurrentlyConnected
= true;
1710 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
1711 // Tell our peer we prefer to receive headers rather than inv's
1712 // We send this to non-NODE NETWORK peers as well, because even
1713 // non-NODE NETWORK peers can announce blocks (such as pruning
1715 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDHEADERS
));
1717 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
1718 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1719 // However, we do not request new block announcements using
1720 // cmpctblock messages.
1721 // We send this to non-NODE NETWORK peers as well, because
1722 // they may wish to request compact blocks from us
1723 bool fAnnounceUsingCMPCTBLOCK
= false;
1724 uint64_t nCMPCTBLOCKVersion
= 2;
1725 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1726 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1727 nCMPCTBLOCKVersion
= 1;
1728 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1730 pfrom
->fSuccessfullyConnected
= true;
1733 else if (!pfrom
->fSuccessfullyConnected
)
1735 // Must have a verack message before anything else
1737 Misbehaving(pfrom
->GetId(), 1);
1741 else if (strCommand
== NetMsgType::ADDR
)
1743 std::vector
<CAddress
> vAddr
;
1746 // Don't want addr from older versions unless seeding
1747 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
->GetAddressCount() > 1000)
1749 if (vAddr
.size() > 1000)
1752 Misbehaving(pfrom
->GetId(), 20);
1753 return error("message addr size() = %u", vAddr
.size());
1756 // Store the new addresses
1757 std::vector
<CAddress
> vAddrOk
;
1758 int64_t nNow
= GetAdjustedTime();
1759 int64_t nSince
= nNow
- 10 * 60;
1760 for (CAddress
& addr
: vAddr
)
1762 if (interruptMsgProc
)
1765 // We only bother storing full nodes, though this may include
1766 // things which we would not make an outbound connection to, in
1767 // part because we may make feeler connections to them.
1768 if (!MayHaveUsefulAddressDB(addr
.nServices
))
1771 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
1772 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
1773 pfrom
->AddAddressKnown(addr
);
1774 bool fReachable
= IsReachable(addr
);
1775 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
1777 // Relay to a limited number of other nodes
1778 RelayAddress(addr
, fReachable
, connman
);
1780 // Do not store addresses outside our network
1782 vAddrOk
.push_back(addr
);
1784 connman
->AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
1785 if (vAddr
.size() < 1000)
1786 pfrom
->fGetAddr
= false;
1787 if (pfrom
->fOneShot
)
1788 pfrom
->fDisconnect
= true;
1791 else if (strCommand
== NetMsgType::SENDHEADERS
)
1794 State(pfrom
->GetId())->fPreferHeaders
= true;
1797 else if (strCommand
== NetMsgType::SENDCMPCT
)
1799 bool fAnnounceUsingCMPCTBLOCK
= false;
1800 uint64_t nCMPCTBLOCKVersion
= 0;
1801 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
1802 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
1804 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1805 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
1806 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
1807 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
1809 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
1810 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
1811 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
1812 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1813 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
1815 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
1821 else if (strCommand
== NetMsgType::INV
)
1823 std::vector
<CInv
> vInv
;
1825 if (vInv
.size() > MAX_INV_SZ
)
1828 Misbehaving(pfrom
->GetId(), 20);
1829 return error("message inv size() = %u", vInv
.size());
1832 bool fBlocksOnly
= !fRelayTxes
;
1834 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1835 if (pfrom
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
1836 fBlocksOnly
= false;
1840 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
1842 for (CInv
&inv
: vInv
)
1844 if (interruptMsgProc
)
1847 bool fAlreadyHave
= AlreadyHave(inv
);
1848 LogPrint(BCLog::NET
, "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->GetId());
1850 if (inv
.type
== MSG_TX
) {
1851 inv
.type
|= nFetchFlags
;
1854 if (inv
.type
== MSG_BLOCK
) {
1855 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
1856 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
1857 // We used to request the full block here, but since headers-announcements are now the
1858 // primary method of announcement on the network, and since, in the case that a node
1859 // fell back to inv we probably have a reorg which we should get the headers for first,
1860 // we now only provide a getheaders response here. When we receive the headers, we will
1861 // then ask for the blocks we need.
1862 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
));
1863 LogPrint(BCLog::NET
, "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->GetId());
1868 pfrom
->AddInventoryKnown(inv
);
1870 LogPrint(BCLog::NET
, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->GetId());
1871 } else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload()) {
1876 // Track requests for our stuff
1877 GetMainSignals().Inventory(inv
.hash
);
1882 else if (strCommand
== NetMsgType::GETDATA
)
1884 std::vector
<CInv
> vInv
;
1886 if (vInv
.size() > MAX_INV_SZ
)
1889 Misbehaving(pfrom
->GetId(), 20);
1890 return error("message getdata size() = %u", vInv
.size());
1893 LogPrint(BCLog::NET
, "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->GetId());
1895 if (vInv
.size() > 0) {
1896 LogPrint(BCLog::NET
, "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->GetId());
1899 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
1900 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1904 else if (strCommand
== NetMsgType::GETBLOCKS
)
1906 CBlockLocator locator
;
1908 vRecv
>> locator
>> hashStop
;
1910 // We might have announced the currently-being-connected tip using a
1911 // compact block, which resulted in the peer sending a getblocks
1912 // request, which we would otherwise respond to without the new block.
1913 // To avoid this situation we simply verify that we are on our best
1914 // known chain now. This is super overkill, but we handle it better
1915 // for getheaders requests, and there are no known nodes which support
1916 // compact blocks but still use getblocks to request blocks.
1918 std::shared_ptr
<const CBlock
> a_recent_block
;
1920 LOCK(cs_most_recent_block
);
1921 a_recent_block
= most_recent_block
;
1923 CValidationState dummy
;
1924 ActivateBestChain(dummy
, Params(), a_recent_block
);
1929 // Find the last block the caller has in the main chain
1930 const CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1932 // Send the rest of the chain
1934 pindex
= chainActive
.Next(pindex
);
1936 LogPrint(BCLog::NET
, "getblocks %d to %s limit %d from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), nLimit
, pfrom
->GetId());
1937 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1939 if (pindex
->GetBlockHash() == hashStop
)
1941 LogPrint(BCLog::NET
, " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1944 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1945 // for some reasonable time window (1 hour) that block relay might require.
1946 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
1947 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
1949 LogPrint(BCLog::NET
, " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1952 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
1955 // When this block is requested, we'll send an inv that'll
1956 // trigger the peer to getblocks the next batch of inventory.
1957 LogPrint(BCLog::NET
, " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1958 pfrom
->hashContinue
= pindex
->GetBlockHash();
1965 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
1967 BlockTransactionsRequest req
;
1970 std::shared_ptr
<const CBlock
> recent_block
;
1972 LOCK(cs_most_recent_block
);
1973 if (most_recent_block_hash
== req
.blockhash
)
1974 recent_block
= most_recent_block
;
1975 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1978 SendBlockTransactions(*recent_block
, req
, pfrom
, connman
);
1984 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
1985 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
1986 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom
->GetId());
1990 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
1991 // If an older block is requested (should never happen in practice,
1992 // but can happen in tests) send a block response instead of a
1993 // blocktxn response. Sending a full block response instead of a
1994 // small blocktxn response is preferable in the case where a peer
1995 // might maliciously send lots of getblocktxn requests to trigger
1996 // expensive disk reads, because it will require the peer to
1997 // actually receive all the data read from disk over the network.
1998 LogPrint(BCLog::NET
, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->GetId(), MAX_BLOCKTXN_DEPTH
);
2000 inv
.type
= State(pfrom
->GetId())->fWantsCmpctWitness
? MSG_WITNESS_BLOCK
: MSG_BLOCK
;
2001 inv
.hash
= req
.blockhash
;
2002 pfrom
->vRecvGetData
.push_back(inv
);
2003 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2008 bool ret
= ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus());
2011 SendBlockTransactions(block
, req
, pfrom
, connman
);
2015 else if (strCommand
== NetMsgType::GETHEADERS
)
2017 CBlockLocator locator
;
2019 vRecv
>> locator
>> hashStop
;
2022 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
2023 LogPrint(BCLog::NET
, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->GetId());
2027 CNodeState
*nodestate
= State(pfrom
->GetId());
2028 const CBlockIndex
* pindex
= nullptr;
2029 if (locator
.IsNull())
2031 // If locator is null, return the hashStop block
2032 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
2033 if (mi
== mapBlockIndex
.end())
2035 pindex
= (*mi
).second
;
2037 if (!chainActive
.Contains(pindex
) &&
2038 !StaleBlockRequestAllowed(pindex
, chainparams
.GetConsensus())) {
2039 LogPrintf("%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__
, pfrom
->GetId());
2045 // Find the last block the caller has in the main chain
2046 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
2048 pindex
= chainActive
.Next(pindex
);
2051 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
2052 std::vector
<CBlock
> vHeaders
;
2053 int nLimit
= MAX_HEADERS_RESULTS
;
2054 LogPrint(BCLog::NET
, "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->GetId());
2055 for (; pindex
; pindex
= chainActive
.Next(pindex
))
2057 vHeaders
.push_back(pindex
->GetBlockHeader());
2058 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
2061 // pindex can be nullptr either if we sent chainActive.Tip() OR
2062 // if our peer has chainActive.Tip() (and thus we are sending an empty
2063 // headers message). In both cases it's safe to update
2064 // pindexBestHeaderSent to be our tip.
2066 // It is important that we simply reset the BestHeaderSent value here,
2067 // and not max(BestHeaderSent, newHeaderSent). We might have announced
2068 // the currently-being-connected tip using a compact block, which
2069 // resulted in the peer sending a headers request, which we respond to
2070 // without the new block. By resetting the BestHeaderSent, we ensure we
2071 // will re-announce the new block via headers (or compact blocks again)
2072 // in the SendMessages logic.
2073 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
2074 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
2078 else if (strCommand
== NetMsgType::TX
)
2080 // Stop processing the transaction early if
2081 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
2082 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !gArgs
.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
2084 LogPrint(BCLog::NET
, "transaction sent in violation of protocol peer=%d\n", pfrom
->GetId());
2088 std::deque
<COutPoint
> vWorkQueue
;
2089 std::vector
<uint256
> vEraseQueue
;
2090 CTransactionRef ptx
;
2092 const CTransaction
& tx
= *ptx
;
2094 CInv
inv(MSG_TX
, tx
.GetHash());
2095 pfrom
->AddInventoryKnown(inv
);
2099 bool fMissingInputs
= false;
2100 CValidationState state
;
2102 pfrom
->setAskFor
.erase(inv
.hash
);
2103 mapAlreadyAskedFor
.erase(inv
.hash
);
2105 std::list
<CTransactionRef
> lRemovedTxn
;
2107 if (!AlreadyHave(inv
) &&
2108 AcceptToMemoryPool(mempool
, state
, ptx
, &fMissingInputs
, &lRemovedTxn
, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2109 mempool
.check(pcoinsTip
);
2110 RelayTransaction(tx
, connman
);
2111 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
2112 vWorkQueue
.emplace_back(inv
.hash
, i
);
2115 pfrom
->nLastTXTime
= GetTime();
2117 LogPrint(BCLog::MEMPOOL
, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
2119 tx
.GetHash().ToString(),
2120 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
2122 // Recursively process any orphan transactions that depended on this one
2123 std::set
<NodeId
> setMisbehaving
;
2124 while (!vWorkQueue
.empty()) {
2125 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
2126 vWorkQueue
.pop_front();
2127 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
2129 for (auto mi
= itByPrev
->second
.begin();
2130 mi
!= itByPrev
->second
.end();
2133 const CTransactionRef
& porphanTx
= (*mi
)->second
.tx
;
2134 const CTransaction
& orphanTx
= *porphanTx
;
2135 const uint256
& orphanHash
= orphanTx
.GetHash();
2136 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
2137 bool fMissingInputs2
= false;
2138 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
2139 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
2140 // anyone relaying LegitTxX banned)
2141 CValidationState stateDummy
;
2144 if (setMisbehaving
.count(fromPeer
))
2146 if (AcceptToMemoryPool(mempool
, stateDummy
, porphanTx
, &fMissingInputs2
, &lRemovedTxn
, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
2147 LogPrint(BCLog::MEMPOOL
, " accepted orphan tx %s\n", orphanHash
.ToString());
2148 RelayTransaction(orphanTx
, connman
);
2149 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
2150 vWorkQueue
.emplace_back(orphanHash
, i
);
2152 vEraseQueue
.push_back(orphanHash
);
2154 else if (!fMissingInputs2
)
2157 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
2159 // Punish peer that gave us an invalid orphan tx
2160 Misbehaving(fromPeer
, nDos
);
2161 setMisbehaving
.insert(fromPeer
);
2162 LogPrint(BCLog::MEMPOOL
, " invalid orphan tx %s\n", orphanHash
.ToString());
2164 // Has inputs but not accepted to mempool
2165 // Probably non-standard or insufficient fee
2166 LogPrint(BCLog::MEMPOOL
, " removed orphan tx %s\n", orphanHash
.ToString());
2167 vEraseQueue
.push_back(orphanHash
);
2168 if (!orphanTx
.HasWitness() && !stateDummy
.CorruptionPossible()) {
2169 // Do not use rejection cache for witness transactions or
2170 // witness-stripped transactions, as they can have been malleated.
2171 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2172 assert(recentRejects
);
2173 recentRejects
->insert(orphanHash
);
2176 mempool
.check(pcoinsTip
);
2180 for (uint256 hash
: vEraseQueue
)
2181 EraseOrphanTx(hash
);
2183 else if (fMissingInputs
)
2185 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
2186 for (const CTxIn
& txin
: tx
.vin
) {
2187 if (recentRejects
->contains(txin
.prevout
.hash
)) {
2188 fRejectedParents
= true;
2192 if (!fRejectedParents
) {
2193 uint32_t nFetchFlags
= GetFetchFlags(pfrom
);
2194 for (const CTxIn
& txin
: tx
.vin
) {
2195 CInv
_inv(MSG_TX
| nFetchFlags
, txin
.prevout
.hash
);
2196 pfrom
->AddInventoryKnown(_inv
);
2197 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
2199 AddOrphanTx(ptx
, pfrom
->GetId());
2201 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2202 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, gArgs
.GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
2203 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
2205 LogPrint(BCLog::MEMPOOL
, "mapOrphan overflow, removed %u tx\n", nEvicted
);
2208 LogPrint(BCLog::MEMPOOL
, "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
2209 // We will continue to reject this tx since it has rejected
2210 // parents so avoid re-requesting it from other peers.
2211 recentRejects
->insert(tx
.GetHash());
2214 if (!tx
.HasWitness() && !state
.CorruptionPossible()) {
2215 // Do not use rejection cache for witness transactions or
2216 // witness-stripped transactions, as they can have been malleated.
2217 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
2218 assert(recentRejects
);
2219 recentRejects
->insert(tx
.GetHash());
2220 if (RecursiveDynamicUsage(*ptx
) < 100000) {
2221 AddToCompactExtraTransactions(ptx
);
2223 } else if (tx
.HasWitness() && RecursiveDynamicUsage(*ptx
) < 100000) {
2224 AddToCompactExtraTransactions(ptx
);
2227 if (pfrom
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
2228 // Always relay transactions received from whitelisted peers, even
2229 // if they were already in the mempool or rejected from it due
2230 // to policy, allowing the node to function as a gateway for
2231 // nodes hidden behind it.
2233 // Never relay transactions that we would assign a non-zero DoS
2234 // score for, as we expect peers to do the same with us in that
2237 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
2238 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->GetId());
2239 RelayTransaction(tx
, connman
);
2241 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->GetId(), FormatStateMessage(state
));
2246 for (const CTransactionRef
& removedTx
: lRemovedTxn
)
2247 AddToCompactExtraTransactions(removedTx
);
2250 if (state
.IsInvalid(nDoS
))
2252 LogPrint(BCLog::MEMPOOLREJ
, "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
2254 FormatStateMessage(state
));
2255 if (state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
2256 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
2257 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
));
2259 Misbehaving(pfrom
->GetId(), nDoS
);
2265 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2267 CBlockHeaderAndShortTxIDs cmpctblock
;
2268 vRecv
>> cmpctblock
;
2270 bool received_new_header
= false;
2275 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
2276 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
2277 if (!IsInitialBlockDownload())
2278 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
2282 if (mapBlockIndex
.find(cmpctblock
.header
.GetHash()) == mapBlockIndex
.end()) {
2283 received_new_header
= true;
2287 const CBlockIndex
*pindex
= nullptr;
2288 CValidationState state
;
2289 if (!ProcessNewBlockHeaders({cmpctblock
.header
}, state
, chainparams
, &pindex
)) {
2291 if (state
.IsInvalid(nDoS
)) {
2294 Misbehaving(pfrom
->GetId(), nDoS
);
2296 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->GetId());
2301 // When we succeed in decoding a block's txids from a cmpctblock
2302 // message we typically jump to the BLOCKTXN handling code, with a
2303 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2304 // completing processing of the putative block (without cs_main).
2305 bool fProcessBLOCKTXN
= false;
2306 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2308 // If we end up treating this as a plain headers message, call that as well
2310 bool fRevertToHeaderProcessing
= false;
2312 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2314 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2315 bool fBlockReconstructed
= false;
2319 // If AcceptBlockHeader returned true, it set pindex
2321 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
2323 CNodeState
*nodestate
= State(pfrom
->GetId());
2325 // If this was a new header with more work than our tip, update the
2326 // peer's last block announcement time
2327 if (received_new_header
&& pindex
->nChainWork
> chainActive
.Tip()->nChainWork
) {
2328 nodestate
->m_last_block_announcement
= GetTime();
2331 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
2332 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
2334 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
2337 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
2338 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
2339 if (fAlreadyInFlight
) {
2340 // We requested this block for some reason, but our mempool will probably be useless
2341 // so we just grab the block via normal getdata
2342 std::vector
<CInv
> vInv(1);
2343 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2344 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2349 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2350 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
2353 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
2354 // Don't bother trying to process compact blocks from v1 peers
2355 // after segwit activates.
2359 // We want to be a bit conservative just to be extra careful about DoS
2360 // possibilities in compact block processing...
2361 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
2362 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
2363 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
2364 std::list
<QueuedBlock
>::iterator
* queuedBlockIt
= nullptr;
2365 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), pindex
, &queuedBlockIt
)) {
2366 if (!(*queuedBlockIt
)->partialBlock
)
2367 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
2369 // The block was already in flight using compact blocks from the same peer
2370 LogPrint(BCLog::NET
, "Peer sent us compact block we were already syncing!\n");
2375 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
2376 ReadStatus status
= partialBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2377 if (status
== READ_STATUS_INVALID
) {
2378 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
2379 Misbehaving(pfrom
->GetId(), 100);
2380 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->GetId());
2382 } else if (status
== READ_STATUS_FAILED
) {
2383 // Duplicate txindexes, the block is now in-flight, so just request it
2384 std::vector
<CInv
> vInv(1);
2385 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2386 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2390 BlockTransactionsRequest req
;
2391 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
2392 if (!partialBlock
.IsTxAvailable(i
))
2393 req
.indexes
.push_back(i
);
2395 if (req
.indexes
.empty()) {
2396 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2397 BlockTransactions txn
;
2398 txn
.blockhash
= cmpctblock
.header
.GetHash();
2400 fProcessBLOCKTXN
= true;
2402 req
.blockhash
= pindex
->GetBlockHash();
2403 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETBLOCKTXN
, req
));
2406 // This block is either already in flight from a different
2407 // peer, or this peer has too many blocks outstanding to
2409 // Optimistically try to reconstruct anyway since we might be
2410 // able to without any round trips.
2411 PartiallyDownloadedBlock
tempBlock(&mempool
);
2412 ReadStatus status
= tempBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2413 if (status
!= READ_STATUS_OK
) {
2414 // TODO: don't ignore failures
2417 std::vector
<CTransactionRef
> dummy
;
2418 status
= tempBlock
.FillBlock(*pblock
, dummy
);
2419 if (status
== READ_STATUS_OK
) {
2420 fBlockReconstructed
= true;
2424 if (fAlreadyInFlight
) {
2425 // We requested this block, but its far into the future, so our
2426 // mempool will probably be useless - request the block normally
2427 std::vector
<CInv
> vInv(1);
2428 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), cmpctblock
.header
.GetHash());
2429 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2432 // If this was an announce-cmpctblock, we want the same treatment as a header message
2433 fRevertToHeaderProcessing
= true;
2438 if (fProcessBLOCKTXN
)
2439 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2441 if (fRevertToHeaderProcessing
) {
2442 // Headers received from HB compact block peers are permitted to be
2443 // relayed before full validation (see BIP 152), so we don't want to disconnect
2444 // the peer if the header turns out to be for an invalid block.
2445 // Note that if a peer tries to build on an invalid chain, that
2446 // will be detected and the peer will be banned.
2447 return ProcessHeadersMessage(pfrom
, connman
, {cmpctblock
.header
}, chainparams
, /*punish_duplicate_invalid=*/false);
2450 if (fBlockReconstructed
) {
2451 // If we got here, we were able to optimistically reconstruct a
2452 // block that is in flight from some other peer.
2455 mapBlockSource
.emplace(pblock
->GetHash(), std::make_pair(pfrom
->GetId(), false));
2457 bool fNewBlock
= false;
2458 // Setting fForceProcessing to true means that we bypass some of
2459 // our anti-DoS protections in AcceptBlock, which filters
2460 // unrequested blocks that might be trying to waste our resources
2461 // (eg disk space). Because we only try to reconstruct blocks when
2462 // we're close to caught up (via the CanDirectFetch() requirement
2463 // above, combined with the behavior of not requesting blocks until
2464 // we have a chain with at least nMinimumChainWork), and we ignore
2465 // compact blocks with less work than our tip, it is safe to treat
2466 // reconstructed compact blocks as having been requested.
2467 ProcessNewBlock(chainparams
, pblock
, /*fForceProcessing=*/true, &fNewBlock
);
2469 pfrom
->nLastBlockTime
= GetTime();
2472 mapBlockSource
.erase(pblock
->GetHash());
2474 LOCK(cs_main
); // hold cs_main for CBlockIndex::IsValid()
2475 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
)) {
2476 // Clear download state for this block, which is in
2477 // process from some other peer. We do this after calling
2478 // ProcessNewBlock so that a malleated cmpctblock announcement
2479 // can't be used to interfere with block relay.
2480 MarkBlockAsReceived(pblock
->GetHash());
2486 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2488 BlockTransactions resp
;
2491 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2492 bool fBlockRead
= false;
2496 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
2497 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
2498 it
->second
.first
!= pfrom
->GetId()) {
2499 LogPrint(BCLog::NET
, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->GetId());
2503 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
2504 ReadStatus status
= partialBlock
.FillBlock(*pblock
, resp
.txn
);
2505 if (status
== READ_STATUS_INVALID
) {
2506 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
2507 Misbehaving(pfrom
->GetId(), 100);
2508 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->GetId());
2510 } else if (status
== READ_STATUS_FAILED
) {
2511 // Might have collided, fall back to getdata now :(
2512 std::vector
<CInv
> invs
;
2513 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
), resp
.blockhash
));
2514 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, invs
));
2516 // Block is either okay, or possibly we received
2517 // READ_STATUS_CHECKBLOCK_FAILED.
2518 // Note that CheckBlock can only fail for one of a few reasons:
2519 // 1. bad-proof-of-work (impossible here, because we've already
2520 // accepted the header)
2521 // 2. merkleroot doesn't match the transactions given (already
2522 // caught in FillBlock with READ_STATUS_FAILED, so
2524 // 3. the block is otherwise invalid (eg invalid coinbase,
2525 // block is too big, too many legacy sigops, etc).
2526 // So if CheckBlock failed, #3 is the only possibility.
2527 // Under BIP 152, we don't DoS-ban unless proof of work is
2528 // invalid (we don't require all the stateless checks to have
2529 // been run). This is handled below, so just treat this as
2530 // though the block was successfully read, and rely on the
2531 // handling in ProcessNewBlock to ensure the block index is
2532 // updated, reject messages go out, etc.
2533 MarkBlockAsReceived(resp
.blockhash
); // it is now an empty pointer
2535 // mapBlockSource is only used for sending reject messages and DoS scores,
2536 // so the race between here and cs_main in ProcessNewBlock is fine.
2537 // BIP 152 permits peers to relay compact blocks after validating
2538 // the header only; we should not punish peers if the block turns
2539 // out to be invalid.
2540 mapBlockSource
.emplace(resp
.blockhash
, std::make_pair(pfrom
->GetId(), false));
2542 } // Don't hold cs_main when we call into ProcessNewBlock
2544 bool fNewBlock
= false;
2545 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2546 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2547 // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent
2548 // disk-space attacks), but this should be safe due to the
2549 // protections in the compact block handler -- see related comment
2550 // in compact block optimistic reconstruction handling.
2551 ProcessNewBlock(chainparams
, pblock
, /*fForceProcessing=*/true, &fNewBlock
);
2553 pfrom
->nLastBlockTime
= GetTime();
2556 mapBlockSource
.erase(pblock
->GetHash());
2562 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
2564 std::vector
<CBlockHeader
> headers
;
2566 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2567 unsigned int nCount
= ReadCompactSize(vRecv
);
2568 if (nCount
> MAX_HEADERS_RESULTS
) {
2570 Misbehaving(pfrom
->GetId(), 20);
2571 return error("headers message size = %u", nCount
);
2573 headers
.resize(nCount
);
2574 for (unsigned int n
= 0; n
< nCount
; n
++) {
2575 vRecv
>> headers
[n
];
2576 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
2579 // Headers received via a HEADERS message should be valid, and reflect
2580 // the chain the peer is on. If we receive a known-invalid header,
2581 // disconnect the peer if it is using one of our outbound connection
2583 bool should_punish
= !pfrom
->fInbound
&& !pfrom
->m_manual_connection
;
2584 return ProcessHeadersMessage(pfrom
, connman
, headers
, chainparams
, should_punish
);
2587 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2589 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2592 LogPrint(BCLog::NET
, "received block %s peer=%d\n", pblock
->GetHash().ToString(), pfrom
->GetId());
2594 bool forceProcessing
= false;
2595 const uint256
hash(pblock
->GetHash());
2598 // Also always process if we requested the block explicitly, as we may
2599 // need it even though it is not a candidate for a new best tip.
2600 forceProcessing
|= MarkBlockAsReceived(hash
);
2601 // mapBlockSource is only used for sending reject messages and DoS scores,
2602 // so the race between here and cs_main in ProcessNewBlock is fine.
2603 mapBlockSource
.emplace(hash
, std::make_pair(pfrom
->GetId(), true));
2605 bool fNewBlock
= false;
2606 ProcessNewBlock(chainparams
, pblock
, forceProcessing
, &fNewBlock
);
2608 pfrom
->nLastBlockTime
= GetTime();
2611 mapBlockSource
.erase(pblock
->GetHash());
2616 else if (strCommand
== NetMsgType::GETADDR
)
2618 // This asymmetric behavior for inbound and outbound connections was introduced
2619 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2620 // to users' AddrMan and later request them by sending getaddr messages.
2621 // Making nodes which are behind NAT and can only make outgoing connections ignore
2622 // the getaddr message mitigates the attack.
2623 if (!pfrom
->fInbound
) {
2624 LogPrint(BCLog::NET
, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->GetId());
2628 // Only send one GetAddr response per connection to reduce resource waste
2629 // and discourage addr stamping of INV announcements.
2630 if (pfrom
->fSentAddr
) {
2631 LogPrint(BCLog::NET
, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->GetId());
2634 pfrom
->fSentAddr
= true;
2636 pfrom
->vAddrToSend
.clear();
2637 std::vector
<CAddress
> vAddr
= connman
->GetAddresses();
2638 FastRandomContext insecure_rand
;
2639 for (const CAddress
&addr
: vAddr
)
2640 pfrom
->PushAddress(addr
, insecure_rand
);
2644 else if (strCommand
== NetMsgType::MEMPOOL
)
2646 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
2648 LogPrint(BCLog::NET
, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
2649 pfrom
->fDisconnect
= true;
2653 if (connman
->OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
2655 LogPrint(BCLog::NET
, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
2656 pfrom
->fDisconnect
= true;
2660 LOCK(pfrom
->cs_inventory
);
2661 pfrom
->fSendMempool
= true;
2665 else if (strCommand
== NetMsgType::PING
)
2667 if (pfrom
->nVersion
> BIP0031_VERSION
)
2671 // Echo the message back with the nonce. This allows for two useful features:
2673 // 1) A remote node can quickly check if the connection is operational
2674 // 2) Remote nodes can measure the latency of the network thread. If this node
2675 // is overloaded it won't respond to pings quickly and the remote node can
2676 // avoid sending us more work, like chain download requests.
2678 // The nonce stops the remote getting confused between different pings: without
2679 // it, if the remote node sends a ping once per second and this node takes 5
2680 // seconds to respond to each, the 5th ping the remote sends would appear to
2681 // return very quickly.
2682 connman
->PushMessage(pfrom
, msgMaker
.Make(NetMsgType::PONG
, nonce
));
2687 else if (strCommand
== NetMsgType::PONG
)
2689 int64_t pingUsecEnd
= nTimeReceived
;
2691 size_t nAvail
= vRecv
.in_avail();
2692 bool bPingFinished
= false;
2693 std::string sProblem
;
2695 if (nAvail
>= sizeof(nonce
)) {
2698 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2699 if (pfrom
->nPingNonceSent
!= 0) {
2700 if (nonce
== pfrom
->nPingNonceSent
) {
2701 // Matching pong received, this ping is no longer outstanding
2702 bPingFinished
= true;
2703 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
2704 if (pingUsecTime
> 0) {
2705 // Successful ping time measurement, replace previous
2706 pfrom
->nPingUsecTime
= pingUsecTime
;
2707 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
.load(), pingUsecTime
);
2709 // This should never happen
2710 sProblem
= "Timing mishap";
2713 // Nonce mismatches are normal when pings are overlapping
2714 sProblem
= "Nonce mismatch";
2716 // This is most likely a bug in another implementation somewhere; cancel this ping
2717 bPingFinished
= true;
2718 sProblem
= "Nonce zero";
2722 sProblem
= "Unsolicited pong without ping";
2725 // This is most likely a bug in another implementation somewhere; cancel this ping
2726 bPingFinished
= true;
2727 sProblem
= "Short payload";
2730 if (!(sProblem
.empty())) {
2731 LogPrint(BCLog::NET
, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2734 pfrom
->nPingNonceSent
,
2738 if (bPingFinished
) {
2739 pfrom
->nPingNonceSent
= 0;
2744 else if (strCommand
== NetMsgType::FILTERLOAD
)
2746 CBloomFilter filter
;
2749 if (!filter
.IsWithinSizeConstraints())
2751 // There is no excuse for sending a too-large filter
2753 Misbehaving(pfrom
->GetId(), 100);
2757 LOCK(pfrom
->cs_filter
);
2758 delete pfrom
->pfilter
;
2759 pfrom
->pfilter
= new CBloomFilter(filter
);
2760 pfrom
->pfilter
->UpdateEmptyFull();
2761 pfrom
->fRelayTxes
= true;
2766 else if (strCommand
== NetMsgType::FILTERADD
)
2768 std::vector
<unsigned char> vData
;
2771 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2772 // and thus, the maximum size any matched object can have) in a filteradd message
2774 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
2777 LOCK(pfrom
->cs_filter
);
2778 if (pfrom
->pfilter
) {
2779 pfrom
->pfilter
->insert(vData
);
2786 Misbehaving(pfrom
->GetId(), 100);
2791 else if (strCommand
== NetMsgType::FILTERCLEAR
)
2793 LOCK(pfrom
->cs_filter
);
2794 if (pfrom
->GetLocalServices() & NODE_BLOOM
) {
2795 delete pfrom
->pfilter
;
2796 pfrom
->pfilter
= new CBloomFilter();
2798 pfrom
->fRelayTxes
= true;
2801 else if (strCommand
== NetMsgType::FEEFILTER
) {
2802 CAmount newFeeFilter
= 0;
2803 vRecv
>> newFeeFilter
;
2804 if (MoneyRange(newFeeFilter
)) {
2806 LOCK(pfrom
->cs_feeFilter
);
2807 pfrom
->minFeeFilter
= newFeeFilter
;
2809 LogPrint(BCLog::NET
, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->GetId());
2813 else if (strCommand
== NetMsgType::NOTFOUND
) {
2814 // We do not care about the NOTFOUND message, but logging an Unknown Command
2815 // message would be undesirable as we transmit it ourselves.
2819 // Ignore unknown commands for extensibility
2820 LogPrint(BCLog::NET
, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->GetId());
2828 static bool SendRejectsAndCheckIfBanned(CNode
* pnode
, CConnman
* connman
)
2830 AssertLockHeld(cs_main
);
2831 CNodeState
&state
= *State(pnode
->GetId());
2833 for (const CBlockReject
& reject
: state
.rejects
) {
2834 connman
->PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, (std::string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
));
2836 state
.rejects
.clear();
2838 if (state
.fShouldBan
) {
2839 state
.fShouldBan
= false;
2840 if (pnode
->fWhitelisted
)
2841 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode
->addr
.ToString());
2842 else if (pnode
->m_manual_connection
)
2843 LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode
->addr
.ToString());
2845 pnode
->fDisconnect
= true;
2846 if (pnode
->addr
.IsLocal())
2847 LogPrintf("Warning: not banning local peer %s!\n", pnode
->addr
.ToString());
2850 connman
->Ban(pnode
->addr
, BanReasonNodeMisbehaving
);
2858 bool PeerLogicValidation::ProcessMessages(CNode
* pfrom
, std::atomic
<bool>& interruptMsgProc
)
2860 const CChainParams
& chainparams
= Params();
2863 // (4) message start
2869 bool fMoreWork
= false;
2871 if (!pfrom
->vRecvGetData
.empty())
2872 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2874 if (pfrom
->fDisconnect
)
2877 // this maintains the order of responses
2878 if (!pfrom
->vRecvGetData
.empty()) return true;
2880 // Don't bother if send buffer is too full to respond anyway
2881 if (pfrom
->fPauseSend
)
2884 std::list
<CNetMessage
> msgs
;
2886 LOCK(pfrom
->cs_vProcessMsg
);
2887 if (pfrom
->vProcessMsg
.empty())
2889 // Just take one message
2890 msgs
.splice(msgs
.begin(), pfrom
->vProcessMsg
, pfrom
->vProcessMsg
.begin());
2891 pfrom
->nProcessQueueSize
-= msgs
.front().vRecv
.size() + CMessageHeader::HEADER_SIZE
;
2892 pfrom
->fPauseRecv
= pfrom
->nProcessQueueSize
> connman
->GetReceiveFloodSize();
2893 fMoreWork
= !pfrom
->vProcessMsg
.empty();
2895 CNetMessage
& msg(msgs
.front());
2897 msg
.SetVersion(pfrom
->GetRecvVersion());
2898 // Scan for message start
2899 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
2900 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->GetId());
2901 pfrom
->fDisconnect
= true;
2906 CMessageHeader
& hdr
= msg
.hdr
;
2907 if (!hdr
.IsValid(chainparams
.MessageStart()))
2909 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->GetId());
2912 std::string strCommand
= hdr
.GetCommand();
2915 unsigned int nMessageSize
= hdr
.nMessageSize
;
2918 CDataStream
& vRecv
= msg
.vRecv
;
2919 const uint256
& hash
= msg
.GetMessageHash();
2920 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
2922 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
2923 SanitizeString(strCommand
), nMessageSize
,
2924 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
2925 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
2933 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
, interruptMsgProc
);
2934 if (interruptMsgProc
)
2936 if (!pfrom
->vRecvGetData
.empty())
2939 catch (const std::ios_base::failure
& e
)
2941 connman
->PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, std::string("error parsing message")));
2942 if (strstr(e
.what(), "end of data"))
2944 // Allow exceptions from under-length message on vRecv
2945 LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2947 else if (strstr(e
.what(), "size too large"))
2949 // Allow exceptions from over-long size
2950 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2952 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
2954 // Allow exceptions from non-canonical encoding
2955 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2959 PrintExceptionContinue(&e
, "ProcessMessages()");
2962 catch (const std::exception
& e
) {
2963 PrintExceptionContinue(&e
, "ProcessMessages()");
2965 PrintExceptionContinue(nullptr, "ProcessMessages()");
2969 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->GetId());
2973 SendRejectsAndCheckIfBanned(pfrom
, connman
);
2978 void PeerLogicValidation::ConsiderEviction(CNode
*pto
, int64_t time_in_seconds
)
2980 AssertLockHeld(cs_main
);
2982 CNodeState
&state
= *State(pto
->GetId());
2983 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
2985 if (!state
.m_chain_sync
.m_protect
&& IsOutboundDisconnectionCandidate(pto
) && state
.fSyncStarted
) {
2986 // This is an outbound peer subject to disconnection if they don't
2987 // announce a block with as much work as the current tip within
2988 // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if
2989 // their chain has more work than ours, we should sync to it,
2990 // unless it's invalid, in which case we should find that out and
2991 // disconnect from them elsewhere).
2992 if (state
.pindexBestKnownBlock
!= nullptr && state
.pindexBestKnownBlock
->nChainWork
>= chainActive
.Tip()->nChainWork
) {
2993 if (state
.m_chain_sync
.m_timeout
!= 0) {
2994 state
.m_chain_sync
.m_timeout
= 0;
2995 state
.m_chain_sync
.m_work_header
= nullptr;
2996 state
.m_chain_sync
.m_sent_getheaders
= false;
2998 } 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
)) {
2999 // Our best block known by this peer is behind our tip, and we're either noticing
3000 // that for the first time, OR this peer was able to catch up to some earlier point
3001 // where we checked against our tip.
3002 // Either way, set a new timeout based on current tip.
3003 state
.m_chain_sync
.m_timeout
= time_in_seconds
+ CHAIN_SYNC_TIMEOUT
;
3004 state
.m_chain_sync
.m_work_header
= chainActive
.Tip();
3005 state
.m_chain_sync
.m_sent_getheaders
= false;
3006 } else if (state
.m_chain_sync
.m_timeout
> 0 && time_in_seconds
> state
.m_chain_sync
.m_timeout
) {
3007 // No evidence yet that our peer has synced to a chain with work equal to that
3008 // of our tip, when we first detected it was behind. Send a single getheaders
3009 // message to give the peer a chance to update us.
3010 if (state
.m_chain_sync
.m_sent_getheaders
) {
3011 // They've run out of time to catch up!
3012 LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto
->GetId(), state
.pindexBestKnownBlock
!= nullptr ? state
.pindexBestKnownBlock
->GetBlockHash().ToString() : "<none>");
3013 pto
->fDisconnect
= true;
3015 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());
3016 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(state
.m_chain_sync
.m_work_header
->pprev
), uint256()));
3017 state
.m_chain_sync
.m_sent_getheaders
= true;
3018 constexpr int64_t HEADERS_RESPONSE_TIME
= 120; // 2 minutes
3019 // Bump the timeout to allow a response, which could clear the timeout
3020 // (if the response shows the peer has synced), reset the timeout (if
3021 // the peer syncs to the required work but not to our tip), or result
3022 // in disconnect (if we advance to the timeout and pindexBestKnownBlock
3023 // has not sufficiently progressed)
3024 state
.m_chain_sync
.m_timeout
= time_in_seconds
+ HEADERS_RESPONSE_TIME
;
3030 void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds
)
3032 // Check whether we have too many outbound peers
3033 int extra_peers
= connman
->GetExtraOutboundCount();
3034 if (extra_peers
> 0) {
3035 // If we have more outbound peers than we target, disconnect one.
3036 // Pick the outbound peer that least recently announced
3037 // us a new block, with ties broken by choosing the more recent
3038 // connection (higher node id)
3039 NodeId worst_peer
= -1;
3040 int64_t oldest_block_announcement
= std::numeric_limits
<int64_t>::max();
3044 connman
->ForEachNode([&](CNode
* pnode
) {
3045 // Ignore non-outbound peers, or nodes marked for disconnect already
3046 if (!IsOutboundDisconnectionCandidate(pnode
) || pnode
->fDisconnect
) return;
3047 CNodeState
*state
= State(pnode
->GetId());
3048 if (state
== nullptr) return; // shouldn't be possible, but just in case
3049 // Don't evict our protected peers
3050 if (state
->m_chain_sync
.m_protect
) return;
3051 if (state
->m_last_block_announcement
< oldest_block_announcement
|| (state
->m_last_block_announcement
== oldest_block_announcement
&& pnode
->GetId() > worst_peer
)) {
3052 worst_peer
= pnode
->GetId();
3053 oldest_block_announcement
= state
->m_last_block_announcement
;
3056 if (worst_peer
!= -1) {
3057 bool disconnected
= connman
->ForNode(worst_peer
, [&](CNode
*pnode
) {
3058 // Only disconnect a peer that has been connected to us for
3059 // some reasonable fraction of our check-frequency, to give
3060 // it time for new information to have arrived.
3061 // Also don't disconnect any peer we're trying to download a
3063 CNodeState
&state
= *State(pnode
->GetId());
3064 if (time_in_seconds
- pnode
->nTimeConnected
> MINIMUM_CONNECT_TIME
&& state
.nBlocksInFlight
== 0) {
3065 LogPrint(BCLog::NET
, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode
->GetId(), oldest_block_announcement
);
3066 pnode
->fDisconnect
= true;
3069 LogPrint(BCLog::NET
, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode
->GetId(), pnode
->nTimeConnected
, state
.nBlocksInFlight
);
3074 // If we disconnected an extra peer, that means we successfully
3075 // connected to at least one peer after the last time we
3076 // detected a stale tip. Don't try any more extra peers until
3077 // we next detect a stale tip, to limit the load we put on the
3078 // network from these extra connections.
3079 connman
->SetTryNewOutboundPeer(false);
3085 void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params
&consensusParams
)
3087 if (connman
== nullptr) return;
3089 int64_t time_in_seconds
= GetTime();
3091 EvictExtraOutboundPeers(time_in_seconds
);
3093 if (time_in_seconds
> m_stale_tip_check_time
) {
3095 // Check whether our tip is stale, and if so, allow using an extra
3097 if (TipMayBeStale(consensusParams
)) {
3098 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
);
3099 connman
->SetTryNewOutboundPeer(true);
3100 } else if (connman
->GetTryNewOutboundPeer()) {
3101 connman
->SetTryNewOutboundPeer(false);
3103 m_stale_tip_check_time
= time_in_seconds
+ STALE_CHECK_INTERVAL
;
3107 class CompareInvMempoolOrder
3111 explicit CompareInvMempoolOrder(CTxMemPool
*_mempool
)
3116 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
3118 /* As std::make_heap produces a max-heap, we want the entries with the
3119 * fewest ancestors/highest fee to sort later. */
3120 return mp
->CompareDepthAndScore(*b
, *a
);
3124 bool PeerLogicValidation::SendMessages(CNode
* pto
, std::atomic
<bool>& interruptMsgProc
)
3126 const Consensus::Params
& consensusParams
= Params().GetConsensus();
3128 // Don't send anything until the version handshake is complete
3129 if (!pto
->fSuccessfullyConnected
|| pto
->fDisconnect
)
3132 // If we get here, the outgoing message serialization version is set and can't change.
3133 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
3138 bool pingSend
= false;
3139 if (pto
->fPingQueued
) {
3140 // RPC ping request by user
3143 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
3144 // Ping automatically sent as a latency probe & keepalive.
3149 while (nonce
== 0) {
3150 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
3152 pto
->fPingQueued
= false;
3153 pto
->nPingUsecStart
= GetTimeMicros();
3154 if (pto
->nVersion
> BIP0031_VERSION
) {
3155 pto
->nPingNonceSent
= nonce
;
3156 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
, nonce
));
3158 // Peer is too old to support ping command with nonce, pong will never arrive.
3159 pto
->nPingNonceSent
= 0;
3160 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
));
3164 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
3168 if (SendRejectsAndCheckIfBanned(pto
, connman
))
3170 CNodeState
&state
= *State(pto
->GetId());
3172 // Address refresh broadcast
3173 int64_t nNow
= GetTimeMicros();
3174 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
3175 AdvertiseLocal(pto
);
3176 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
3182 if (pto
->nNextAddrSend
< nNow
) {
3183 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
3184 std::vector
<CAddress
> vAddr
;
3185 vAddr
.reserve(pto
->vAddrToSend
.size());
3186 for (const CAddress
& addr
: pto
->vAddrToSend
)
3188 if (!pto
->addrKnown
.contains(addr
.GetKey()))
3190 pto
->addrKnown
.insert(addr
.GetKey());
3191 vAddr
.push_back(addr
);
3192 // receiver rejects addr messages larger than 1000
3193 if (vAddr
.size() >= 1000)
3195 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
3200 pto
->vAddrToSend
.clear();
3202 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
3203 // we only send the big addr message once
3204 if (pto
->vAddrToSend
.capacity() > 40)
3205 pto
->vAddrToSend
.shrink_to_fit();
3209 if (pindexBestHeader
== nullptr)
3210 pindexBestHeader
= chainActive
.Tip();
3211 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.
3212 if (!state
.fSyncStarted
&& !pto
->fClient
&& !fImporting
&& !fReindex
) {
3213 // Only actively request headers from a single peer, unless we're close to today.
3214 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
3215 state
.fSyncStarted
= true;
3216 state
.nHeadersSyncTimeout
= GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE
+ HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
* (GetAdjustedTime() - pindexBestHeader
->GetBlockTime())/(consensusParams
.nPowTargetSpacing
);
3218 const CBlockIndex
*pindexStart
= pindexBestHeader
;
3219 /* If possible, start at the block preceding the currently
3220 best known header. This ensures that we always get a
3221 non-empty list of headers back as long as the peer
3222 is up-to-date. With a non-empty response, we can initialise
3223 the peer's known best block. This wouldn't be possible
3224 if we requested starting at pindexBestHeader and
3225 got back an empty response. */
3226 if (pindexStart
->pprev
)
3227 pindexStart
= pindexStart
->pprev
;
3228 LogPrint(BCLog::NET
, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->GetId(), pto
->nStartingHeight
);
3229 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256()));
3233 // Resend wallet transactions that haven't gotten in a block yet
3234 // Except during reindex, importing and IBD, when old wallet
3235 // transactions become unconfirmed and spams other nodes.
3236 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
3238 GetMainSignals().Broadcast(nTimeBestReceived
, connman
);
3242 // Try sending block announcements via headers
3245 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
3246 // list of block hashes we're relaying, and our peer wants
3247 // headers announcements, then find the first header
3248 // not yet known to our peer but would connect, and send.
3249 // If no header would connect, or if we have too many
3250 // blocks, or if the peer doesn't want headers, just
3251 // add all to the inv queue.
3252 LOCK(pto
->cs_inventory
);
3253 std::vector
<CBlock
> vHeaders
;
3254 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
3255 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
3256 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
3257 const CBlockIndex
*pBestIndex
= nullptr; // last header queued for delivery
3258 ProcessBlockAvailability(pto
->GetId()); // ensure pindexBestKnownBlock is up-to-date
3260 if (!fRevertToInv
) {
3261 bool fFoundStartingHeader
= false;
3262 // Try to find first header that our peer doesn't have, and
3263 // then send all headers past that one. If we come across any
3264 // headers that aren't on chainActive, give up.
3265 for (const uint256
&hash
: pto
->vBlockHashesToAnnounce
) {
3266 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
3267 assert(mi
!= mapBlockIndex
.end());
3268 const CBlockIndex
*pindex
= mi
->second
;
3269 if (chainActive
[pindex
->nHeight
] != pindex
) {
3270 // Bail out if we reorged away from this block
3271 fRevertToInv
= true;
3274 if (pBestIndex
!= nullptr && pindex
->pprev
!= pBestIndex
) {
3275 // This means that the list of blocks to announce don't
3276 // connect to each other.
3277 // This shouldn't really be possible to hit during
3278 // regular operation (because reorgs should take us to
3279 // a chain that has some block not on the prior chain,
3280 // which should be caught by the prior check), but one
3281 // way this could happen is by using invalidateblock /
3282 // reconsiderblock repeatedly on the tip, causing it to
3283 // be added multiple times to vBlockHashesToAnnounce.
3284 // Robustly deal with this rare situation by reverting
3286 fRevertToInv
= true;
3289 pBestIndex
= pindex
;
3290 if (fFoundStartingHeader
) {
3291 // add this to the headers message
3292 vHeaders
.push_back(pindex
->GetBlockHeader());
3293 } else if (PeerHasHeader(&state
, pindex
)) {
3294 continue; // keep looking for the first new block
3295 } else if (pindex
->pprev
== nullptr || PeerHasHeader(&state
, pindex
->pprev
)) {
3296 // Peer doesn't have this header but they do have the prior one.
3297 // Start sending headers.
3298 fFoundStartingHeader
= true;
3299 vHeaders
.push_back(pindex
->GetBlockHeader());
3301 // Peer doesn't have this header or the prior one -- nothing will
3302 // connect, so bail out.
3303 fRevertToInv
= true;
3308 if (!fRevertToInv
&& !vHeaders
.empty()) {
3309 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
3310 // We only send up to 1 block as header-and-ids, as otherwise
3311 // probably means we're doing an initial-ish-sync or they're slow
3312 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", __func__
,
3313 vHeaders
.front().GetHash().ToString(), pto
->GetId());
3315 int nSendFlags
= state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
3317 bool fGotBlockFromCache
= false;
3319 LOCK(cs_most_recent_block
);
3320 if (most_recent_block_hash
== pBestIndex
->GetBlockHash()) {
3321 if (state
.fWantsCmpctWitness
|| !fWitnessesPresentInMostRecentCompactBlock
)
3322 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *most_recent_compact_block
));
3324 CBlockHeaderAndShortTxIDs
cmpctblock(*most_recent_block
, state
.fWantsCmpctWitness
);
3325 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3327 fGotBlockFromCache
= true;
3330 if (!fGotBlockFromCache
) {
3332 bool ret
= ReadBlockFromDisk(block
, pBestIndex
, consensusParams
);
3334 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
3335 connman
->PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3337 state
.pindexBestHeaderSent
= pBestIndex
;
3338 } else if (state
.fPreferHeaders
) {
3339 if (vHeaders
.size() > 1) {
3340 LogPrint(BCLog::NET
, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
3342 vHeaders
.front().GetHash().ToString(),
3343 vHeaders
.back().GetHash().ToString(), pto
->GetId());
3345 LogPrint(BCLog::NET
, "%s: sending header %s to peer=%d\n", __func__
,
3346 vHeaders
.front().GetHash().ToString(), pto
->GetId());
3348 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
3349 state
.pindexBestHeaderSent
= pBestIndex
;
3351 fRevertToInv
= true;
3354 // If falling back to using an inv, just try to inv the tip.
3355 // The last entry in vBlockHashesToAnnounce was our tip at some point
3357 if (!pto
->vBlockHashesToAnnounce
.empty()) {
3358 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
3359 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
3360 assert(mi
!= mapBlockIndex
.end());
3361 const CBlockIndex
*pindex
= mi
->second
;
3363 // Warn if we're announcing a block that is not on the main chain.
3364 // This should be very rare and could be optimized out.
3365 // Just log for now.
3366 if (chainActive
[pindex
->nHeight
] != pindex
) {
3367 LogPrint(BCLog::NET
, "Announcing block %s not on main chain (tip=%s)\n",
3368 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
3371 // If the peer's chain has this block, don't inv it back.
3372 if (!PeerHasHeader(&state
, pindex
)) {
3373 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
3374 LogPrint(BCLog::NET
, "%s: sending inv peer=%d hash=%s\n", __func__
,
3375 pto
->GetId(), hashToAnnounce
.ToString());
3379 pto
->vBlockHashesToAnnounce
.clear();
3383 // Message: inventory
3385 std::vector
<CInv
> vInv
;
3387 LOCK(pto
->cs_inventory
);
3388 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
3391 for (const uint256
& hash
: pto
->vInventoryBlockToSend
) {
3392 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
3393 if (vInv
.size() == MAX_INV_SZ
) {
3394 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3398 pto
->vInventoryBlockToSend
.clear();
3400 // Check whether periodic sends should happen
3401 bool fSendTrickle
= pto
->fWhitelisted
;
3402 if (pto
->nNextInvSend
< nNow
) {
3403 fSendTrickle
= true;
3404 // Use half the delay for outbound peers, as there is less privacy concern for them.
3405 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
3408 // Time to send but the peer has requested we not relay transactions.
3410 LOCK(pto
->cs_filter
);
3411 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
3414 // Respond to BIP35 mempool requests
3415 if (fSendTrickle
&& pto
->fSendMempool
) {
3416 auto vtxinfo
= mempool
.infoAll();
3417 pto
->fSendMempool
= false;
3418 CAmount filterrate
= 0;
3420 LOCK(pto
->cs_feeFilter
);
3421 filterrate
= pto
->minFeeFilter
;
3424 LOCK(pto
->cs_filter
);
3426 for (const auto& txinfo
: vtxinfo
) {
3427 const uint256
& hash
= txinfo
.tx
->GetHash();
3428 CInv
inv(MSG_TX
, hash
);
3429 pto
->setInventoryTxToSend
.erase(hash
);
3431 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
3435 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3437 pto
->filterInventoryKnown
.insert(hash
);
3438 vInv
.push_back(inv
);
3439 if (vInv
.size() == MAX_INV_SZ
) {
3440 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3444 pto
->timeLastMempoolReq
= GetTime();
3447 // Determine transactions to relay
3449 // Produce a vector with all candidates for sending
3450 std::vector
<std::set
<uint256
>::iterator
> vInvTx
;
3451 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
3452 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
3453 vInvTx
.push_back(it
);
3455 CAmount filterrate
= 0;
3457 LOCK(pto
->cs_feeFilter
);
3458 filterrate
= pto
->minFeeFilter
;
3460 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3461 // A heap is used so that not all items need sorting if only a few are being sent.
3462 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
3463 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3464 // No reason to drain out at many times the network's capacity,
3465 // especially since we have many peers and some will draw much shorter delays.
3466 unsigned int nRelayedTransactions
= 0;
3467 LOCK(pto
->cs_filter
);
3468 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
3469 // Fetch the top element from the heap
3470 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3471 std::set
<uint256
>::iterator it
= vInvTx
.back();
3474 // Remove it from the to-be-sent set
3475 pto
->setInventoryTxToSend
.erase(it
);
3476 // Check if not in the filter already
3477 if (pto
->filterInventoryKnown
.contains(hash
)) {
3480 // Not in the mempool anymore? don't bother sending it.
3481 auto txinfo
= mempool
.info(hash
);
3485 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
3488 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3490 vInv
.push_back(CInv(MSG_TX
, hash
));
3491 nRelayedTransactions
++;
3493 // Expire old relay messages
3494 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
3496 mapRelay
.erase(vRelayExpiration
.front().second
);
3497 vRelayExpiration
.pop_front();
3500 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
3502 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
3505 if (vInv
.size() == MAX_INV_SZ
) {
3506 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3509 pto
->filterInventoryKnown
.insert(hash
);
3514 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3516 // Detect whether we're stalling
3517 nNow
= GetTimeMicros();
3518 if (state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
3519 // Stalling only triggers when the block download window cannot move. During normal steady state,
3520 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3521 // should only happen during initial block download.
3522 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->GetId());
3523 pto
->fDisconnect
= true;
3526 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3527 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3528 // We compensate for other peers to prevent killing off peers due to our own downstream link
3529 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3530 // to unreasonably increase our timeout.
3531 if (state
.vBlocksInFlight
.size() > 0) {
3532 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
3533 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
3534 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
3535 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->GetId());
3536 pto
->fDisconnect
= true;
3540 // Check for headers sync timeouts
3541 if (state
.fSyncStarted
&& state
.nHeadersSyncTimeout
< std::numeric_limits
<int64_t>::max()) {
3542 // Detect whether this is a stalling initial-headers-sync peer
3543 if (pindexBestHeader
->GetBlockTime() <= GetAdjustedTime() - 24*60*60) {
3544 if (nNow
> state
.nHeadersSyncTimeout
&& nSyncStarted
== 1 && (nPreferredDownload
- state
.fPreferredDownload
>= 1)) {
3545 // Disconnect a (non-whitelisted) peer if it is our only sync peer,
3546 // and we have others we could be using instead.
3547 // Note: If all our peers are inbound, then we won't
3548 // disconnect our sync peer for stalling; we have bigger
3549 // problems if we can't get any outbound peers.
3550 if (!pto
->fWhitelisted
) {
3551 LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto
->GetId());
3552 pto
->fDisconnect
= true;
3555 LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto
->GetId());
3556 // Reset the headers sync state so that we have a
3557 // chance to try downloading from a different peer.
3558 // Note: this will also result in at least one more
3559 // getheaders message to be sent to
3560 // this peer (eventually).
3561 state
.fSyncStarted
= false;
3563 state
.nHeadersSyncTimeout
= 0;
3567 // After we've caught up once, reset the timeout so we can't trigger
3568 // disconnect later.
3569 state
.nHeadersSyncTimeout
= std::numeric_limits
<int64_t>::max();
3573 // Check that outbound peers have reasonable chains
3574 // GetTime() is used by this anti-DoS logic so we can test this using mocktime
3575 ConsiderEviction(pto
, GetTime());
3578 // Message: getdata (blocks)
3580 std::vector
<CInv
> vGetData
;
3581 if (!pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
3582 std::vector
<const CBlockIndex
*> vToDownload
;
3583 NodeId staller
= -1;
3584 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
3585 for (const CBlockIndex
*pindex
: vToDownload
) {
3586 uint32_t nFetchFlags
= GetFetchFlags(pto
);
3587 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
3588 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), pindex
);
3589 LogPrint(BCLog::NET
, "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
3590 pindex
->nHeight
, pto
->GetId());
3592 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
3593 if (State(staller
)->nStallingSince
== 0) {
3594 State(staller
)->nStallingSince
= nNow
;
3595 LogPrint(BCLog::NET
, "Stall started peer=%d\n", staller
);
3601 // Message: getdata (non-blocks)
3603 while (!pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
3605 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
3606 if (!AlreadyHave(inv
))
3608 LogPrint(BCLog::NET
, "Requesting %s peer=%d\n", inv
.ToString(), pto
->GetId());
3609 vGetData
.push_back(inv
);
3610 if (vGetData
.size() >= 1000)
3612 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3616 //If we're not going to ask, don't expect a response.
3617 pto
->setAskFor
.erase(inv
.hash
);
3619 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
3621 if (!vGetData
.empty())
3622 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3625 // Message: feefilter
3627 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3628 if (pto
->nVersion
>= FEEFILTER_VERSION
&& gArgs
.GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
3629 !(pto
->fWhitelisted
&& gArgs
.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
3630 CAmount currentFilter
= mempool
.GetMinFee(gArgs
.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
3631 int64_t timeNow
= GetTimeMicros();
3632 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
3633 static CFeeRate
default_feerate(DEFAULT_MIN_RELAY_TX_FEE
);
3634 static FeeFilterRounder
filterRounder(default_feerate
);
3635 CAmount filterToSend
= filterRounder
.round(currentFilter
);
3636 // We always have a fee filter of at least minRelayTxFee
3637 filterToSend
= std::max(filterToSend
, ::minRelayTxFee
.GetFeePerK());
3638 if (filterToSend
!= pto
->lastSentFeeFilter
) {
3639 connman
->PushMessage(pto
, msgMaker
.Make(NetMsgType::FEEFILTER
, filterToSend
));
3640 pto
->lastSentFeeFilter
= filterToSend
;
3642 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
3644 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3645 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3646 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
3647 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
3648 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
3655 class CNetProcessingCleanup
3658 CNetProcessingCleanup() {}
3659 ~CNetProcessingCleanup() {
3660 // orphan transactions
3661 mapOrphanTransactions
.clear();
3662 mapOrphanTransactionsByPrev
.clear();
3664 } instance_of_cnetprocessingcleanup
;