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 "tinyformat.h"
26 #include "txmempool.h"
27 #include "ui_interface.h"
29 #include "utilmoneystr.h"
30 #include "utilstrencodings.h"
31 #include "validationinterface.h"
33 #include <boost/thread.hpp>
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]
67 /** Number of nodes with fSyncStarted. */
71 * Sources of received blocks, saved to be able to send them reject
72 * messages or ban them when processing happens afterwards. Protected by
74 * Set mapBlockSource[hash].second to false if the node should not be
75 * punished if the block is invalid.
77 std::map
<uint256
, std::pair
<NodeId
, bool>> mapBlockSource
;
80 * Filter for transactions that were recently rejected by
81 * AcceptToMemoryPool. These are not rerequested until the chain tip
82 * changes, at which point the entire filter is reset. Protected by
85 * Without this filter we'd be re-requesting txs from each of our peers,
86 * increasing bandwidth consumption considerably. For instance, with 100
87 * peers, half of which relay a tx we don't accept, that might be a 50x
88 * bandwidth increase. A flooding attacker attempting to roll-over the
89 * filter using minimum-sized, 60byte, transactions might manage to send
90 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
91 * two minute window to send invs to us.
93 * Decreasing the false positive rate is fairly cheap, so we pick one in a
94 * million to make it highly unlikely for users to have issues with this
99 std::unique_ptr
<CRollingBloomFilter
> recentRejects
;
100 uint256 hashRecentRejectsChainTip
;
102 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
105 const CBlockIndex
* pindex
; //!< Optional.
106 bool fValidatedHeaders
; //!< Whether this block has validated headers at the time of request.
107 std::unique_ptr
<PartiallyDownloadedBlock
> partialBlock
; //!< Optional, used for CMPCTBLOCK downloads
109 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> > mapBlocksInFlight
;
111 /** Stack of nodes which we have set to announce using compact blocks */
112 std::list
<NodeId
> lNodesAnnouncingHeaderAndIDs
;
114 /** Number of preferable block download peers. */
115 int nPreferredDownload
= 0;
117 /** Number of peers from which we're downloading blocks. */
118 int nPeersWithValidatedDownloads
= 0;
120 /** Relay map, protected by cs_main. */
121 typedef std::map
<uint256
, CTransactionRef
> MapRelay
;
123 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
124 std::deque
<std::pair
<int64_t, MapRelay::iterator
>> vRelayExpiration
;
127 //////////////////////////////////////////////////////////////////////////////
129 // Registration of network node signals.
134 struct CBlockReject
{
135 unsigned char chRejectCode
;
136 std::string strRejectReason
;
141 * Maintain validation-specific state about nodes, protected by cs_main, instead
142 * by CNode's own locks. This simplifies asynchronous operation, where
143 * processing of incoming data is done after the ProcessMessage call returns,
144 * and we're no longer holding the node's locks.
147 //! The peer's address
148 const CService address
;
149 //! Whether we have a fully established connection.
150 bool fCurrentlyConnected
;
151 //! Accumulated misbehaviour score for this peer.
153 //! Whether this peer should be disconnected and banned (unless whitelisted).
155 //! String name of this peer (debugging/logging purposes).
156 const std::string name
;
157 //! List of asynchronously-determined block rejections to notify this peer about.
158 std::vector
<CBlockReject
> rejects
;
159 //! The best known block we know this peer has announced.
160 const CBlockIndex
*pindexBestKnownBlock
;
161 //! The hash of the last unknown block this peer has announced.
162 uint256 hashLastUnknownBlock
;
163 //! The last full block we both have.
164 const CBlockIndex
*pindexLastCommonBlock
;
165 //! The best header we have sent our peer.
166 const CBlockIndex
*pindexBestHeaderSent
;
167 //! Length of current-streak of unconnecting headers announcements
168 int nUnconnectingHeaders
;
169 //! Whether we've started headers synchronization with this peer.
171 //! Since when we're stalling block download progress (in microseconds), or 0.
172 int64_t nStallingSince
;
173 std::list
<QueuedBlock
> vBlocksInFlight
;
174 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
175 int64_t nDownloadingSince
;
177 int nBlocksInFlightValidHeaders
;
178 //! Whether we consider this a preferred download peer.
179 bool fPreferredDownload
;
180 //! Whether this peer wants invs or headers (when possible) for block announcements.
182 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
183 bool fPreferHeaderAndIDs
;
185 * Whether this peer will send us cmpctblocks if we request them.
186 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
187 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
189 bool fProvidesHeaderAndIDs
;
190 //! Whether this peer can give us witnesses
192 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
193 bool fWantsCmpctWitness
;
195 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
196 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
198 bool fSupportsDesiredCmpctVersion
;
200 CNodeState(CAddress addrIn
, std::string addrNameIn
) : address(addrIn
), name(addrNameIn
) {
201 fCurrentlyConnected
= false;
204 pindexBestKnownBlock
= NULL
;
205 hashLastUnknownBlock
.SetNull();
206 pindexLastCommonBlock
= NULL
;
207 pindexBestHeaderSent
= NULL
;
208 nUnconnectingHeaders
= 0;
209 fSyncStarted
= false;
211 nDownloadingSince
= 0;
213 nBlocksInFlightValidHeaders
= 0;
214 fPreferredDownload
= false;
215 fPreferHeaders
= false;
216 fPreferHeaderAndIDs
= false;
217 fProvidesHeaderAndIDs
= false;
218 fHaveWitness
= false;
219 fWantsCmpctWitness
= false;
220 fSupportsDesiredCmpctVersion
= false;
224 /** Map maintaining per-node state. Requires cs_main. */
225 std::map
<NodeId
, CNodeState
> mapNodeState
;
228 CNodeState
*State(NodeId pnode
) {
229 std::map
<NodeId
, CNodeState
>::iterator it
= mapNodeState
.find(pnode
);
230 if (it
== mapNodeState
.end())
235 void UpdatePreferredDownload(CNode
* node
, CNodeState
* state
)
237 nPreferredDownload
-= state
->fPreferredDownload
;
239 // Whether this node should be marked as a preferred download node.
240 state
->fPreferredDownload
= (!node
->fInbound
|| node
->fWhitelisted
) && !node
->fOneShot
&& !node
->fClient
;
242 nPreferredDownload
+= state
->fPreferredDownload
;
245 void PushNodeVersion(CNode
*pnode
, CConnman
& connman
, int64_t nTime
)
247 ServiceFlags nLocalNodeServices
= pnode
->GetLocalServices();
248 uint64_t nonce
= pnode
->GetLocalNonce();
249 int nNodeStartingHeight
= pnode
->GetMyStartingHeight();
250 NodeId nodeid
= pnode
->GetId();
251 CAddress addr
= pnode
->addr
;
253 CAddress addrYou
= (addr
.IsRoutable() && !IsProxy(addr
) ? addr
: CAddress(CService(), addr
.nServices
));
254 CAddress addrMe
= CAddress(CService(), nLocalNodeServices
);
256 connman
.PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERSION
, PROTOCOL_VERSION
, (uint64_t)nLocalNodeServices
, nTime
, addrYou
, addrMe
,
257 nonce
, strSubVersion
, nNodeStartingHeight
, ::fRelayTxes
));
260 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
);
262 LogPrint(BCLog::NET
, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), nodeid
);
266 void InitializeNode(CNode
*pnode
, CConnman
& connman
) {
267 CAddress addr
= pnode
->addr
;
268 std::string addrName
= pnode
->GetAddrName();
269 NodeId nodeid
= pnode
->GetId();
272 mapNodeState
.emplace_hint(mapNodeState
.end(), std::piecewise_construct
, std::forward_as_tuple(nodeid
), std::forward_as_tuple(addr
, std::move(addrName
)));
275 PushNodeVersion(pnode
, connman
, GetTime());
278 void FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
279 fUpdateConnectionTime
= false;
281 CNodeState
*state
= State(nodeid
);
283 if (state
->fSyncStarted
)
286 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
287 fUpdateConnectionTime
= true;
290 BOOST_FOREACH(const QueuedBlock
& entry
, state
->vBlocksInFlight
) {
291 mapBlocksInFlight
.erase(entry
.hash
);
293 EraseOrphansFor(nodeid
);
294 nPreferredDownload
-= state
->fPreferredDownload
;
295 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
296 assert(nPeersWithValidatedDownloads
>= 0);
298 mapNodeState
.erase(nodeid
);
300 if (mapNodeState
.empty()) {
301 // Do a consistency check after the last peer is removed.
302 assert(mapBlocksInFlight
.empty());
303 assert(nPreferredDownload
== 0);
304 assert(nPeersWithValidatedDownloads
== 0);
309 // Returns a bool indicating whether we requested this block.
310 // Also used if a block was /not/ received and timed out or started with another peer
311 bool MarkBlockAsReceived(const uint256
& hash
) {
312 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
313 if (itInFlight
!= mapBlocksInFlight
.end()) {
314 CNodeState
*state
= State(itInFlight
->second
.first
);
315 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
316 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
317 // Last validated block on the queue was received.
318 nPeersWithValidatedDownloads
--;
320 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
321 // First block on the queue was received, update the start download time for the next one
322 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
324 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
325 state
->nBlocksInFlight
--;
326 state
->nStallingSince
= 0;
327 mapBlocksInFlight
.erase(itInFlight
);
334 // returns false, still setting pit, if the block was already in flight from the same peer
335 // pit will only be valid as long as the same cs_main lock is being held
336 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindex
= NULL
, std::list
<QueuedBlock
>::iterator
** pit
= NULL
) {
337 CNodeState
*state
= State(nodeid
);
338 assert(state
!= NULL
);
340 // Short-circuit most stuff in case its from the same node
341 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
342 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
343 *pit
= &itInFlight
->second
.second
;
347 // Make sure it's not listed somewhere already.
348 MarkBlockAsReceived(hash
);
350 std::list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
351 {hash
, pindex
, pindex
!= NULL
, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : NULL
)});
352 state
->nBlocksInFlight
++;
353 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
354 if (state
->nBlocksInFlight
== 1) {
355 // We're starting a block download (batch) from this peer.
356 state
->nDownloadingSince
= GetTimeMicros();
358 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= NULL
) {
359 nPeersWithValidatedDownloads
++;
361 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
363 *pit
= &itInFlight
->second
.second
;
367 /** Check whether the last unknown block a peer advertised is not yet known. */
368 void ProcessBlockAvailability(NodeId nodeid
) {
369 CNodeState
*state
= State(nodeid
);
370 assert(state
!= NULL
);
372 if (!state
->hashLastUnknownBlock
.IsNull()) {
373 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
374 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
375 if (state
->pindexBestKnownBlock
== NULL
|| itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
376 state
->pindexBestKnownBlock
= itOld
->second
;
377 state
->hashLastUnknownBlock
.SetNull();
382 /** Update tracking information about which blocks a peer is assumed to have. */
383 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
384 CNodeState
*state
= State(nodeid
);
385 assert(state
!= NULL
);
387 ProcessBlockAvailability(nodeid
);
389 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
390 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
391 // An actually better block was announced.
392 if (state
->pindexBestKnownBlock
== NULL
|| it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
393 state
->pindexBestKnownBlock
= it
->second
;
395 // An unknown block was announced; just assume that the latest one is the best one.
396 state
->hashLastUnknownBlock
= hash
;
400 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid
, CConnman
& connman
) {
401 AssertLockHeld(cs_main
);
402 CNodeState
* nodestate
= State(nodeid
);
403 if (!nodestate
|| !nodestate
->fSupportsDesiredCmpctVersion
) {
404 // Never ask from peers who can't provide witnesses.
407 if (nodestate
->fProvidesHeaderAndIDs
) {
408 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
410 lNodesAnnouncingHeaderAndIDs
.erase(it
);
411 lNodesAnnouncingHeaderAndIDs
.push_back(nodeid
);
415 connman
.ForNode(nodeid
, [&connman
](CNode
* pfrom
){
416 bool fAnnounceUsingCMPCTBLOCK
= false;
417 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
418 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
419 // As per BIP152, we only get 3 of our peers to announce
420 // blocks using compact encodings.
421 connman
.ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [&connman
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
422 connman
.PushMessage(pnodeStop
, CNetMsgMaker(pnodeStop
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
425 lNodesAnnouncingHeaderAndIDs
.pop_front();
427 fAnnounceUsingCMPCTBLOCK
= true;
428 connman
.PushMessage(pfrom
, CNetMsgMaker(pfrom
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
429 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
436 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
438 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
442 bool PeerHasHeader(CNodeState
*state
, const CBlockIndex
*pindex
)
444 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
446 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
451 /** Find the last common ancestor two blocks have.
452 * Both pa and pb must be non-NULL. */
453 const CBlockIndex
* LastCommonAncestor(const CBlockIndex
* pa
, const CBlockIndex
* pb
) {
454 if (pa
->nHeight
> pb
->nHeight
) {
455 pa
= pa
->GetAncestor(pb
->nHeight
);
456 } else if (pb
->nHeight
> pa
->nHeight
) {
457 pb
= pb
->GetAncestor(pa
->nHeight
);
460 while (pa
!= pb
&& pa
&& pb
) {
465 // Eventually all chain branches meet at the genesis block.
470 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
471 * at most count entries. */
472 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<const CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
476 vBlocks
.reserve(vBlocks
.size() + count
);
477 CNodeState
*state
= State(nodeid
);
478 assert(state
!= NULL
);
480 // Make sure pindexBestKnownBlock is up to date, we'll need it.
481 ProcessBlockAvailability(nodeid
);
483 if (state
->pindexBestKnownBlock
== NULL
|| state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
) {
484 // This peer has nothing interesting.
488 if (state
->pindexLastCommonBlock
== NULL
) {
489 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
490 // Guessing wrong in either direction is not a problem.
491 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
494 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
495 // of its current tip anymore. Go back enough to fix that.
496 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
497 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
500 std::vector
<const CBlockIndex
*> vToFetch
;
501 const CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
502 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
503 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
504 // download that next block if the window were 1 larger.
505 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
506 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
507 NodeId waitingfor
= -1;
508 while (pindexWalk
->nHeight
< nMaxHeight
) {
509 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
510 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
511 // as iterating over ~100 CBlockIndex* entries anyway.
512 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
513 vToFetch
.resize(nToFetch
);
514 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
515 vToFetch
[nToFetch
- 1] = pindexWalk
;
516 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
517 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
520 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
521 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
522 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
523 // already part of our chain (and therefore don't need it even if pruned).
524 BOOST_FOREACH(const CBlockIndex
* pindex
, vToFetch
) {
525 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
526 // We consider the chain that this peer is on invalid.
529 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
530 // We wouldn't download this block or its descendants from this peer.
533 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
534 if (pindex
->nChainTx
)
535 state
->pindexLastCommonBlock
= pindex
;
536 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
537 // The block is not already downloaded, and not yet in flight.
538 if (pindex
->nHeight
> nWindowEnd
) {
539 // We reached the end of the window.
540 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
541 // We aren't able to fetch anything, but we would be if the download window was one larger.
542 nodeStaller
= waitingfor
;
546 vBlocks
.push_back(pindex
);
547 if (vBlocks
.size() == count
) {
550 } else if (waitingfor
== -1) {
551 // This is the first already-in-flight block.
552 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
560 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
562 CNodeState
*state
= State(nodeid
);
565 stats
.nMisbehavior
= state
->nMisbehavior
;
566 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
567 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
568 BOOST_FOREACH(const QueuedBlock
& queue
, state
->vBlocksInFlight
) {
570 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
575 void RegisterNodeSignals(CNodeSignals
& nodeSignals
)
577 nodeSignals
.ProcessMessages
.connect(&ProcessMessages
);
578 nodeSignals
.SendMessages
.connect(&SendMessages
);
579 nodeSignals
.InitializeNode
.connect(&InitializeNode
);
580 nodeSignals
.FinalizeNode
.connect(&FinalizeNode
);
583 void UnregisterNodeSignals(CNodeSignals
& nodeSignals
)
585 nodeSignals
.ProcessMessages
.disconnect(&ProcessMessages
);
586 nodeSignals
.SendMessages
.disconnect(&SendMessages
);
587 nodeSignals
.InitializeNode
.disconnect(&InitializeNode
);
588 nodeSignals
.FinalizeNode
.disconnect(&FinalizeNode
);
591 //////////////////////////////////////////////////////////////////////////////
593 // mapOrphanTransactions
596 void AddToCompactExtraTransactions(const CTransactionRef
& tx
)
598 size_t max_extra_txn
= GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
);
599 if (max_extra_txn
<= 0)
601 if (!vExtraTxnForCompact
.size())
602 vExtraTxnForCompact
.resize(max_extra_txn
);
603 vExtraTxnForCompact
[vExtraTxnForCompactIt
] = std::make_pair(tx
->GetWitnessHash(), tx
);
604 vExtraTxnForCompactIt
= (vExtraTxnForCompactIt
+ 1) % max_extra_txn
;
607 bool AddOrphanTx(const CTransactionRef
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
609 const uint256
& hash
= tx
->GetHash();
610 if (mapOrphanTransactions
.count(hash
))
613 // Ignore big transactions, to avoid a
614 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
615 // large transaction with a missing parent then we assume
616 // it will rebroadcast it later, after the parent transaction(s)
617 // have been mined or received.
618 // 100 orphans, each of which is at most 99,999 bytes big is
619 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
620 unsigned int sz
= GetTransactionWeight(*tx
);
621 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
623 LogPrint(BCLog::MEMPOOL
, "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
627 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
629 BOOST_FOREACH(const CTxIn
& txin
, tx
->vin
) {
630 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
633 AddToCompactExtraTransactions(tx
);
635 LogPrint(BCLog::MEMPOOL
, "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
636 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
640 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
642 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
643 if (it
== mapOrphanTransactions
.end())
645 BOOST_FOREACH(const CTxIn
& txin
, it
->second
.tx
->vin
)
647 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
648 if (itPrev
== mapOrphanTransactionsByPrev
.end())
650 itPrev
->second
.erase(it
);
651 if (itPrev
->second
.empty())
652 mapOrphanTransactionsByPrev
.erase(itPrev
);
654 mapOrphanTransactions
.erase(it
);
658 void EraseOrphansFor(NodeId peer
)
661 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
662 while (iter
!= mapOrphanTransactions
.end())
664 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
665 if (maybeErase
->second
.fromPeer
== peer
)
667 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
670 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx from peer=%d\n", nErased
, peer
);
674 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
676 unsigned int nEvicted
= 0;
677 static int64_t nNextSweep
;
678 int64_t nNow
= GetTime();
679 if (nNextSweep
<= nNow
) {
680 // Sweep out expired orphan pool entries:
682 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
683 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
684 while (iter
!= mapOrphanTransactions
.end())
686 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
687 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
688 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
690 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
693 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
694 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
695 if (nErased
> 0) LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx due to expiration\n", nErased
);
697 while (mapOrphanTransactions
.size() > nMaxOrphans
)
699 // Evict a random orphan:
700 uint256 randomhash
= GetRandHash();
701 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
702 if (it
== mapOrphanTransactions
.end())
703 it
= mapOrphanTransactions
.begin();
704 EraseOrphanTx(it
->first
);
711 void Misbehaving(NodeId pnode
, int howmuch
)
716 CNodeState
*state
= State(pnode
);
720 state
->nMisbehavior
+= howmuch
;
721 int banscore
= GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
722 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
724 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
725 state
->fShouldBan
= true;
727 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
737 //////////////////////////////////////////////////////////////////////////////
739 // blockchain -> download logic notification
742 PeerLogicValidation::PeerLogicValidation(CConnman
* connmanIn
) : connman(connmanIn
) {
743 // Initialize global variables that cannot be constructed at startup.
744 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
747 void PeerLogicValidation::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
* pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
750 std::vector
<uint256
> vOrphanErase
;
752 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
753 const CTransaction
& tx
= *ptx
;
755 // Which orphan pool entries must we evict?
756 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
757 auto itByPrev
= mapOrphanTransactionsByPrev
.find(tx
.vin
[j
].prevout
);
758 if (itByPrev
== mapOrphanTransactionsByPrev
.end()) continue;
759 for (auto mi
= itByPrev
->second
.begin(); mi
!= itByPrev
->second
.end(); ++mi
) {
760 const CTransaction
& orphanTx
= *(*mi
)->second
.tx
;
761 const uint256
& orphanHash
= orphanTx
.GetHash();
762 vOrphanErase
.push_back(orphanHash
);
767 // Erase orphan transactions include or precluded by this block
768 if (vOrphanErase
.size()) {
770 BOOST_FOREACH(uint256
&orphanHash
, vOrphanErase
) {
771 nErased
+= EraseOrphanTx(orphanHash
);
773 LogPrint(BCLog::MEMPOOL
, "Erased %d orphan tx included or conflicted by block\n", nErased
);
777 // All of the following cache a recent block, and are protected by cs_most_recent_block
778 static CCriticalSection cs_most_recent_block
;
779 static std::shared_ptr
<const CBlock
> most_recent_block
;
780 static std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> most_recent_compact_block
;
781 static uint256 most_recent_block_hash
;
782 static bool fWitnessesPresentInMostRecentCompactBlock
;
784 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex
*pindex
, const std::shared_ptr
<const CBlock
>& pblock
) {
785 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> pcmpctblock
= std::make_shared
<const CBlockHeaderAndShortTxIDs
> (*pblock
, true);
786 const CNetMsgMaker
msgMaker(PROTOCOL_VERSION
);
790 static int nHighestFastAnnounce
= 0;
791 if (pindex
->nHeight
<= nHighestFastAnnounce
)
793 nHighestFastAnnounce
= pindex
->nHeight
;
795 bool fWitnessEnabled
= IsWitnessEnabled(pindex
->pprev
, Params().GetConsensus());
796 uint256
hashBlock(pblock
->GetHash());
799 LOCK(cs_most_recent_block
);
800 most_recent_block_hash
= hashBlock
;
801 most_recent_block
= pblock
;
802 most_recent_compact_block
= pcmpctblock
;
803 fWitnessesPresentInMostRecentCompactBlock
= fWitnessEnabled
;
806 connman
->ForEachNode([this, &pcmpctblock
, pindex
, &msgMaker
, fWitnessEnabled
, &hashBlock
](CNode
* pnode
) {
807 // TODO: Avoid the repeated-serialization here
808 if (pnode
->nVersion
< INVALID_CB_NO_BAN_VERSION
|| pnode
->fDisconnect
)
810 ProcessBlockAvailability(pnode
->GetId());
811 CNodeState
&state
= *State(pnode
->GetId());
812 // If the peer has, or we announced to them the previous block already,
813 // but we don't think they have this one, go ahead and announce it
814 if (state
.fPreferHeaderAndIDs
&& (!fWitnessEnabled
|| state
.fWantsCmpctWitness
) &&
815 !PeerHasHeader(&state
, pindex
) && PeerHasHeader(&state
, pindex
->pprev
)) {
817 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
818 hashBlock
.ToString(), pnode
->id
);
819 connman
->PushMessage(pnode
, msgMaker
.Make(NetMsgType::CMPCTBLOCK
, *pcmpctblock
));
820 state
.pindexBestHeaderSent
= pindex
;
825 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex
*pindexNew
, const CBlockIndex
*pindexFork
, bool fInitialDownload
) {
826 const int nNewHeight
= pindexNew
->nHeight
;
827 connman
->SetBestHeight(nNewHeight
);
829 if (!fInitialDownload
) {
830 // Find the hashes of all blocks that weren't previously in the best chain.
831 std::vector
<uint256
> vHashes
;
832 const CBlockIndex
*pindexToAnnounce
= pindexNew
;
833 while (pindexToAnnounce
!= pindexFork
) {
834 vHashes
.push_back(pindexToAnnounce
->GetBlockHash());
835 pindexToAnnounce
= pindexToAnnounce
->pprev
;
836 if (vHashes
.size() == MAX_BLOCKS_TO_ANNOUNCE
) {
837 // Limit announcements in case of a huge reorganization.
838 // Rely on the peer's synchronization mechanism in that case.
842 // Relay inventory, but don't relay old inventory during initial block download.
843 connman
->ForEachNode([nNewHeight
, &vHashes
](CNode
* pnode
) {
844 if (nNewHeight
> (pnode
->nStartingHeight
!= -1 ? pnode
->nStartingHeight
- 2000 : 0)) {
845 BOOST_REVERSE_FOREACH(const uint256
& hash
, vHashes
) {
846 pnode
->PushBlockHash(hash
);
850 connman
->WakeMessageHandler();
853 nTimeBestReceived
= GetTime();
856 void PeerLogicValidation::BlockChecked(const CBlock
& block
, const CValidationState
& state
) {
859 const uint256
hash(block
.GetHash());
860 std::map
<uint256
, std::pair
<NodeId
, bool>>::iterator it
= mapBlockSource
.find(hash
);
863 if (state
.IsInvalid(nDoS
)) {
864 // Don't send reject message with code 0 or an internal reject code.
865 if (it
!= mapBlockSource
.end() && State(it
->second
.first
) && state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) {
866 CBlockReject reject
= {(unsigned char)state
.GetRejectCode(), state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), hash
};
867 State(it
->second
.first
)->rejects
.push_back(reject
);
868 if (nDoS
> 0 && it
->second
.second
)
869 Misbehaving(it
->second
.first
, nDoS
);
873 // 1. The block is valid
874 // 2. We're not in initial block download
875 // 3. This is currently the best block we're aware of. We haven't updated
876 // the tip yet so we have no way to check this directly here. Instead we
877 // just check that there are currently no other blocks in flight.
878 else if (state
.IsValid() &&
879 !IsInitialBlockDownload() &&
880 mapBlocksInFlight
.count(hash
) == mapBlocksInFlight
.size()) {
881 if (it
!= mapBlockSource
.end()) {
882 MaybeSetPeerAsAnnouncingHeaderAndIDs(it
->second
.first
, *connman
);
885 if (it
!= mapBlockSource
.end())
886 mapBlockSource
.erase(it
);
889 //////////////////////////////////////////////////////////////////////////////
895 bool static AlreadyHave(const CInv
& inv
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
902 assert(recentRejects
);
903 if (chainActive
.Tip()->GetBlockHash() != hashRecentRejectsChainTip
)
905 // If the chain tip has changed previously rejected transactions
906 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
907 // or a double-spend. Reset the rejects filter and give those
908 // txs a second chance.
909 hashRecentRejectsChainTip
= chainActive
.Tip()->GetBlockHash();
910 recentRejects
->reset();
913 // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
914 // requesting or processing some txs which have already been included in a block
915 return recentRejects
->contains(inv
.hash
) ||
916 mempool
.exists(inv
.hash
) ||
917 mapOrphanTransactions
.count(inv
.hash
) ||
918 pcoinsTip
->HaveCoinsInCache(inv
.hash
);
921 case MSG_WITNESS_BLOCK
:
922 return mapBlockIndex
.count(inv
.hash
);
924 // Don't know what it is, just say we already got one
928 static void RelayTransaction(const CTransaction
& tx
, CConnman
& connman
)
930 CInv
inv(MSG_TX
, tx
.GetHash());
931 connman
.ForEachNode([&inv
](CNode
* pnode
)
933 pnode
->PushInventory(inv
);
937 static void RelayAddress(const CAddress
& addr
, bool fReachable
, CConnman
& connman
)
939 unsigned int nRelayNodes
= fReachable
? 2 : 1; // limited relaying of addresses outside our network(s)
941 // Relay to a limited number of other nodes
942 // Use deterministic randomness to send to the same nodes for 24 hours
943 // at a time so the addrKnowns of the chosen nodes prevent repeats
944 uint64_t hashAddr
= addr
.GetHash();
945 const CSipHasher hasher
= connman
.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY
).Write(hashAddr
<< 32).Write((GetTime() + hashAddr
) / (24*60*60));
946 FastRandomContext insecure_rand
;
948 std::array
<std::pair
<uint64_t, CNode
*>,2> best
{{{0, nullptr}, {0, nullptr}}};
949 assert(nRelayNodes
<= best
.size());
951 auto sortfunc
= [&best
, &hasher
, nRelayNodes
](CNode
* pnode
) {
952 if (pnode
->nVersion
>= CADDR_TIME_VERSION
) {
953 uint64_t hashKey
= CSipHasher(hasher
).Write(pnode
->id
).Finalize();
954 for (unsigned int i
= 0; i
< nRelayNodes
; i
++) {
955 if (hashKey
> best
[i
].first
) {
956 std::copy(best
.begin() + i
, best
.begin() + nRelayNodes
- 1, best
.begin() + i
+ 1);
957 best
[i
] = std::make_pair(hashKey
, pnode
);
964 auto pushfunc
= [&addr
, &best
, nRelayNodes
, &insecure_rand
] {
965 for (unsigned int i
= 0; i
< nRelayNodes
&& best
[i
].first
!= 0; i
++) {
966 best
[i
].second
->PushAddress(addr
, insecure_rand
);
970 connman
.ForEachNodeThen(std::move(sortfunc
), std::move(pushfunc
));
973 void static ProcessGetData(CNode
* pfrom
, const Consensus::Params
& consensusParams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
975 std::deque
<CInv
>::iterator it
= pfrom
->vRecvGetData
.begin();
976 std::vector
<CInv
> vNotFound
;
977 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
980 while (it
!= pfrom
->vRecvGetData
.end()) {
981 // Don't bother if send buffer is too full to respond anyway
982 if (pfrom
->fPauseSend
)
985 const CInv
&inv
= *it
;
987 if (interruptMsgProc
)
992 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
995 BlockMap::iterator mi
= mapBlockIndex
.find(inv
.hash
);
996 std::shared_ptr
<const CBlock
> a_recent_block
;
997 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> a_recent_compact_block
;
998 bool fWitnessesPresentInARecentCompactBlock
;
1000 LOCK(cs_most_recent_block
);
1001 a_recent_block
= most_recent_block
;
1002 a_recent_compact_block
= most_recent_compact_block
;
1003 fWitnessesPresentInARecentCompactBlock
= fWitnessesPresentInMostRecentCompactBlock
;
1005 if (mi
!= mapBlockIndex
.end())
1007 if (mi
->second
->nChainTx
&& !mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) &&
1008 mi
->second
->IsValid(BLOCK_VALID_TREE
)) {
1009 // If we have the block and all of its parents, but have not yet validated it,
1010 // we might be in the middle of connecting it (ie in the unlock of cs_main
1011 // before ActivateBestChain but after AcceptBlock).
1012 // In this case, we need to run ActivateBestChain prior to checking the relay
1013 // conditions below.
1014 CValidationState dummy
;
1015 ActivateBestChain(dummy
, Params(), a_recent_block
);
1017 if (chainActive
.Contains(mi
->second
)) {
1020 static const int nOneMonth
= 30 * 24 * 60 * 60;
1021 // To prevent fingerprinting attacks, only send blocks outside of the active
1022 // chain if they are valid, and no more than a month older (both in time, and in
1023 // best equivalent proof of work) than the best header chain we know about.
1024 send
= mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) && (pindexBestHeader
!= NULL
) &&
1025 (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() < nOneMonth
) &&
1026 (GetBlockProofEquivalentTime(*pindexBestHeader
, *mi
->second
, *pindexBestHeader
, consensusParams
) < nOneMonth
);
1028 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
1032 // disconnect node in case we have reached the outbound limit for serving historical blocks
1033 // never disconnect whitelisted nodes
1034 static const int nOneWeek
= 7 * 24 * 60 * 60; // assume > 1 week = historical
1035 if (send
&& connman
.OutboundTargetReached(true) && ( ((pindexBestHeader
!= NULL
) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > nOneWeek
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
1037 LogPrint(BCLog::NET
, "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
1040 pfrom
->fDisconnect
= true;
1043 // Pruned nodes may have deleted the block, so check whether
1044 // it's available before trying to send.
1045 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
1047 std::shared_ptr
<const CBlock
> pblock
;
1048 if (a_recent_block
&& a_recent_block
->GetHash() == (*mi
).second
->GetBlockHash()) {
1049 pblock
= a_recent_block
;
1051 // Send block from disk
1052 std::shared_ptr
<CBlock
> pblockRead
= std::make_shared
<CBlock
>();
1053 if (!ReadBlockFromDisk(*pblockRead
, (*mi
).second
, consensusParams
))
1054 assert(!"cannot load block from disk");
1055 pblock
= pblockRead
;
1057 if (inv
.type
== MSG_BLOCK
)
1058 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, *pblock
));
1059 else if (inv
.type
== MSG_WITNESS_BLOCK
)
1060 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::BLOCK
, *pblock
));
1061 else if (inv
.type
== MSG_FILTERED_BLOCK
)
1063 bool sendMerkleBlock
= false;
1064 CMerkleBlock merkleBlock
;
1066 LOCK(pfrom
->cs_filter
);
1067 if (pfrom
->pfilter
) {
1068 sendMerkleBlock
= true;
1069 merkleBlock
= CMerkleBlock(*pblock
, *pfrom
->pfilter
);
1072 if (sendMerkleBlock
) {
1073 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::MERKLEBLOCK
, merkleBlock
));
1074 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1075 // This avoids hurting performance by pointlessly requiring a round-trip
1076 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1077 // they must either disconnect and retry or request the full block.
1078 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1079 // however we MUST always provide at least what the remote peer needs
1080 typedef std::pair
<unsigned int, uint256
> PairType
;
1081 BOOST_FOREACH(PairType
& pair
, merkleBlock
.vMatchedTxn
)
1082 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, *pblock
->vtx
[pair
.first
]));
1087 else if (inv
.type
== MSG_CMPCT_BLOCK
)
1089 // If a peer is asking for old blocks, we're almost guaranteed
1090 // they won't have a useful mempool to match against a compact block,
1091 // and we don't feel like constructing the object for them, so
1092 // instead we respond with the full, non-compact block.
1093 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
1094 int nSendFlags
= fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1095 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
1096 if ((fPeerWantsWitness
|| !fWitnessesPresentInARecentCompactBlock
) && a_recent_compact_block
&& a_recent_compact_block
->header
.GetHash() == mi
->second
->GetBlockHash()) {
1097 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *a_recent_compact_block
));
1099 CBlockHeaderAndShortTxIDs
cmpctblock(*pblock
, fPeerWantsWitness
);
1100 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
1103 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCK
, *pblock
));
1107 // Trigger the peer node to send a getblocks request for the next batch of inventory
1108 if (inv
.hash
== pfrom
->hashContinue
)
1110 // Bypass PushInventory, this must send even if redundant,
1111 // and we want it right after the last block so they don't
1112 // wait for other stuff first.
1113 std::vector
<CInv
> vInv
;
1114 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
1115 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::INV
, vInv
));
1116 pfrom
->hashContinue
.SetNull();
1120 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
1122 // Send stream from relay memory
1124 auto mi
= mapRelay
.find(inv
.hash
);
1125 int nSendFlags
= (inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0);
1126 if (mi
!= mapRelay
.end()) {
1127 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *mi
->second
));
1129 } else if (pfrom
->timeLastMempoolReq
) {
1130 auto txinfo
= mempool
.info(inv
.hash
);
1131 // To protect privacy, do not answer getdata using the mempool when
1132 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1133 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
1134 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *txinfo
.tx
));
1139 vNotFound
.push_back(inv
);
1143 // Track requests for our stuff.
1144 GetMainSignals().Inventory(inv
.hash
);
1146 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1151 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
1153 if (!vNotFound
.empty()) {
1154 // Let the peer know that we didn't find what it asked for, so it doesn't
1155 // have to wait around forever. Currently only SPV clients actually care
1156 // about this message: it's needed when they are recursively walking the
1157 // dependencies of relevant unconfirmed transactions. SPV clients want to
1158 // do that because they want to know about (and store and rebroadcast and
1159 // risk analyze) the dependencies of transactions relevant to them, without
1160 // having to download the entire memory pool.
1161 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::NOTFOUND
, vNotFound
));
1165 uint32_t GetFetchFlags(CNode
* pfrom
, const CBlockIndex
* pprev
, const Consensus::Params
& chainparams
) {
1166 uint32_t nFetchFlags
= 0;
1167 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
1168 nFetchFlags
|= MSG_WITNESS_FLAG
;
1173 inline void static SendBlockTransactions(const CBlock
& block
, const BlockTransactionsRequest
& req
, CNode
* pfrom
, CConnman
& connman
) {
1174 BlockTransactions
resp(req
);
1175 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
1176 if (req
.indexes
[i
] >= block
.vtx
.size()) {
1178 Misbehaving(pfrom
->GetId(), 100);
1179 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->id
);
1182 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
1185 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1186 int nSendFlags
= State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1187 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCKTXN
, resp
));
1190 bool static ProcessMessage(CNode
* pfrom
, const std::string
& strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
1192 LogPrint(BCLog::NET
, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->id
);
1193 if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
1195 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1200 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
1201 (strCommand
== NetMsgType::FILTERLOAD
||
1202 strCommand
== NetMsgType::FILTERADD
))
1204 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
1206 Misbehaving(pfrom
->GetId(), 100);
1209 pfrom
->fDisconnect
= true;
1214 if (strCommand
== NetMsgType::REJECT
)
1216 if (LogAcceptCategory(BCLog::NET
)) {
1218 std::string strMsg
; unsigned char ccode
; std::string strReason
;
1219 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
1221 std::ostringstream ss
;
1222 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
1224 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
1228 ss
<< ": hash " << hash
.ToString();
1230 LogPrint(BCLog::NET
, "Reject %s\n", SanitizeString(ss
.str()));
1231 } catch (const std::ios_base::failure
&) {
1232 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
1233 LogPrint(BCLog::NET
, "Unparseable reject message received\n");
1238 else if (strCommand
== NetMsgType::VERSION
)
1240 // Each connection can only send one version message
1241 if (pfrom
->nVersion
!= 0)
1243 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, std::string("Duplicate version message")));
1245 Misbehaving(pfrom
->GetId(), 1);
1252 uint64_t nNonce
= 1;
1253 uint64_t nServiceInt
;
1254 ServiceFlags nServices
;
1257 std::string strSubVer
;
1258 std::string cleanSubVer
;
1259 int nStartingHeight
= -1;
1262 vRecv
>> nVersion
>> nServiceInt
>> nTime
>> addrMe
;
1263 nSendVersion
= std::min(nVersion
, PROTOCOL_VERSION
);
1264 nServices
= ServiceFlags(nServiceInt
);
1265 if (!pfrom
->fInbound
)
1267 connman
.SetServices(pfrom
->addr
, nServices
);
1269 if (pfrom
->nServicesExpected
& ~nServices
)
1271 LogPrint(BCLog::NET
, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->id
, nServices
, pfrom
->nServicesExpected
);
1272 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
1273 strprintf("Expected to offer services %08x", pfrom
->nServicesExpected
)));
1274 pfrom
->fDisconnect
= true;
1278 if (nVersion
< MIN_PEER_PROTO_VERSION
)
1280 // disconnect from peers older than this proto version
1281 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom
->id
, nVersion
);
1282 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
1283 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
)));
1284 pfrom
->fDisconnect
= true;
1288 if (nVersion
== 10300)
1291 vRecv
>> addrFrom
>> nNonce
;
1292 if (!vRecv
.empty()) {
1293 vRecv
>> LIMITED_STRING(strSubVer
, MAX_SUBVERSION_LENGTH
);
1294 cleanSubVer
= SanitizeString(strSubVer
);
1296 if (!vRecv
.empty()) {
1297 vRecv
>> nStartingHeight
;
1301 // Disconnect if we connected to ourself
1302 if (pfrom
->fInbound
&& !connman
.CheckIncomingNonce(nNonce
))
1304 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
1305 pfrom
->fDisconnect
= true;
1309 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
1314 // Be shy and don't send version until we hear
1315 if (pfrom
->fInbound
)
1316 PushNodeVersion(pfrom
, connman
, GetAdjustedTime());
1318 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERACK
));
1320 pfrom
->nServices
= nServices
;
1321 pfrom
->SetAddrLocal(addrMe
);
1323 LOCK(pfrom
->cs_SubVer
);
1324 pfrom
->strSubVer
= strSubVer
;
1325 pfrom
->cleanSubVer
= cleanSubVer
;
1327 pfrom
->nStartingHeight
= nStartingHeight
;
1328 pfrom
->fClient
= !(nServices
& NODE_NETWORK
);
1330 LOCK(pfrom
->cs_filter
);
1331 pfrom
->fRelayTxes
= fRelay
; // set to true after we get the first filter* message
1335 pfrom
->SetSendVersion(nSendVersion
);
1336 pfrom
->nVersion
= nVersion
;
1338 if((nServices
& NODE_WITNESS
))
1341 State(pfrom
->GetId())->fHaveWitness
= true;
1344 // Potentially mark this peer as a preferred download peer.
1347 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
1350 if (!pfrom
->fInbound
)
1352 // Advertise our address
1353 if (fListen
&& !IsInitialBlockDownload())
1355 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
1356 FastRandomContext insecure_rand
;
1357 if (addr
.IsRoutable())
1359 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1360 pfrom
->PushAddress(addr
, insecure_rand
);
1361 } else if (IsPeerAddrLocalGood(pfrom
)) {
1363 LogPrint(BCLog::NET
, "ProcessMessages: advertising address %s\n", addr
.ToString());
1364 pfrom
->PushAddress(addr
, insecure_rand
);
1368 // Get recent addresses
1369 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
.GetAddressCount() < 1000)
1371 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make(NetMsgType::GETADDR
));
1372 pfrom
->fGetAddr
= true;
1374 connman
.MarkAddressGood(pfrom
->addr
);
1377 std::string remoteAddr
;
1379 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
1381 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1382 cleanSubVer
, pfrom
->nVersion
,
1383 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->id
,
1386 int64_t nTimeOffset
= nTime
- GetTime();
1387 pfrom
->nTimeOffset
= nTimeOffset
;
1388 AddTimeData(pfrom
->addr
, nTimeOffset
);
1390 // If the peer is old enough to have the old alert system, send it the final alert.
1391 if (pfrom
->nVersion
<= 70012) {
1392 CDataStream
finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK
, PROTOCOL_VERSION
);
1393 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make("alert", finalAlert
));
1396 // Feeler connections exist only to verify if address is online.
1397 if (pfrom
->fFeeler
) {
1398 assert(pfrom
->fInbound
== false);
1399 pfrom
->fDisconnect
= true;
1405 else if (pfrom
->nVersion
== 0)
1407 // Must have a version message before anything else
1409 Misbehaving(pfrom
->GetId(), 1);
1413 // At this point, the outgoing message serialization version can't change.
1414 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1416 if (strCommand
== NetMsgType::VERACK
)
1418 pfrom
->SetRecvVersion(std::min(pfrom
->nVersion
.load(), PROTOCOL_VERSION
));
1420 if (!pfrom
->fInbound
) {
1421 // Mark this node as currently connected, so we update its timestamp later.
1423 State(pfrom
->GetId())->fCurrentlyConnected
= true;
1426 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
1427 // Tell our peer we prefer to receive headers rather than inv's
1428 // We send this to non-NODE NETWORK peers as well, because even
1429 // non-NODE NETWORK peers can announce blocks (such as pruning
1431 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDHEADERS
));
1433 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
1434 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1435 // However, we do not request new block announcements using
1436 // cmpctblock messages.
1437 // We send this to non-NODE NETWORK peers as well, because
1438 // they may wish to request compact blocks from us
1439 bool fAnnounceUsingCMPCTBLOCK
= false;
1440 uint64_t nCMPCTBLOCKVersion
= 2;
1441 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1442 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1443 nCMPCTBLOCKVersion
= 1;
1444 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1446 pfrom
->fSuccessfullyConnected
= true;
1449 else if (!pfrom
->fSuccessfullyConnected
)
1451 // Must have a verack message before anything else
1453 Misbehaving(pfrom
->GetId(), 1);
1457 else if (strCommand
== NetMsgType::ADDR
)
1459 std::vector
<CAddress
> vAddr
;
1462 // Don't want addr from older versions unless seeding
1463 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
.GetAddressCount() > 1000)
1465 if (vAddr
.size() > 1000)
1468 Misbehaving(pfrom
->GetId(), 20);
1469 return error("message addr size() = %u", vAddr
.size());
1472 // Store the new addresses
1473 std::vector
<CAddress
> vAddrOk
;
1474 int64_t nNow
= GetAdjustedTime();
1475 int64_t nSince
= nNow
- 10 * 60;
1476 BOOST_FOREACH(CAddress
& addr
, vAddr
)
1478 if (interruptMsgProc
)
1481 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1484 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
1485 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
1486 pfrom
->AddAddressKnown(addr
);
1487 bool fReachable
= IsReachable(addr
);
1488 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
1490 // Relay to a limited number of other nodes
1491 RelayAddress(addr
, fReachable
, connman
);
1493 // Do not store addresses outside our network
1495 vAddrOk
.push_back(addr
);
1497 connman
.AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
1498 if (vAddr
.size() < 1000)
1499 pfrom
->fGetAddr
= false;
1500 if (pfrom
->fOneShot
)
1501 pfrom
->fDisconnect
= true;
1504 else if (strCommand
== NetMsgType::SENDHEADERS
)
1507 State(pfrom
->GetId())->fPreferHeaders
= true;
1510 else if (strCommand
== NetMsgType::SENDCMPCT
)
1512 bool fAnnounceUsingCMPCTBLOCK
= false;
1513 uint64_t nCMPCTBLOCKVersion
= 0;
1514 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
1515 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
1517 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1518 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
1519 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
1520 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
1522 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
1523 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
1524 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
1525 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1526 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
1528 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
1534 else if (strCommand
== NetMsgType::INV
)
1536 std::vector
<CInv
> vInv
;
1538 if (vInv
.size() > MAX_INV_SZ
)
1541 Misbehaving(pfrom
->GetId(), 20);
1542 return error("message inv size() = %u", vInv
.size());
1545 bool fBlocksOnly
= !fRelayTxes
;
1547 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1548 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
1549 fBlocksOnly
= false;
1553 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus());
1555 std::vector
<CInv
> vToFetch
;
1557 for (unsigned int nInv
= 0; nInv
< vInv
.size(); nInv
++)
1559 CInv
&inv
= vInv
[nInv
];
1561 if (interruptMsgProc
)
1564 bool fAlreadyHave
= AlreadyHave(inv
);
1565 LogPrint(BCLog::NET
, "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->id
);
1567 if (inv
.type
== MSG_TX
) {
1568 inv
.type
|= nFetchFlags
;
1571 if (inv
.type
== MSG_BLOCK
) {
1572 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
1573 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
1574 // We used to request the full block here, but since headers-announcements are now the
1575 // primary method of announcement on the network, and since, in the case that a node
1576 // fell back to inv we probably have a reorg which we should get the headers for first,
1577 // we now only provide a getheaders response here. When we receive the headers, we will
1578 // then ask for the blocks we need.
1579 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
));
1580 LogPrint(BCLog::NET
, "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->id
);
1585 pfrom
->AddInventoryKnown(inv
);
1587 LogPrint(BCLog::NET
, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->id
);
1588 } else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload()) {
1593 // Track requests for our stuff
1594 GetMainSignals().Inventory(inv
.hash
);
1597 if (!vToFetch
.empty())
1598 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vToFetch
));
1602 else if (strCommand
== NetMsgType::GETDATA
)
1604 std::vector
<CInv
> vInv
;
1606 if (vInv
.size() > MAX_INV_SZ
)
1609 Misbehaving(pfrom
->GetId(), 20);
1610 return error("message getdata size() = %u", vInv
.size());
1613 LogPrint(BCLog::NET
, "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->id
);
1615 if (vInv
.size() > 0) {
1616 LogPrint(BCLog::NET
, "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->id
);
1619 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
1620 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1624 else if (strCommand
== NetMsgType::GETBLOCKS
)
1626 CBlockLocator locator
;
1628 vRecv
>> locator
>> hashStop
;
1630 // We might have announced the currently-being-connected tip using a
1631 // compact block, which resulted in the peer sending a getblocks
1632 // request, which we would otherwise respond to without the new block.
1633 // To avoid this situation we simply verify that we are on our best
1634 // known chain now. This is super overkill, but we handle it better
1635 // for getheaders requests, and there are no known nodes which support
1636 // compact blocks but still use getblocks to request blocks.
1638 std::shared_ptr
<const CBlock
> a_recent_block
;
1640 LOCK(cs_most_recent_block
);
1641 a_recent_block
= most_recent_block
;
1643 CValidationState dummy
;
1644 ActivateBestChain(dummy
, Params(), a_recent_block
);
1649 // Find the last block the caller has in the main chain
1650 const CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1652 // Send the rest of the chain
1654 pindex
= chainActive
.Next(pindex
);
1656 LogPrint(BCLog::NET
, "getblocks %d to %s limit %d from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), nLimit
, pfrom
->id
);
1657 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1659 if (pindex
->GetBlockHash() == hashStop
)
1661 LogPrint(BCLog::NET
, " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1664 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1665 // for some reasonable time window (1 hour) that block relay might require.
1666 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
1667 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
1669 LogPrint(BCLog::NET
, " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1672 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
1675 // When this block is requested, we'll send an inv that'll
1676 // trigger the peer to getblocks the next batch of inventory.
1677 LogPrint(BCLog::NET
, " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1678 pfrom
->hashContinue
= pindex
->GetBlockHash();
1685 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
1687 BlockTransactionsRequest req
;
1690 std::shared_ptr
<const CBlock
> recent_block
;
1692 LOCK(cs_most_recent_block
);
1693 if (most_recent_block_hash
== req
.blockhash
)
1694 recent_block
= most_recent_block
;
1695 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1698 SendBlockTransactions(*recent_block
, req
, pfrom
, connman
);
1704 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
1705 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
1706 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom
->id
);
1710 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
1711 // If an older block is requested (should never happen in practice,
1712 // but can happen in tests) send a block response instead of a
1713 // blocktxn response. Sending a full block response instead of a
1714 // small blocktxn response is preferable in the case where a peer
1715 // might maliciously send lots of getblocktxn requests to trigger
1716 // expensive disk reads, because it will require the peer to
1717 // actually receive all the data read from disk over the network.
1718 LogPrint(BCLog::NET
, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->id
, MAX_BLOCKTXN_DEPTH
);
1720 inv
.type
= State(pfrom
->GetId())->fWantsCmpctWitness
? MSG_WITNESS_BLOCK
: MSG_BLOCK
;
1721 inv
.hash
= req
.blockhash
;
1722 pfrom
->vRecvGetData
.push_back(inv
);
1723 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1728 bool ret
= ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus());
1731 SendBlockTransactions(block
, req
, pfrom
, connman
);
1735 else if (strCommand
== NetMsgType::GETHEADERS
)
1737 CBlockLocator locator
;
1739 vRecv
>> locator
>> hashStop
;
1742 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
1743 LogPrint(BCLog::NET
, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->id
);
1747 CNodeState
*nodestate
= State(pfrom
->GetId());
1748 const CBlockIndex
* pindex
= NULL
;
1749 if (locator
.IsNull())
1751 // If locator is null, return the hashStop block
1752 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
1753 if (mi
== mapBlockIndex
.end())
1755 pindex
= (*mi
).second
;
1759 // Find the last block the caller has in the main chain
1760 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1762 pindex
= chainActive
.Next(pindex
);
1765 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1766 std::vector
<CBlock
> vHeaders
;
1767 int nLimit
= MAX_HEADERS_RESULTS
;
1768 LogPrint(BCLog::NET
, "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->id
);
1769 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1771 vHeaders
.push_back(pindex
->GetBlockHeader());
1772 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
1775 // pindex can be NULL either if we sent chainActive.Tip() OR
1776 // if our peer has chainActive.Tip() (and thus we are sending an empty
1777 // headers message). In both cases it's safe to update
1778 // pindexBestHeaderSent to be our tip.
1780 // It is important that we simply reset the BestHeaderSent value here,
1781 // and not max(BestHeaderSent, newHeaderSent). We might have announced
1782 // the currently-being-connected tip using a compact block, which
1783 // resulted in the peer sending a headers request, which we respond to
1784 // without the new block. By resetting the BestHeaderSent, we ensure we
1785 // will re-announce the new block via headers (or compact blocks again)
1786 // in the SendMessages logic.
1787 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
1788 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
1792 else if (strCommand
== NetMsgType::TX
)
1794 // Stop processing the transaction early if
1795 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1796 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
1798 LogPrint(BCLog::NET
, "transaction sent in violation of protocol peer=%d\n", pfrom
->id
);
1802 std::deque
<COutPoint
> vWorkQueue
;
1803 std::vector
<uint256
> vEraseQueue
;
1804 CTransactionRef ptx
;
1806 const CTransaction
& tx
= *ptx
;
1808 CInv
inv(MSG_TX
, tx
.GetHash());
1809 pfrom
->AddInventoryKnown(inv
);
1813 bool fMissingInputs
= false;
1814 CValidationState state
;
1816 pfrom
->setAskFor
.erase(inv
.hash
);
1817 mapAlreadyAskedFor
.erase(inv
.hash
);
1819 std::list
<CTransactionRef
> lRemovedTxn
;
1821 if (!AlreadyHave(inv
) && AcceptToMemoryPool(mempool
, state
, ptx
, true, &fMissingInputs
, &lRemovedTxn
)) {
1822 mempool
.check(pcoinsTip
);
1823 RelayTransaction(tx
, connman
);
1824 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
1825 vWorkQueue
.emplace_back(inv
.hash
, i
);
1828 pfrom
->nLastTXTime
= GetTime();
1830 LogPrint(BCLog::MEMPOOL
, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1832 tx
.GetHash().ToString(),
1833 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
1835 // Recursively process any orphan transactions that depended on this one
1836 std::set
<NodeId
> setMisbehaving
;
1837 while (!vWorkQueue
.empty()) {
1838 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
1839 vWorkQueue
.pop_front();
1840 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
1842 for (auto mi
= itByPrev
->second
.begin();
1843 mi
!= itByPrev
->second
.end();
1846 const CTransactionRef
& porphanTx
= (*mi
)->second
.tx
;
1847 const CTransaction
& orphanTx
= *porphanTx
;
1848 const uint256
& orphanHash
= orphanTx
.GetHash();
1849 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
1850 bool fMissingInputs2
= false;
1851 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1852 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1853 // anyone relaying LegitTxX banned)
1854 CValidationState stateDummy
;
1857 if (setMisbehaving
.count(fromPeer
))
1859 if (AcceptToMemoryPool(mempool
, stateDummy
, porphanTx
, true, &fMissingInputs2
, &lRemovedTxn
)) {
1860 LogPrint(BCLog::MEMPOOL
, " accepted orphan tx %s\n", orphanHash
.ToString());
1861 RelayTransaction(orphanTx
, connman
);
1862 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
1863 vWorkQueue
.emplace_back(orphanHash
, i
);
1865 vEraseQueue
.push_back(orphanHash
);
1867 else if (!fMissingInputs2
)
1870 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
1872 // Punish peer that gave us an invalid orphan tx
1873 Misbehaving(fromPeer
, nDos
);
1874 setMisbehaving
.insert(fromPeer
);
1875 LogPrint(BCLog::MEMPOOL
, " invalid orphan tx %s\n", orphanHash
.ToString());
1877 // Has inputs but not accepted to mempool
1878 // Probably non-standard or insufficient fee
1879 LogPrint(BCLog::MEMPOOL
, " removed orphan tx %s\n", orphanHash
.ToString());
1880 vEraseQueue
.push_back(orphanHash
);
1881 if (!orphanTx
.HasWitness() && !stateDummy
.CorruptionPossible()) {
1882 // Do not use rejection cache for witness transactions or
1883 // witness-stripped transactions, as they can have been malleated.
1884 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1885 assert(recentRejects
);
1886 recentRejects
->insert(orphanHash
);
1889 mempool
.check(pcoinsTip
);
1893 BOOST_FOREACH(uint256 hash
, vEraseQueue
)
1894 EraseOrphanTx(hash
);
1896 else if (fMissingInputs
)
1898 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
1899 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1900 if (recentRejects
->contains(txin
.prevout
.hash
)) {
1901 fRejectedParents
= true;
1905 if (!fRejectedParents
) {
1906 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus());
1907 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1908 CInv
_inv(MSG_TX
| nFetchFlags
, txin
.prevout
.hash
);
1909 pfrom
->AddInventoryKnown(_inv
);
1910 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
1912 AddOrphanTx(ptx
, pfrom
->GetId());
1914 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1915 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
1916 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
1918 LogPrint(BCLog::MEMPOOL
, "mapOrphan overflow, removed %u tx\n", nEvicted
);
1921 LogPrint(BCLog::MEMPOOL
, "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
1922 // We will continue to reject this tx since it has rejected
1923 // parents so avoid re-requesting it from other peers.
1924 recentRejects
->insert(tx
.GetHash());
1927 if (!tx
.HasWitness() && !state
.CorruptionPossible()) {
1928 // Do not use rejection cache for witness transactions or
1929 // witness-stripped transactions, as they can have been malleated.
1930 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1931 assert(recentRejects
);
1932 recentRejects
->insert(tx
.GetHash());
1933 if (RecursiveDynamicUsage(*ptx
) < 100000) {
1934 AddToCompactExtraTransactions(ptx
);
1936 } else if (tx
.HasWitness() && RecursiveDynamicUsage(*ptx
) < 100000) {
1937 AddToCompactExtraTransactions(ptx
);
1940 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
1941 // Always relay transactions received from whitelisted peers, even
1942 // if they were already in the mempool or rejected from it due
1943 // to policy, allowing the node to function as a gateway for
1944 // nodes hidden behind it.
1946 // Never relay transactions that we would assign a non-zero DoS
1947 // score for, as we expect peers to do the same with us in that
1950 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
1951 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->id
);
1952 RelayTransaction(tx
, connman
);
1954 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->id
, FormatStateMessage(state
));
1959 for (const CTransactionRef
& removedTx
: lRemovedTxn
)
1960 AddToCompactExtraTransactions(removedTx
);
1963 if (state
.IsInvalid(nDoS
))
1965 LogPrint(BCLog::MEMPOOLREJ
, "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
1967 FormatStateMessage(state
));
1968 if (state
.GetRejectCode() > 0 && state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
1969 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
1970 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
));
1972 Misbehaving(pfrom
->GetId(), nDoS
);
1978 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
1980 CBlockHeaderAndShortTxIDs cmpctblock
;
1981 vRecv
>> cmpctblock
;
1986 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
1987 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1988 if (!IsInitialBlockDownload())
1989 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
1994 const CBlockIndex
*pindex
= NULL
;
1995 CValidationState state
;
1996 if (!ProcessNewBlockHeaders({cmpctblock
.header
}, state
, chainparams
, &pindex
)) {
1998 if (state
.IsInvalid(nDoS
)) {
2001 Misbehaving(pfrom
->GetId(), nDoS
);
2003 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->id
);
2008 // When we succeed in decoding a block's txids from a cmpctblock
2009 // message we typically jump to the BLOCKTXN handling code, with a
2010 // dummy (empty) BLOCKTXN message, to re-use the logic there in
2011 // completing processing of the putative block (without cs_main).
2012 bool fProcessBLOCKTXN
= false;
2013 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2015 // If we end up treating this as a plain headers message, call that as well
2017 bool fRevertToHeaderProcessing
= false;
2018 CDataStream
vHeadersMsg(SER_NETWORK
, PROTOCOL_VERSION
);
2020 // Keep a CBlock for "optimistic" compactblock reconstructions (see
2022 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2023 bool fBlockReconstructed
= false;
2027 // If AcceptBlockHeader returned true, it set pindex
2029 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
2031 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
2032 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
2034 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
2037 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
2038 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
2039 if (fAlreadyInFlight
) {
2040 // We requested this block for some reason, but our mempool will probably be useless
2041 // so we just grab the block via normal getdata
2042 std::vector
<CInv
> vInv(1);
2043 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
2044 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2049 // If we're not close to tip yet, give up and let parallel block fetch work its magic
2050 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
2053 CNodeState
*nodestate
= State(pfrom
->GetId());
2055 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
2056 // Don't bother trying to process compact blocks from v1 peers
2057 // after segwit activates.
2061 // We want to be a bit conservative just to be extra careful about DoS
2062 // possibilities in compact block processing...
2063 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
2064 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
2065 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
2066 std::list
<QueuedBlock
>::iterator
* queuedBlockIt
= NULL
;
2067 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
, &queuedBlockIt
)) {
2068 if (!(*queuedBlockIt
)->partialBlock
)
2069 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
2071 // The block was already in flight using compact blocks from the same peer
2072 LogPrint(BCLog::NET
, "Peer sent us compact block we were already syncing!\n");
2077 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
2078 ReadStatus status
= partialBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2079 if (status
== READ_STATUS_INVALID
) {
2080 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
2081 Misbehaving(pfrom
->GetId(), 100);
2082 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->id
);
2084 } else if (status
== READ_STATUS_FAILED
) {
2085 // Duplicate txindexes, the block is now in-flight, so just request it
2086 std::vector
<CInv
> vInv(1);
2087 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
2088 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2092 BlockTransactionsRequest req
;
2093 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
2094 if (!partialBlock
.IsTxAvailable(i
))
2095 req
.indexes
.push_back(i
);
2097 if (req
.indexes
.empty()) {
2098 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2099 BlockTransactions txn
;
2100 txn
.blockhash
= cmpctblock
.header
.GetHash();
2102 fProcessBLOCKTXN
= true;
2104 req
.blockhash
= pindex
->GetBlockHash();
2105 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETBLOCKTXN
, req
));
2108 // This block is either already in flight from a different
2109 // peer, or this peer has too many blocks outstanding to
2111 // Optimistically try to reconstruct anyway since we might be
2112 // able to without any round trips.
2113 PartiallyDownloadedBlock
tempBlock(&mempool
);
2114 ReadStatus status
= tempBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2115 if (status
!= READ_STATUS_OK
) {
2116 // TODO: don't ignore failures
2119 std::vector
<CTransactionRef
> dummy
;
2120 status
= tempBlock
.FillBlock(*pblock
, dummy
);
2121 if (status
== READ_STATUS_OK
) {
2122 fBlockReconstructed
= true;
2126 if (fAlreadyInFlight
) {
2127 // We requested this block, but its far into the future, so our
2128 // mempool will probably be useless - request the block normally
2129 std::vector
<CInv
> vInv(1);
2130 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
2131 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2134 // If this was an announce-cmpctblock, we want the same treatment as a header message
2135 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
2136 std::vector
<CBlock
> headers
;
2137 headers
.push_back(cmpctblock
.header
);
2138 vHeadersMsg
<< headers
;
2139 fRevertToHeaderProcessing
= true;
2144 if (fProcessBLOCKTXN
)
2145 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2147 if (fRevertToHeaderProcessing
)
2148 return ProcessMessage(pfrom
, NetMsgType::HEADERS
, vHeadersMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2150 if (fBlockReconstructed
) {
2151 // If we got here, we were able to optimistically reconstruct a
2152 // block that is in flight from some other peer.
2155 mapBlockSource
.emplace(pblock
->GetHash(), std::make_pair(pfrom
->GetId(), false));
2157 bool fNewBlock
= false;
2158 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2160 pfrom
->nLastBlockTime
= GetTime();
2162 LOCK(cs_main
); // hold cs_main for CBlockIndex::IsValid()
2163 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
)) {
2164 // Clear download state for this block, which is in
2165 // process from some other peer. We do this after calling
2166 // ProcessNewBlock so that a malleated cmpctblock announcement
2167 // can't be used to interfere with block relay.
2168 MarkBlockAsReceived(pblock
->GetHash());
2174 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2176 BlockTransactions resp
;
2179 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2180 bool fBlockRead
= false;
2184 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
2185 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
2186 it
->second
.first
!= pfrom
->GetId()) {
2187 LogPrint(BCLog::NET
, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->id
);
2191 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
2192 ReadStatus status
= partialBlock
.FillBlock(*pblock
, resp
.txn
);
2193 if (status
== READ_STATUS_INVALID
) {
2194 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
2195 Misbehaving(pfrom
->GetId(), 100);
2196 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->id
);
2198 } else if (status
== READ_STATUS_FAILED
) {
2199 // Might have collided, fall back to getdata now :(
2200 std::vector
<CInv
> invs
;
2201 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus()), resp
.blockhash
));
2202 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, invs
));
2204 // Block is either okay, or possibly we received
2205 // READ_STATUS_CHECKBLOCK_FAILED.
2206 // Note that CheckBlock can only fail for one of a few reasons:
2207 // 1. bad-proof-of-work (impossible here, because we've already
2208 // accepted the header)
2209 // 2. merkleroot doesn't match the transactions given (already
2210 // caught in FillBlock with READ_STATUS_FAILED, so
2212 // 3. the block is otherwise invalid (eg invalid coinbase,
2213 // block is too big, too many legacy sigops, etc).
2214 // So if CheckBlock failed, #3 is the only possibility.
2215 // Under BIP 152, we don't DoS-ban unless proof of work is
2216 // invalid (we don't require all the stateless checks to have
2217 // been run). This is handled below, so just treat this as
2218 // though the block was successfully read, and rely on the
2219 // handling in ProcessNewBlock to ensure the block index is
2220 // updated, reject messages go out, etc.
2221 MarkBlockAsReceived(resp
.blockhash
); // it is now an empty pointer
2223 // mapBlockSource is only used for sending reject messages and DoS scores,
2224 // so the race between here and cs_main in ProcessNewBlock is fine.
2225 // BIP 152 permits peers to relay compact blocks after validating
2226 // the header only; we should not punish peers if the block turns
2227 // out to be invalid.
2228 mapBlockSource
.emplace(resp
.blockhash
, std::make_pair(pfrom
->GetId(), false));
2230 } // Don't hold cs_main when we call into ProcessNewBlock
2232 bool fNewBlock
= false;
2233 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2234 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2235 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2237 pfrom
->nLastBlockTime
= GetTime();
2242 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
2244 std::vector
<CBlockHeader
> headers
;
2246 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2247 unsigned int nCount
= ReadCompactSize(vRecv
);
2248 if (nCount
> MAX_HEADERS_RESULTS
) {
2250 Misbehaving(pfrom
->GetId(), 20);
2251 return error("headers message size = %u", nCount
);
2253 headers
.resize(nCount
);
2254 for (unsigned int n
= 0; n
< nCount
; n
++) {
2255 vRecv
>> headers
[n
];
2256 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
2260 // Nothing interesting. Stop asking this peers for more headers.
2264 const CBlockIndex
*pindexLast
= NULL
;
2267 CNodeState
*nodestate
= State(pfrom
->GetId());
2269 // If this looks like it could be a block announcement (nCount <
2270 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2272 // - Send a getheaders message in response to try to connect the chain.
2273 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2274 // don't connect before giving DoS points
2275 // - Once a headers message is received that is valid and does connect,
2276 // nUnconnectingHeaders gets reset back to 0.
2277 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
2278 nodestate
->nUnconnectingHeaders
++;
2279 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
2280 LogPrint(BCLog::NET
, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2281 headers
[0].GetHash().ToString(),
2282 headers
[0].hashPrevBlock
.ToString(),
2283 pindexBestHeader
->nHeight
,
2284 pfrom
->id
, nodestate
->nUnconnectingHeaders
);
2285 // Set hashLastUnknownBlock for this peer, so that if we
2286 // eventually get the headers - even from a different peer -
2287 // we can use this peer to download.
2288 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
2290 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
2291 Misbehaving(pfrom
->GetId(), 20);
2296 uint256 hashLastBlock
;
2297 for (const CBlockHeader
& header
: headers
) {
2298 if (!hashLastBlock
.IsNull() && header
.hashPrevBlock
!= hashLastBlock
) {
2299 Misbehaving(pfrom
->GetId(), 20);
2300 return error("non-continuous headers sequence");
2302 hashLastBlock
= header
.GetHash();
2306 CValidationState state
;
2307 if (!ProcessNewBlockHeaders(headers
, state
, chainparams
, &pindexLast
)) {
2309 if (state
.IsInvalid(nDoS
)) {
2312 Misbehaving(pfrom
->GetId(), nDoS
);
2314 return error("invalid header received");
2320 CNodeState
*nodestate
= State(pfrom
->GetId());
2321 if (nodestate
->nUnconnectingHeaders
> 0) {
2322 LogPrint(BCLog::NET
, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->id
, nodestate
->nUnconnectingHeaders
);
2324 nodestate
->nUnconnectingHeaders
= 0;
2327 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
2329 if (nCount
== MAX_HEADERS_RESULTS
) {
2330 // Headers message had its maximum size; the peer may have more headers.
2331 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2332 // from there instead.
2333 LogPrint(BCLog::NET
, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->id
, pfrom
->nStartingHeight
);
2334 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256()));
2337 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
2338 // If this set of headers is valid and ends in a block with at least as
2339 // much work as our tip, download as much as possible.
2340 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
2341 std::vector
<const CBlockIndex
*> vToFetch
;
2342 const CBlockIndex
*pindexWalk
= pindexLast
;
2343 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2344 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2345 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
2346 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
2347 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
2348 // We don't have this block, and it's not yet in flight.
2349 vToFetch
.push_back(pindexWalk
);
2351 pindexWalk
= pindexWalk
->pprev
;
2353 // If pindexWalk still isn't on our main chain, we're looking at a
2354 // very large reorg at a time we think we're close to caught up to
2355 // the main chain -- this shouldn't really happen. Bail out on the
2356 // direct fetch and rely on parallel download instead.
2357 if (!chainActive
.Contains(pindexWalk
)) {
2358 LogPrint(BCLog::NET
, "Large reorg, won't direct fetch to %s (%d)\n",
2359 pindexLast
->GetBlockHash().ToString(),
2360 pindexLast
->nHeight
);
2362 std::vector
<CInv
> vGetData
;
2363 // Download as much as possible, from earliest to latest.
2364 BOOST_REVERSE_FOREACH(const CBlockIndex
*pindex
, vToFetch
) {
2365 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2366 // Can't download any more from this peer
2369 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus());
2370 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
2371 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
);
2372 LogPrint(BCLog::NET
, "Requesting block %s from peer=%d\n",
2373 pindex
->GetBlockHash().ToString(), pfrom
->id
);
2375 if (vGetData
.size() > 1) {
2376 LogPrint(BCLog::NET
, "Downloading blocks toward %s (%d) via headers direct fetch\n",
2377 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
2379 if (vGetData
.size() > 0) {
2380 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
2381 // In any case, we want to download using a compact block, not a regular one
2382 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
2384 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
2391 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2393 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2396 LogPrint(BCLog::NET
, "received block %s peer=%d\n", pblock
->GetHash().ToString(), pfrom
->id
);
2398 // Process all blocks from whitelisted peers, even if not requested,
2399 // unless we're still syncing with the network.
2400 // Such an unrequested block may still be processed, subject to the
2401 // conditions in AcceptBlock().
2402 bool forceProcessing
= pfrom
->fWhitelisted
&& !IsInitialBlockDownload();
2403 const uint256
hash(pblock
->GetHash());
2406 // Also always process if we requested the block explicitly, as we may
2407 // need it even though it is not a candidate for a new best tip.
2408 forceProcessing
|= MarkBlockAsReceived(hash
);
2409 // mapBlockSource is only used for sending reject messages and DoS scores,
2410 // so the race between here and cs_main in ProcessNewBlock is fine.
2411 mapBlockSource
.emplace(hash
, std::make_pair(pfrom
->GetId(), true));
2413 bool fNewBlock
= false;
2414 ProcessNewBlock(chainparams
, pblock
, forceProcessing
, &fNewBlock
);
2416 pfrom
->nLastBlockTime
= GetTime();
2420 else if (strCommand
== NetMsgType::GETADDR
)
2422 // This asymmetric behavior for inbound and outbound connections was introduced
2423 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2424 // to users' AddrMan and later request them by sending getaddr messages.
2425 // Making nodes which are behind NAT and can only make outgoing connections ignore
2426 // the getaddr message mitigates the attack.
2427 if (!pfrom
->fInbound
) {
2428 LogPrint(BCLog::NET
, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->id
);
2432 // Only send one GetAddr response per connection to reduce resource waste
2433 // and discourage addr stamping of INV announcements.
2434 if (pfrom
->fSentAddr
) {
2435 LogPrint(BCLog::NET
, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->id
);
2438 pfrom
->fSentAddr
= true;
2440 pfrom
->vAddrToSend
.clear();
2441 std::vector
<CAddress
> vAddr
= connman
.GetAddresses();
2442 FastRandomContext insecure_rand
;
2443 BOOST_FOREACH(const CAddress
&addr
, vAddr
)
2444 pfrom
->PushAddress(addr
, insecure_rand
);
2448 else if (strCommand
== NetMsgType::MEMPOOL
)
2450 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
2452 LogPrint(BCLog::NET
, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
2453 pfrom
->fDisconnect
= true;
2457 if (connman
.OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
2459 LogPrint(BCLog::NET
, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
2460 pfrom
->fDisconnect
= true;
2464 LOCK(pfrom
->cs_inventory
);
2465 pfrom
->fSendMempool
= true;
2469 else if (strCommand
== NetMsgType::PING
)
2471 if (pfrom
->nVersion
> BIP0031_VERSION
)
2475 // Echo the message back with the nonce. This allows for two useful features:
2477 // 1) A remote node can quickly check if the connection is operational
2478 // 2) Remote nodes can measure the latency of the network thread. If this node
2479 // is overloaded it won't respond to pings quickly and the remote node can
2480 // avoid sending us more work, like chain download requests.
2482 // The nonce stops the remote getting confused between different pings: without
2483 // it, if the remote node sends a ping once per second and this node takes 5
2484 // seconds to respond to each, the 5th ping the remote sends would appear to
2485 // return very quickly.
2486 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::PONG
, nonce
));
2491 else if (strCommand
== NetMsgType::PONG
)
2493 int64_t pingUsecEnd
= nTimeReceived
;
2495 size_t nAvail
= vRecv
.in_avail();
2496 bool bPingFinished
= false;
2497 std::string sProblem
;
2499 if (nAvail
>= sizeof(nonce
)) {
2502 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2503 if (pfrom
->nPingNonceSent
!= 0) {
2504 if (nonce
== pfrom
->nPingNonceSent
) {
2505 // Matching pong received, this ping is no longer outstanding
2506 bPingFinished
= true;
2507 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
2508 if (pingUsecTime
> 0) {
2509 // Successful ping time measurement, replace previous
2510 pfrom
->nPingUsecTime
= pingUsecTime
;
2511 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
.load(), pingUsecTime
);
2513 // This should never happen
2514 sProblem
= "Timing mishap";
2517 // Nonce mismatches are normal when pings are overlapping
2518 sProblem
= "Nonce mismatch";
2520 // This is most likely a bug in another implementation somewhere; cancel this ping
2521 bPingFinished
= true;
2522 sProblem
= "Nonce zero";
2526 sProblem
= "Unsolicited pong without ping";
2529 // This is most likely a bug in another implementation somewhere; cancel this ping
2530 bPingFinished
= true;
2531 sProblem
= "Short payload";
2534 if (!(sProblem
.empty())) {
2535 LogPrint(BCLog::NET
, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2538 pfrom
->nPingNonceSent
,
2542 if (bPingFinished
) {
2543 pfrom
->nPingNonceSent
= 0;
2548 else if (strCommand
== NetMsgType::FILTERLOAD
)
2550 CBloomFilter filter
;
2553 if (!filter
.IsWithinSizeConstraints())
2555 // There is no excuse for sending a too-large filter
2557 Misbehaving(pfrom
->GetId(), 100);
2561 LOCK(pfrom
->cs_filter
);
2562 delete pfrom
->pfilter
;
2563 pfrom
->pfilter
= new CBloomFilter(filter
);
2564 pfrom
->pfilter
->UpdateEmptyFull();
2565 pfrom
->fRelayTxes
= true;
2570 else if (strCommand
== NetMsgType::FILTERADD
)
2572 std::vector
<unsigned char> vData
;
2575 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2576 // and thus, the maximum size any matched object can have) in a filteradd message
2578 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
2581 LOCK(pfrom
->cs_filter
);
2582 if (pfrom
->pfilter
) {
2583 pfrom
->pfilter
->insert(vData
);
2590 Misbehaving(pfrom
->GetId(), 100);
2595 else if (strCommand
== NetMsgType::FILTERCLEAR
)
2597 LOCK(pfrom
->cs_filter
);
2598 if (pfrom
->GetLocalServices() & NODE_BLOOM
) {
2599 delete pfrom
->pfilter
;
2600 pfrom
->pfilter
= new CBloomFilter();
2602 pfrom
->fRelayTxes
= true;
2605 else if (strCommand
== NetMsgType::FEEFILTER
) {
2606 CAmount newFeeFilter
= 0;
2607 vRecv
>> newFeeFilter
;
2608 if (MoneyRange(newFeeFilter
)) {
2610 LOCK(pfrom
->cs_feeFilter
);
2611 pfrom
->minFeeFilter
= newFeeFilter
;
2613 LogPrint(BCLog::NET
, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->id
);
2617 else if (strCommand
== NetMsgType::NOTFOUND
) {
2618 // We do not care about the NOTFOUND message, but logging an Unknown Command
2619 // message would be undesirable as we transmit it ourselves.
2623 // Ignore unknown commands for extensibility
2624 LogPrint(BCLog::NET
, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->id
);
2632 static bool SendRejectsAndCheckIfBanned(CNode
* pnode
, CConnman
& connman
)
2634 AssertLockHeld(cs_main
);
2635 CNodeState
&state
= *State(pnode
->GetId());
2637 BOOST_FOREACH(const CBlockReject
& reject
, state
.rejects
) {
2638 connman
.PushMessage(pnode
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, (std::string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
));
2640 state
.rejects
.clear();
2642 if (state
.fShouldBan
) {
2643 state
.fShouldBan
= false;
2644 if (pnode
->fWhitelisted
)
2645 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode
->addr
.ToString());
2646 else if (pnode
->fAddnode
)
2647 LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode
->addr
.ToString());
2649 pnode
->fDisconnect
= true;
2650 if (pnode
->addr
.IsLocal())
2651 LogPrintf("Warning: not banning local peer %s!\n", pnode
->addr
.ToString());
2654 connman
.Ban(pnode
->addr
, BanReasonNodeMisbehaving
);
2662 bool ProcessMessages(CNode
* pfrom
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2664 const CChainParams
& chainparams
= Params();
2667 // (4) message start
2673 bool fMoreWork
= false;
2675 if (!pfrom
->vRecvGetData
.empty())
2676 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2678 if (pfrom
->fDisconnect
)
2681 // this maintains the order of responses
2682 if (!pfrom
->vRecvGetData
.empty()) return true;
2684 // Don't bother if send buffer is too full to respond anyway
2685 if (pfrom
->fPauseSend
)
2688 std::list
<CNetMessage
> msgs
;
2690 LOCK(pfrom
->cs_vProcessMsg
);
2691 if (pfrom
->vProcessMsg
.empty())
2693 // Just take one message
2694 msgs
.splice(msgs
.begin(), pfrom
->vProcessMsg
, pfrom
->vProcessMsg
.begin());
2695 pfrom
->nProcessQueueSize
-= msgs
.front().vRecv
.size() + CMessageHeader::HEADER_SIZE
;
2696 pfrom
->fPauseRecv
= pfrom
->nProcessQueueSize
> connman
.GetReceiveFloodSize();
2697 fMoreWork
= !pfrom
->vProcessMsg
.empty();
2699 CNetMessage
& msg(msgs
.front());
2701 msg
.SetVersion(pfrom
->GetRecvVersion());
2702 // Scan for message start
2703 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
2704 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->id
);
2705 pfrom
->fDisconnect
= true;
2710 CMessageHeader
& hdr
= msg
.hdr
;
2711 if (!hdr
.IsValid(chainparams
.MessageStart()))
2713 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->id
);
2716 std::string strCommand
= hdr
.GetCommand();
2719 unsigned int nMessageSize
= hdr
.nMessageSize
;
2722 CDataStream
& vRecv
= msg
.vRecv
;
2723 const uint256
& hash
= msg
.GetMessageHash();
2724 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
2726 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
2727 SanitizeString(strCommand
), nMessageSize
,
2728 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
2729 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
2737 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
, interruptMsgProc
);
2738 if (interruptMsgProc
)
2740 if (!pfrom
->vRecvGetData
.empty())
2743 catch (const std::ios_base::failure
& e
)
2745 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, std::string("error parsing message")));
2746 if (strstr(e
.what(), "end of data"))
2748 // Allow exceptions from under-length message on vRecv
2749 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());
2751 else if (strstr(e
.what(), "size too large"))
2753 // Allow exceptions from over-long size
2754 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2756 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
2758 // Allow exceptions from non-canonical encoding
2759 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2763 PrintExceptionContinue(&e
, "ProcessMessages()");
2766 catch (const std::exception
& e
) {
2767 PrintExceptionContinue(&e
, "ProcessMessages()");
2769 PrintExceptionContinue(NULL
, "ProcessMessages()");
2773 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->id
);
2777 SendRejectsAndCheckIfBanned(pfrom
, connman
);
2782 class CompareInvMempoolOrder
2786 CompareInvMempoolOrder(CTxMemPool
*_mempool
)
2791 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
2793 /* As std::make_heap produces a max-heap, we want the entries with the
2794 * fewest ancestors/highest fee to sort later. */
2795 return mp
->CompareDepthAndScore(*b
, *a
);
2799 bool SendMessages(CNode
* pto
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2801 const Consensus::Params
& consensusParams
= Params().GetConsensus();
2803 // Don't send anything until the version handshake is complete
2804 if (!pto
->fSuccessfullyConnected
|| pto
->fDisconnect
)
2807 // If we get here, the outgoing message serialization version is set and can't change.
2808 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
2813 bool pingSend
= false;
2814 if (pto
->fPingQueued
) {
2815 // RPC ping request by user
2818 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
2819 // Ping automatically sent as a latency probe & keepalive.
2824 while (nonce
== 0) {
2825 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
2827 pto
->fPingQueued
= false;
2828 pto
->nPingUsecStart
= GetTimeMicros();
2829 if (pto
->nVersion
> BIP0031_VERSION
) {
2830 pto
->nPingNonceSent
= nonce
;
2831 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
, nonce
));
2833 // Peer is too old to support ping command with nonce, pong will never arrive.
2834 pto
->nPingNonceSent
= 0;
2835 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
));
2839 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2843 if (SendRejectsAndCheckIfBanned(pto
, connman
))
2845 CNodeState
&state
= *State(pto
->GetId());
2847 // Address refresh broadcast
2848 int64_t nNow
= GetTimeMicros();
2849 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
2850 AdvertiseLocal(pto
);
2851 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
2857 if (pto
->nNextAddrSend
< nNow
) {
2858 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
2859 std::vector
<CAddress
> vAddr
;
2860 vAddr
.reserve(pto
->vAddrToSend
.size());
2861 BOOST_FOREACH(const CAddress
& addr
, pto
->vAddrToSend
)
2863 if (!pto
->addrKnown
.contains(addr
.GetKey()))
2865 pto
->addrKnown
.insert(addr
.GetKey());
2866 vAddr
.push_back(addr
);
2867 // receiver rejects addr messages larger than 1000
2868 if (vAddr
.size() >= 1000)
2870 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2875 pto
->vAddrToSend
.clear();
2877 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2878 // we only send the big addr message once
2879 if (pto
->vAddrToSend
.capacity() > 40)
2880 pto
->vAddrToSend
.shrink_to_fit();
2884 if (pindexBestHeader
== NULL
)
2885 pindexBestHeader
= chainActive
.Tip();
2886 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.
2887 if (!state
.fSyncStarted
&& !pto
->fClient
&& !fImporting
&& !fReindex
) {
2888 // Only actively request headers from a single peer, unless we're close to today.
2889 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2890 state
.fSyncStarted
= true;
2892 const CBlockIndex
*pindexStart
= pindexBestHeader
;
2893 /* If possible, start at the block preceding the currently
2894 best known header. This ensures that we always get a
2895 non-empty list of headers back as long as the peer
2896 is up-to-date. With a non-empty response, we can initialise
2897 the peer's known best block. This wouldn't be possible
2898 if we requested starting at pindexBestHeader and
2899 got back an empty response. */
2900 if (pindexStart
->pprev
)
2901 pindexStart
= pindexStart
->pprev
;
2902 LogPrint(BCLog::NET
, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->id
, pto
->nStartingHeight
);
2903 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256()));
2907 // Resend wallet transactions that haven't gotten in a block yet
2908 // Except during reindex, importing and IBD, when old wallet
2909 // transactions become unconfirmed and spams other nodes.
2910 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
2912 GetMainSignals().Broadcast(nTimeBestReceived
, &connman
);
2916 // Try sending block announcements via headers
2919 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2920 // list of block hashes we're relaying, and our peer wants
2921 // headers announcements, then find the first header
2922 // not yet known to our peer but would connect, and send.
2923 // If no header would connect, or if we have too many
2924 // blocks, or if the peer doesn't want headers, just
2925 // add all to the inv queue.
2926 LOCK(pto
->cs_inventory
);
2927 std::vector
<CBlock
> vHeaders
;
2928 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
2929 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
2930 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
2931 const CBlockIndex
*pBestIndex
= NULL
; // last header queued for delivery
2932 ProcessBlockAvailability(pto
->id
); // ensure pindexBestKnownBlock is up-to-date
2934 if (!fRevertToInv
) {
2935 bool fFoundStartingHeader
= false;
2936 // Try to find first header that our peer doesn't have, and
2937 // then send all headers past that one. If we come across any
2938 // headers that aren't on chainActive, give up.
2939 BOOST_FOREACH(const uint256
&hash
, pto
->vBlockHashesToAnnounce
) {
2940 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
2941 assert(mi
!= mapBlockIndex
.end());
2942 const CBlockIndex
*pindex
= mi
->second
;
2943 if (chainActive
[pindex
->nHeight
] != pindex
) {
2944 // Bail out if we reorged away from this block
2945 fRevertToInv
= true;
2948 if (pBestIndex
!= NULL
&& pindex
->pprev
!= pBestIndex
) {
2949 // This means that the list of blocks to announce don't
2950 // connect to each other.
2951 // This shouldn't really be possible to hit during
2952 // regular operation (because reorgs should take us to
2953 // a chain that has some block not on the prior chain,
2954 // which should be caught by the prior check), but one
2955 // way this could happen is by using invalidateblock /
2956 // reconsiderblock repeatedly on the tip, causing it to
2957 // be added multiple times to vBlockHashesToAnnounce.
2958 // Robustly deal with this rare situation by reverting
2960 fRevertToInv
= true;
2963 pBestIndex
= pindex
;
2964 if (fFoundStartingHeader
) {
2965 // add this to the headers message
2966 vHeaders
.push_back(pindex
->GetBlockHeader());
2967 } else if (PeerHasHeader(&state
, pindex
)) {
2968 continue; // keep looking for the first new block
2969 } else if (pindex
->pprev
== NULL
|| PeerHasHeader(&state
, pindex
->pprev
)) {
2970 // Peer doesn't have this header but they do have the prior one.
2971 // Start sending headers.
2972 fFoundStartingHeader
= true;
2973 vHeaders
.push_back(pindex
->GetBlockHeader());
2975 // Peer doesn't have this header or the prior one -- nothing will
2976 // connect, so bail out.
2977 fRevertToInv
= true;
2982 if (!fRevertToInv
&& !vHeaders
.empty()) {
2983 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
2984 // We only send up to 1 block as header-and-ids, as otherwise
2985 // probably means we're doing an initial-ish-sync or they're slow
2986 LogPrint(BCLog::NET
, "%s sending header-and-ids %s to peer=%d\n", __func__
,
2987 vHeaders
.front().GetHash().ToString(), pto
->id
);
2989 int nSendFlags
= state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
2991 bool fGotBlockFromCache
= false;
2993 LOCK(cs_most_recent_block
);
2994 if (most_recent_block_hash
== pBestIndex
->GetBlockHash()) {
2995 if (state
.fWantsCmpctWitness
|| !fWitnessesPresentInMostRecentCompactBlock
)
2996 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *most_recent_compact_block
));
2998 CBlockHeaderAndShortTxIDs
cmpctblock(*most_recent_block
, state
.fWantsCmpctWitness
);
2999 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3001 fGotBlockFromCache
= true;
3004 if (!fGotBlockFromCache
) {
3006 bool ret
= ReadBlockFromDisk(block
, pBestIndex
, consensusParams
);
3008 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
3009 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
3011 state
.pindexBestHeaderSent
= pBestIndex
;
3012 } else if (state
.fPreferHeaders
) {
3013 if (vHeaders
.size() > 1) {
3014 LogPrint(BCLog::NET
, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
3016 vHeaders
.front().GetHash().ToString(),
3017 vHeaders
.back().GetHash().ToString(), pto
->id
);
3019 LogPrint(BCLog::NET
, "%s: sending header %s to peer=%d\n", __func__
,
3020 vHeaders
.front().GetHash().ToString(), pto
->id
);
3022 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
3023 state
.pindexBestHeaderSent
= pBestIndex
;
3025 fRevertToInv
= true;
3028 // If falling back to using an inv, just try to inv the tip.
3029 // The last entry in vBlockHashesToAnnounce was our tip at some point
3031 if (!pto
->vBlockHashesToAnnounce
.empty()) {
3032 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
3033 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
3034 assert(mi
!= mapBlockIndex
.end());
3035 const CBlockIndex
*pindex
= mi
->second
;
3037 // Warn if we're announcing a block that is not on the main chain.
3038 // This should be very rare and could be optimized out.
3039 // Just log for now.
3040 if (chainActive
[pindex
->nHeight
] != pindex
) {
3041 LogPrint(BCLog::NET
, "Announcing block %s not on main chain (tip=%s)\n",
3042 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
3045 // If the peer's chain has this block, don't inv it back.
3046 if (!PeerHasHeader(&state
, pindex
)) {
3047 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
3048 LogPrint(BCLog::NET
, "%s: sending inv peer=%d hash=%s\n", __func__
,
3049 pto
->id
, hashToAnnounce
.ToString());
3053 pto
->vBlockHashesToAnnounce
.clear();
3057 // Message: inventory
3059 std::vector
<CInv
> vInv
;
3061 LOCK(pto
->cs_inventory
);
3062 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
3065 BOOST_FOREACH(const uint256
& hash
, pto
->vInventoryBlockToSend
) {
3066 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
3067 if (vInv
.size() == MAX_INV_SZ
) {
3068 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3072 pto
->vInventoryBlockToSend
.clear();
3074 // Check whether periodic sends should happen
3075 bool fSendTrickle
= pto
->fWhitelisted
;
3076 if (pto
->nNextInvSend
< nNow
) {
3077 fSendTrickle
= true;
3078 // Use half the delay for outbound peers, as there is less privacy concern for them.
3079 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
3082 // Time to send but the peer has requested we not relay transactions.
3084 LOCK(pto
->cs_filter
);
3085 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
3088 // Respond to BIP35 mempool requests
3089 if (fSendTrickle
&& pto
->fSendMempool
) {
3090 auto vtxinfo
= mempool
.infoAll();
3091 pto
->fSendMempool
= false;
3092 CAmount filterrate
= 0;
3094 LOCK(pto
->cs_feeFilter
);
3095 filterrate
= pto
->minFeeFilter
;
3098 LOCK(pto
->cs_filter
);
3100 for (const auto& txinfo
: vtxinfo
) {
3101 const uint256
& hash
= txinfo
.tx
->GetHash();
3102 CInv
inv(MSG_TX
, hash
);
3103 pto
->setInventoryTxToSend
.erase(hash
);
3105 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
3109 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3111 pto
->filterInventoryKnown
.insert(hash
);
3112 vInv
.push_back(inv
);
3113 if (vInv
.size() == MAX_INV_SZ
) {
3114 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3118 pto
->timeLastMempoolReq
= GetTime();
3121 // Determine transactions to relay
3123 // Produce a vector with all candidates for sending
3124 std::vector
<std::set
<uint256
>::iterator
> vInvTx
;
3125 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
3126 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
3127 vInvTx
.push_back(it
);
3129 CAmount filterrate
= 0;
3131 LOCK(pto
->cs_feeFilter
);
3132 filterrate
= pto
->minFeeFilter
;
3134 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3135 // A heap is used so that not all items need sorting if only a few are being sent.
3136 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
3137 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3138 // No reason to drain out at many times the network's capacity,
3139 // especially since we have many peers and some will draw much shorter delays.
3140 unsigned int nRelayedTransactions
= 0;
3141 LOCK(pto
->cs_filter
);
3142 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
3143 // Fetch the top element from the heap
3144 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3145 std::set
<uint256
>::iterator it
= vInvTx
.back();
3148 // Remove it from the to-be-sent set
3149 pto
->setInventoryTxToSend
.erase(it
);
3150 // Check if not in the filter already
3151 if (pto
->filterInventoryKnown
.contains(hash
)) {
3154 // Not in the mempool anymore? don't bother sending it.
3155 auto txinfo
= mempool
.info(hash
);
3159 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
3162 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3164 vInv
.push_back(CInv(MSG_TX
, hash
));
3165 nRelayedTransactions
++;
3167 // Expire old relay messages
3168 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
3170 mapRelay
.erase(vRelayExpiration
.front().second
);
3171 vRelayExpiration
.pop_front();
3174 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
3176 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
3179 if (vInv
.size() == MAX_INV_SZ
) {
3180 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3183 pto
->filterInventoryKnown
.insert(hash
);
3188 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3190 // Detect whether we're stalling
3191 nNow
= GetTimeMicros();
3192 if (state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
3193 // Stalling only triggers when the block download window cannot move. During normal steady state,
3194 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3195 // should only happen during initial block download.
3196 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->id
);
3197 pto
->fDisconnect
= true;
3200 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3201 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3202 // We compensate for other peers to prevent killing off peers due to our own downstream link
3203 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3204 // to unreasonably increase our timeout.
3205 if (state
.vBlocksInFlight
.size() > 0) {
3206 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
3207 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
3208 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
3209 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->id
);
3210 pto
->fDisconnect
= true;
3216 // Message: getdata (blocks)
3218 std::vector
<CInv
> vGetData
;
3219 if (!pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
3220 std::vector
<const CBlockIndex
*> vToDownload
;
3221 NodeId staller
= -1;
3222 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
3223 BOOST_FOREACH(const CBlockIndex
*pindex
, vToDownload
) {
3224 uint32_t nFetchFlags
= GetFetchFlags(pto
, pindex
->pprev
, consensusParams
);
3225 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
3226 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), consensusParams
, pindex
);
3227 LogPrint(BCLog::NET
, "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
3228 pindex
->nHeight
, pto
->id
);
3230 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
3231 if (State(staller
)->nStallingSince
== 0) {
3232 State(staller
)->nStallingSince
= nNow
;
3233 LogPrint(BCLog::NET
, "Stall started peer=%d\n", staller
);
3239 // Message: getdata (non-blocks)
3241 while (!pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
3243 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
3244 if (!AlreadyHave(inv
))
3246 LogPrint(BCLog::NET
, "Requesting %s peer=%d\n", inv
.ToString(), pto
->id
);
3247 vGetData
.push_back(inv
);
3248 if (vGetData
.size() >= 1000)
3250 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3254 //If we're not going to ask, don't expect a response.
3255 pto
->setAskFor
.erase(inv
.hash
);
3257 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
3259 if (!vGetData
.empty())
3260 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3263 // Message: feefilter
3265 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3266 if (pto
->nVersion
>= FEEFILTER_VERSION
&& GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
3267 !(pto
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
3268 CAmount currentFilter
= mempool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
3269 int64_t timeNow
= GetTimeMicros();
3270 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
3271 static CFeeRate
default_feerate(DEFAULT_MIN_RELAY_TX_FEE
);
3272 static FeeFilterRounder
filterRounder(default_feerate
);
3273 CAmount filterToSend
= filterRounder
.round(currentFilter
);
3274 // We always have a fee filter of at least minRelayTxFee
3275 filterToSend
= std::max(filterToSend
, ::minRelayTxFee
.GetFeePerK());
3276 if (filterToSend
!= pto
->lastSentFeeFilter
) {
3277 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::FEEFILTER
, filterToSend
));
3278 pto
->lastSentFeeFilter
= filterToSend
;
3280 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
3282 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3283 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3284 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
3285 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
3286 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
3293 class CNetProcessingCleanup
3296 CNetProcessingCleanup() {}
3297 ~CNetProcessingCleanup() {
3298 // orphan transactions
3299 mapOrphanTransactions
.clear();
3300 mapOrphanTransactionsByPrev
.clear();
3302 } instance_of_cnetprocessingcleanup
;