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("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("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION
, nNodeStartingHeight
, addrMe
.ToString(), nodeid
);
265 void InitializeNode(CNode
*pnode
, CConnman
& connman
) {
266 CAddress addr
= pnode
->addr
;
267 std::string addrName
= pnode
->GetAddrName();
268 NodeId nodeid
= pnode
->GetId();
271 mapNodeState
.emplace_hint(mapNodeState
.end(), std::piecewise_construct
, std::forward_as_tuple(nodeid
), std::forward_as_tuple(addr
, std::move(addrName
)));
274 PushNodeVersion(pnode
, connman
, GetTime());
277 void FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
278 fUpdateConnectionTime
= false;
280 CNodeState
*state
= State(nodeid
);
282 if (state
->fSyncStarted
)
285 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
286 fUpdateConnectionTime
= true;
289 BOOST_FOREACH(const QueuedBlock
& entry
, state
->vBlocksInFlight
) {
290 mapBlocksInFlight
.erase(entry
.hash
);
292 EraseOrphansFor(nodeid
);
293 nPreferredDownload
-= state
->fPreferredDownload
;
294 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
295 assert(nPeersWithValidatedDownloads
>= 0);
297 mapNodeState
.erase(nodeid
);
299 if (mapNodeState
.empty()) {
300 // Do a consistency check after the last peer is removed.
301 assert(mapBlocksInFlight
.empty());
302 assert(nPreferredDownload
== 0);
303 assert(nPeersWithValidatedDownloads
== 0);
308 // Returns a bool indicating whether we requested this block.
309 // Also used if a block was /not/ received and timed out or started with another peer
310 bool MarkBlockAsReceived(const uint256
& hash
) {
311 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
312 if (itInFlight
!= mapBlocksInFlight
.end()) {
313 CNodeState
*state
= State(itInFlight
->second
.first
);
314 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
315 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
316 // Last validated block on the queue was received.
317 nPeersWithValidatedDownloads
--;
319 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
320 // First block on the queue was received, update the start download time for the next one
321 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
323 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
324 state
->nBlocksInFlight
--;
325 state
->nStallingSince
= 0;
326 mapBlocksInFlight
.erase(itInFlight
);
333 // returns false, still setting pit, if the block was already in flight from the same peer
334 // pit will only be valid as long as the same cs_main lock is being held
335 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindex
= NULL
, std::list
<QueuedBlock
>::iterator
** pit
= NULL
) {
336 CNodeState
*state
= State(nodeid
);
337 assert(state
!= NULL
);
339 // Short-circuit most stuff in case its from the same node
340 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
341 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
342 *pit
= &itInFlight
->second
.second
;
346 // Make sure it's not listed somewhere already.
347 MarkBlockAsReceived(hash
);
349 std::list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
350 {hash
, pindex
, pindex
!= NULL
, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : NULL
)});
351 state
->nBlocksInFlight
++;
352 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
353 if (state
->nBlocksInFlight
== 1) {
354 // We're starting a block download (batch) from this peer.
355 state
->nDownloadingSince
= GetTimeMicros();
357 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= NULL
) {
358 nPeersWithValidatedDownloads
++;
360 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
362 *pit
= &itInFlight
->second
.second
;
366 /** Check whether the last unknown block a peer advertised is not yet known. */
367 void ProcessBlockAvailability(NodeId nodeid
) {
368 CNodeState
*state
= State(nodeid
);
369 assert(state
!= NULL
);
371 if (!state
->hashLastUnknownBlock
.IsNull()) {
372 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
373 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
374 if (state
->pindexBestKnownBlock
== NULL
|| itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
375 state
->pindexBestKnownBlock
= itOld
->second
;
376 state
->hashLastUnknownBlock
.SetNull();
381 /** Update tracking information about which blocks a peer is assumed to have. */
382 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
383 CNodeState
*state
= State(nodeid
);
384 assert(state
!= NULL
);
386 ProcessBlockAvailability(nodeid
);
388 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
389 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
390 // An actually better block was announced.
391 if (state
->pindexBestKnownBlock
== NULL
|| it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
392 state
->pindexBestKnownBlock
= it
->second
;
394 // An unknown block was announced; just assume that the latest one is the best one.
395 state
->hashLastUnknownBlock
= hash
;
399 void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid
, CConnman
& connman
) {
400 AssertLockHeld(cs_main
);
401 CNodeState
* nodestate
= State(nodeid
);
402 if (!nodestate
|| !nodestate
->fSupportsDesiredCmpctVersion
) {
403 // Never ask from peers who can't provide witnesses.
406 if (nodestate
->fProvidesHeaderAndIDs
) {
407 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
409 lNodesAnnouncingHeaderAndIDs
.erase(it
);
410 lNodesAnnouncingHeaderAndIDs
.push_back(nodeid
);
414 connman
.ForNode(nodeid
, [&connman
](CNode
* pfrom
){
415 bool fAnnounceUsingCMPCTBLOCK
= false;
416 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
417 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
418 // As per BIP152, we only get 3 of our peers to announce
419 // blocks using compact encodings.
420 connman
.ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [&connman
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
421 connman
.PushMessage(pnodeStop
, CNetMsgMaker(pnodeStop
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
424 lNodesAnnouncingHeaderAndIDs
.pop_front();
426 fAnnounceUsingCMPCTBLOCK
= true;
427 connman
.PushMessage(pfrom
, CNetMsgMaker(pfrom
->GetSendVersion()).Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
428 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
435 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
437 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
441 bool PeerHasHeader(CNodeState
*state
, const CBlockIndex
*pindex
)
443 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
445 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
450 /** Find the last common ancestor two blocks have.
451 * Both pa and pb must be non-NULL. */
452 const CBlockIndex
* LastCommonAncestor(const CBlockIndex
* pa
, const CBlockIndex
* pb
) {
453 if (pa
->nHeight
> pb
->nHeight
) {
454 pa
= pa
->GetAncestor(pb
->nHeight
);
455 } else if (pb
->nHeight
> pa
->nHeight
) {
456 pb
= pb
->GetAncestor(pa
->nHeight
);
459 while (pa
!= pb
&& pa
&& pb
) {
464 // Eventually all chain branches meet at the genesis block.
469 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
470 * at most count entries. */
471 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<const CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
475 vBlocks
.reserve(vBlocks
.size() + count
);
476 CNodeState
*state
= State(nodeid
);
477 assert(state
!= NULL
);
479 // Make sure pindexBestKnownBlock is up to date, we'll need it.
480 ProcessBlockAvailability(nodeid
);
482 if (state
->pindexBestKnownBlock
== NULL
|| state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
) {
483 // This peer has nothing interesting.
487 if (state
->pindexLastCommonBlock
== NULL
) {
488 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
489 // Guessing wrong in either direction is not a problem.
490 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
493 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
494 // of its current tip anymore. Go back enough to fix that.
495 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
496 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
499 std::vector
<const CBlockIndex
*> vToFetch
;
500 const CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
501 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
502 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
503 // download that next block if the window were 1 larger.
504 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
505 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
506 NodeId waitingfor
= -1;
507 while (pindexWalk
->nHeight
< nMaxHeight
) {
508 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
509 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
510 // as iterating over ~100 CBlockIndex* entries anyway.
511 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
512 vToFetch
.resize(nToFetch
);
513 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
514 vToFetch
[nToFetch
- 1] = pindexWalk
;
515 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
516 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
519 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
520 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
521 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
522 // already part of our chain (and therefore don't need it even if pruned).
523 BOOST_FOREACH(const CBlockIndex
* pindex
, vToFetch
) {
524 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
525 // We consider the chain that this peer is on invalid.
528 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
529 // We wouldn't download this block or its descendants from this peer.
532 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
533 if (pindex
->nChainTx
)
534 state
->pindexLastCommonBlock
= pindex
;
535 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
536 // The block is not already downloaded, and not yet in flight.
537 if (pindex
->nHeight
> nWindowEnd
) {
538 // We reached the end of the window.
539 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
540 // We aren't able to fetch anything, but we would be if the download window was one larger.
541 nodeStaller
= waitingfor
;
545 vBlocks
.push_back(pindex
);
546 if (vBlocks
.size() == count
) {
549 } else if (waitingfor
== -1) {
550 // This is the first already-in-flight block.
551 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
559 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
561 CNodeState
*state
= State(nodeid
);
564 stats
.nMisbehavior
= state
->nMisbehavior
;
565 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
566 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
567 BOOST_FOREACH(const QueuedBlock
& queue
, state
->vBlocksInFlight
) {
569 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
574 void RegisterNodeSignals(CNodeSignals
& nodeSignals
)
576 nodeSignals
.ProcessMessages
.connect(&ProcessMessages
);
577 nodeSignals
.SendMessages
.connect(&SendMessages
);
578 nodeSignals
.InitializeNode
.connect(&InitializeNode
);
579 nodeSignals
.FinalizeNode
.connect(&FinalizeNode
);
582 void UnregisterNodeSignals(CNodeSignals
& nodeSignals
)
584 nodeSignals
.ProcessMessages
.disconnect(&ProcessMessages
);
585 nodeSignals
.SendMessages
.disconnect(&SendMessages
);
586 nodeSignals
.InitializeNode
.disconnect(&InitializeNode
);
587 nodeSignals
.FinalizeNode
.disconnect(&FinalizeNode
);
590 //////////////////////////////////////////////////////////////////////////////
592 // mapOrphanTransactions
595 void AddToCompactExtraTransactions(const CTransactionRef
& tx
)
597 size_t max_extra_txn
= GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
);
598 if (max_extra_txn
<= 0)
600 if (!vExtraTxnForCompact
.size())
601 vExtraTxnForCompact
.resize(max_extra_txn
);
602 vExtraTxnForCompact
[vExtraTxnForCompactIt
] = std::make_pair(tx
->GetWitnessHash(), tx
);
603 vExtraTxnForCompactIt
= (vExtraTxnForCompactIt
+ 1) % max_extra_txn
;
606 bool AddOrphanTx(const CTransactionRef
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
608 const uint256
& hash
= tx
->GetHash();
609 if (mapOrphanTransactions
.count(hash
))
612 // Ignore big transactions, to avoid a
613 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
614 // large transaction with a missing parent then we assume
615 // it will rebroadcast it later, after the parent transaction(s)
616 // have been mined or received.
617 // 100 orphans, each of which is at most 99,999 bytes big is
618 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
619 unsigned int sz
= GetTransactionWeight(*tx
);
620 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
622 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
626 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
628 BOOST_FOREACH(const CTxIn
& txin
, tx
->vin
) {
629 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
632 AddToCompactExtraTransactions(tx
);
634 LogPrint("mempool", "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
635 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
639 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
641 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
642 if (it
== mapOrphanTransactions
.end())
644 BOOST_FOREACH(const CTxIn
& txin
, it
->second
.tx
->vin
)
646 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
647 if (itPrev
== mapOrphanTransactionsByPrev
.end())
649 itPrev
->second
.erase(it
);
650 if (itPrev
->second
.empty())
651 mapOrphanTransactionsByPrev
.erase(itPrev
);
653 mapOrphanTransactions
.erase(it
);
657 void EraseOrphansFor(NodeId peer
)
660 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
661 while (iter
!= mapOrphanTransactions
.end())
663 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
664 if (maybeErase
->second
.fromPeer
== peer
)
666 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
669 if (nErased
> 0) LogPrint("mempool", "Erased %d orphan tx from peer=%d\n", nErased
, peer
);
673 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
675 unsigned int nEvicted
= 0;
676 static int64_t nNextSweep
;
677 int64_t nNow
= GetTime();
678 if (nNextSweep
<= nNow
) {
679 // Sweep out expired orphan pool entries:
681 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
682 std::map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
683 while (iter
!= mapOrphanTransactions
.end())
685 std::map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
686 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
687 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
->GetHash());
689 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
692 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
693 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
694 if (nErased
> 0) LogPrint("mempool", "Erased %d orphan tx due to expiration\n", nErased
);
696 while (mapOrphanTransactions
.size() > nMaxOrphans
)
698 // Evict a random orphan:
699 uint256 randomhash
= GetRandHash();
700 std::map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
701 if (it
== mapOrphanTransactions
.end())
702 it
= mapOrphanTransactions
.begin();
703 EraseOrphanTx(it
->first
);
710 void Misbehaving(NodeId pnode
, int howmuch
)
715 CNodeState
*state
= State(pnode
);
719 state
->nMisbehavior
+= howmuch
;
720 int banscore
= GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
721 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
723 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
724 state
->fShouldBan
= true;
726 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
736 //////////////////////////////////////////////////////////////////////////////
738 // blockchain -> download logic notification
741 PeerLogicValidation::PeerLogicValidation(CConnman
* connmanIn
) : connman(connmanIn
) {
742 // Initialize global variables that cannot be constructed at startup.
743 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
746 void PeerLogicValidation::SyncTransaction(const CTransaction
& tx
, const CBlockIndex
* pindex
, int nPosInBlock
) {
747 if (nPosInBlock
== CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
)
752 std::vector
<uint256
> vOrphanErase
;
753 // Which orphan pool entries must we evict?
754 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
755 auto itByPrev
= mapOrphanTransactionsByPrev
.find(tx
.vin
[j
].prevout
);
756 if (itByPrev
== mapOrphanTransactionsByPrev
.end()) continue;
757 for (auto mi
= itByPrev
->second
.begin(); mi
!= itByPrev
->second
.end(); ++mi
) {
758 const CTransaction
& orphanTx
= *(*mi
)->second
.tx
;
759 const uint256
& orphanHash
= orphanTx
.GetHash();
760 vOrphanErase
.push_back(orphanHash
);
764 // Erase orphan transactions include or precluded by this block
765 if (vOrphanErase
.size()) {
767 BOOST_FOREACH(uint256
&orphanHash
, vOrphanErase
) {
768 nErased
+= EraseOrphanTx(orphanHash
);
770 LogPrint("mempool", "Erased %d orphan tx included or conflicted by block\n", nErased
);
774 static CCriticalSection cs_most_recent_block
;
775 static std::shared_ptr
<const CBlock
> most_recent_block
;
776 static std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> most_recent_compact_block
;
777 static uint256 most_recent_block_hash
;
779 void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex
*pindex
, const std::shared_ptr
<const CBlock
>& pblock
) {
780 std::shared_ptr
<const CBlockHeaderAndShortTxIDs
> pcmpctblock
= std::make_shared
<const CBlockHeaderAndShortTxIDs
> (*pblock
, true);
781 const CNetMsgMaker
msgMaker(PROTOCOL_VERSION
);
785 static int nHighestFastAnnounce
= 0;
786 if (pindex
->nHeight
<= nHighestFastAnnounce
)
788 nHighestFastAnnounce
= pindex
->nHeight
;
790 bool fWitnessEnabled
= IsWitnessEnabled(pindex
->pprev
, Params().GetConsensus());
791 uint256
hashBlock(pblock
->GetHash());
794 LOCK(cs_most_recent_block
);
795 most_recent_block_hash
= hashBlock
;
796 most_recent_block
= pblock
;
797 most_recent_compact_block
= pcmpctblock
;
800 connman
->ForEachNode([this, &pcmpctblock
, pindex
, &msgMaker
, fWitnessEnabled
, &hashBlock
](CNode
* pnode
) {
801 // TODO: Avoid the repeated-serialization here
802 if (pnode
->nVersion
< INVALID_CB_NO_BAN_VERSION
|| pnode
->fDisconnect
)
804 ProcessBlockAvailability(pnode
->GetId());
805 CNodeState
&state
= *State(pnode
->GetId());
806 // If the peer has, or we announced to them the previous block already,
807 // but we don't think they have this one, go ahead and announce it
808 if (state
.fPreferHeaderAndIDs
&& (!fWitnessEnabled
|| state
.fWantsCmpctWitness
) &&
809 !PeerHasHeader(&state
, pindex
) && PeerHasHeader(&state
, pindex
->pprev
)) {
811 LogPrint("net", "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
812 hashBlock
.ToString(), pnode
->id
);
813 connman
->PushMessage(pnode
, msgMaker
.Make(NetMsgType::CMPCTBLOCK
, *pcmpctblock
));
814 state
.pindexBestHeaderSent
= pindex
;
819 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex
*pindexNew
, const CBlockIndex
*pindexFork
, bool fInitialDownload
) {
820 const int nNewHeight
= pindexNew
->nHeight
;
821 connman
->SetBestHeight(nNewHeight
);
823 if (!fInitialDownload
) {
824 // Find the hashes of all blocks that weren't previously in the best chain.
825 std::vector
<uint256
> vHashes
;
826 const CBlockIndex
*pindexToAnnounce
= pindexNew
;
827 while (pindexToAnnounce
!= pindexFork
) {
828 vHashes
.push_back(pindexToAnnounce
->GetBlockHash());
829 pindexToAnnounce
= pindexToAnnounce
->pprev
;
830 if (vHashes
.size() == MAX_BLOCKS_TO_ANNOUNCE
) {
831 // Limit announcements in case of a huge reorganization.
832 // Rely on the peer's synchronization mechanism in that case.
836 // Relay inventory, but don't relay old inventory during initial block download.
837 connman
->ForEachNode([nNewHeight
, &vHashes
](CNode
* pnode
) {
838 if (nNewHeight
> (pnode
->nStartingHeight
!= -1 ? pnode
->nStartingHeight
- 2000 : 0)) {
839 BOOST_REVERSE_FOREACH(const uint256
& hash
, vHashes
) {
840 pnode
->PushBlockHash(hash
);
844 connman
->WakeMessageHandler();
847 nTimeBestReceived
= GetTime();
850 void PeerLogicValidation::BlockChecked(const CBlock
& block
, const CValidationState
& state
) {
853 const uint256
hash(block
.GetHash());
854 std::map
<uint256
, std::pair
<NodeId
, bool>>::iterator it
= mapBlockSource
.find(hash
);
857 if (state
.IsInvalid(nDoS
)) {
858 if (it
!= mapBlockSource
.end() && State(it
->second
.first
)) {
859 assert (state
.GetRejectCode() < REJECT_INTERNAL
); // Blocks are never rejected with internal reject codes
860 CBlockReject reject
= {(unsigned char)state
.GetRejectCode(), state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), hash
};
861 State(it
->second
.first
)->rejects
.push_back(reject
);
862 if (nDoS
> 0 && it
->second
.second
)
863 Misbehaving(it
->second
.first
, nDoS
);
867 // 1. The block is valid
868 // 2. We're not in initial block download
869 // 3. This is currently the best block we're aware of. We haven't updated
870 // the tip yet so we have no way to check this directly here. Instead we
871 // just check that there are currently no other blocks in flight.
872 else if (state
.IsValid() &&
873 !IsInitialBlockDownload() &&
874 mapBlocksInFlight
.count(hash
) == mapBlocksInFlight
.size()) {
875 if (it
!= mapBlockSource
.end()) {
876 MaybeSetPeerAsAnnouncingHeaderAndIDs(it
->second
.first
, *connman
);
879 if (it
!= mapBlockSource
.end())
880 mapBlockSource
.erase(it
);
883 //////////////////////////////////////////////////////////////////////////////
889 bool static AlreadyHave(const CInv
& inv
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
896 assert(recentRejects
);
897 if (chainActive
.Tip()->GetBlockHash() != hashRecentRejectsChainTip
)
899 // If the chain tip has changed previously rejected transactions
900 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
901 // or a double-spend. Reset the rejects filter and give those
902 // txs a second chance.
903 hashRecentRejectsChainTip
= chainActive
.Tip()->GetBlockHash();
904 recentRejects
->reset();
907 // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
908 // requesting or processing some txs which have already been included in a block
909 return recentRejects
->contains(inv
.hash
) ||
910 mempool
.exists(inv
.hash
) ||
911 mapOrphanTransactions
.count(inv
.hash
) ||
912 pcoinsTip
->HaveCoinsInCache(inv
.hash
);
915 case MSG_WITNESS_BLOCK
:
916 return mapBlockIndex
.count(inv
.hash
);
918 // Don't know what it is, just say we already got one
922 static void RelayTransaction(const CTransaction
& tx
, CConnman
& connman
)
924 CInv
inv(MSG_TX
, tx
.GetHash());
925 connman
.ForEachNode([&inv
](CNode
* pnode
)
927 pnode
->PushInventory(inv
);
931 static void RelayAddress(const CAddress
& addr
, bool fReachable
, CConnman
& connman
)
933 unsigned int nRelayNodes
= fReachable
? 2 : 1; // limited relaying of addresses outside our network(s)
935 // Relay to a limited number of other nodes
936 // Use deterministic randomness to send to the same nodes for 24 hours
937 // at a time so the addrKnowns of the chosen nodes prevent repeats
938 uint64_t hashAddr
= addr
.GetHash();
939 const CSipHasher hasher
= connman
.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY
).Write(hashAddr
<< 32).Write((GetTime() + hashAddr
) / (24*60*60));
940 FastRandomContext insecure_rand
;
942 std::array
<std::pair
<uint64_t, CNode
*>,2> best
{{{0, nullptr}, {0, nullptr}}};
943 assert(nRelayNodes
<= best
.size());
945 auto sortfunc
= [&best
, &hasher
, nRelayNodes
](CNode
* pnode
) {
946 if (pnode
->nVersion
>= CADDR_TIME_VERSION
) {
947 uint64_t hashKey
= CSipHasher(hasher
).Write(pnode
->id
).Finalize();
948 for (unsigned int i
= 0; i
< nRelayNodes
; i
++) {
949 if (hashKey
> best
[i
].first
) {
950 std::copy(best
.begin() + i
, best
.begin() + nRelayNodes
- 1, best
.begin() + i
+ 1);
951 best
[i
] = std::make_pair(hashKey
, pnode
);
958 auto pushfunc
= [&addr
, &best
, nRelayNodes
, &insecure_rand
] {
959 for (unsigned int i
= 0; i
< nRelayNodes
&& best
[i
].first
!= 0; i
++) {
960 best
[i
].second
->PushAddress(addr
, insecure_rand
);
964 connman
.ForEachNodeThen(std::move(sortfunc
), std::move(pushfunc
));
967 void static ProcessGetData(CNode
* pfrom
, const Consensus::Params
& consensusParams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
969 std::deque
<CInv
>::iterator it
= pfrom
->vRecvGetData
.begin();
970 std::vector
<CInv
> vNotFound
;
971 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
974 while (it
!= pfrom
->vRecvGetData
.end()) {
975 // Don't bother if send buffer is too full to respond anyway
976 if (pfrom
->fPauseSend
)
979 const CInv
&inv
= *it
;
981 if (interruptMsgProc
)
986 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
989 BlockMap::iterator mi
= mapBlockIndex
.find(inv
.hash
);
990 if (mi
!= mapBlockIndex
.end())
992 if (mi
->second
->nChainTx
&& !mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) &&
993 mi
->second
->IsValid(BLOCK_VALID_TREE
)) {
994 // If we have the block and all of its parents, but have not yet validated it,
995 // we might be in the middle of connecting it (ie in the unlock of cs_main
996 // before ActivateBestChain but after AcceptBlock).
997 // In this case, we need to run ActivateBestChain prior to checking the relay
999 std::shared_ptr
<const CBlock
> a_recent_block
;
1001 LOCK(cs_most_recent_block
);
1002 a_recent_block
= most_recent_block
;
1004 CValidationState dummy
;
1005 ActivateBestChain(dummy
, Params(), a_recent_block
);
1007 if (chainActive
.Contains(mi
->second
)) {
1010 static const int nOneMonth
= 30 * 24 * 60 * 60;
1011 // To prevent fingerprinting attacks, only send blocks outside of the active
1012 // chain if they are valid, and no more than a month older (both in time, and in
1013 // best equivalent proof of work) than the best header chain we know about.
1014 send
= mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) && (pindexBestHeader
!= NULL
) &&
1015 (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() < nOneMonth
) &&
1016 (GetBlockProofEquivalentTime(*pindexBestHeader
, *mi
->second
, *pindexBestHeader
, consensusParams
) < nOneMonth
);
1018 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
1022 // disconnect node in case we have reached the outbound limit for serving historical blocks
1023 // never disconnect whitelisted nodes
1024 static const int nOneWeek
= 7 * 24 * 60 * 60; // assume > 1 week = historical
1025 if (send
&& connman
.OutboundTargetReached(true) && ( ((pindexBestHeader
!= NULL
) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > nOneWeek
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
1027 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
1030 pfrom
->fDisconnect
= true;
1033 // Pruned nodes may have deleted the block, so check whether
1034 // it's available before trying to send.
1035 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
1037 // Send block from disk
1039 if (!ReadBlockFromDisk(block
, (*mi
).second
, consensusParams
))
1040 assert(!"cannot load block from disk");
1041 if (inv
.type
== MSG_BLOCK
)
1042 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, block
));
1043 else if (inv
.type
== MSG_WITNESS_BLOCK
)
1044 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::BLOCK
, block
));
1045 else if (inv
.type
== MSG_FILTERED_BLOCK
)
1047 bool sendMerkleBlock
= false;
1048 CMerkleBlock merkleBlock
;
1050 LOCK(pfrom
->cs_filter
);
1051 if (pfrom
->pfilter
) {
1052 sendMerkleBlock
= true;
1053 merkleBlock
= CMerkleBlock(block
, *pfrom
->pfilter
);
1056 if (sendMerkleBlock
) {
1057 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::MERKLEBLOCK
, merkleBlock
));
1058 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
1059 // This avoids hurting performance by pointlessly requiring a round-trip
1060 // Note that there is currently no way for a node to request any single transactions we didn't send here -
1061 // they must either disconnect and retry or request the full block.
1062 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
1063 // however we MUST always provide at least what the remote peer needs
1064 typedef std::pair
<unsigned int, uint256
> PairType
;
1065 BOOST_FOREACH(PairType
& pair
, merkleBlock
.vMatchedTxn
)
1066 connman
.PushMessage(pfrom
, msgMaker
.Make(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, *block
.vtx
[pair
.first
]));
1071 else if (inv
.type
== MSG_CMPCT_BLOCK
)
1073 // If a peer is asking for old blocks, we're almost guaranteed
1074 // they won't have a useful mempool to match against a compact block,
1075 // and we don't feel like constructing the object for them, so
1076 // instead we respond with the full, non-compact block.
1077 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
1078 int nSendFlags
= fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1079 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
1080 CBlockHeaderAndShortTxIDs
cmpctblock(block
, fPeerWantsWitness
);
1081 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
1083 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCK
, block
));
1086 // Trigger the peer node to send a getblocks request for the next batch of inventory
1087 if (inv
.hash
== pfrom
->hashContinue
)
1089 // Bypass PushInventory, this must send even if redundant,
1090 // and we want it right after the last block so they don't
1091 // wait for other stuff first.
1092 std::vector
<CInv
> vInv
;
1093 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
1094 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::INV
, vInv
));
1095 pfrom
->hashContinue
.SetNull();
1099 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
1101 // Send stream from relay memory
1103 auto mi
= mapRelay
.find(inv
.hash
);
1104 int nSendFlags
= (inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0);
1105 if (mi
!= mapRelay
.end()) {
1106 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *mi
->second
));
1108 } else if (pfrom
->timeLastMempoolReq
) {
1109 auto txinfo
= mempool
.info(inv
.hash
);
1110 // To protect privacy, do not answer getdata using the mempool when
1111 // that TX couldn't have been INVed in reply to a MEMPOOL request.
1112 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
1113 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::TX
, *txinfo
.tx
));
1118 vNotFound
.push_back(inv
);
1122 // Track requests for our stuff.
1123 GetMainSignals().Inventory(inv
.hash
);
1125 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
1130 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
1132 if (!vNotFound
.empty()) {
1133 // Let the peer know that we didn't find what it asked for, so it doesn't
1134 // have to wait around forever. Currently only SPV clients actually care
1135 // about this message: it's needed when they are recursively walking the
1136 // dependencies of relevant unconfirmed transactions. SPV clients want to
1137 // do that because they want to know about (and store and rebroadcast and
1138 // risk analyze) the dependencies of transactions relevant to them, without
1139 // having to download the entire memory pool.
1140 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::NOTFOUND
, vNotFound
));
1144 uint32_t GetFetchFlags(CNode
* pfrom
, const CBlockIndex
* pprev
, const Consensus::Params
& chainparams
) {
1145 uint32_t nFetchFlags
= 0;
1146 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
1147 nFetchFlags
|= MSG_WITNESS_FLAG
;
1152 inline void static SendBlockTransactions(const CBlock
& block
, const BlockTransactionsRequest
& req
, CNode
* pfrom
, CConnman
& connman
) {
1153 BlockTransactions
resp(req
);
1154 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
1155 if (req
.indexes
[i
] >= block
.vtx
.size()) {
1157 Misbehaving(pfrom
->GetId(), 100);
1158 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->id
);
1161 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
1164 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1165 int nSendFlags
= State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
1166 connman
.PushMessage(pfrom
, msgMaker
.Make(nSendFlags
, NetMsgType::BLOCKTXN
, resp
));
1169 bool static ProcessMessage(CNode
* pfrom
, const std::string
& strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
1171 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->id
);
1172 if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
1174 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
1179 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
1180 (strCommand
== NetMsgType::FILTERLOAD
||
1181 strCommand
== NetMsgType::FILTERADD
))
1183 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
1185 Misbehaving(pfrom
->GetId(), 100);
1188 pfrom
->fDisconnect
= true;
1194 if (strCommand
== NetMsgType::VERSION
)
1196 // Each connection can only send one version message
1197 if (pfrom
->nVersion
!= 0)
1199 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, std::string("Duplicate version message")));
1201 Misbehaving(pfrom
->GetId(), 1);
1208 uint64_t nNonce
= 1;
1209 uint64_t nServiceInt
;
1210 ServiceFlags nServices
;
1213 std::string strSubVer
;
1214 std::string cleanSubVer
;
1215 int nStartingHeight
= -1;
1218 vRecv
>> nVersion
>> nServiceInt
>> nTime
>> addrMe
;
1219 nSendVersion
= std::min(nVersion
, PROTOCOL_VERSION
);
1220 nServices
= ServiceFlags(nServiceInt
);
1221 if (!pfrom
->fInbound
)
1223 connman
.SetServices(pfrom
->addr
, nServices
);
1225 if (pfrom
->nServicesExpected
& ~nServices
)
1227 LogPrint("net", "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->id
, nServices
, pfrom
->nServicesExpected
);
1228 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
1229 strprintf("Expected to offer services %08x", pfrom
->nServicesExpected
)));
1230 pfrom
->fDisconnect
= true;
1234 if (nVersion
< MIN_PEER_PROTO_VERSION
)
1236 // disconnect from peers older than this proto version
1237 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom
->id
, nVersion
);
1238 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
1239 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
)));
1240 pfrom
->fDisconnect
= true;
1244 if (nVersion
== 10300)
1247 vRecv
>> addrFrom
>> nNonce
;
1248 if (!vRecv
.empty()) {
1249 vRecv
>> LIMITED_STRING(strSubVer
, MAX_SUBVERSION_LENGTH
);
1250 cleanSubVer
= SanitizeString(strSubVer
);
1252 if (!vRecv
.empty()) {
1253 vRecv
>> nStartingHeight
;
1257 // Disconnect if we connected to ourself
1258 if (pfrom
->fInbound
&& !connman
.CheckIncomingNonce(nNonce
))
1260 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
1261 pfrom
->fDisconnect
= true;
1265 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
1270 // Be shy and don't send version until we hear
1271 if (pfrom
->fInbound
)
1272 PushNodeVersion(pfrom
, connman
, GetAdjustedTime());
1274 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::VERACK
));
1276 pfrom
->nServices
= nServices
;
1277 pfrom
->SetAddrLocal(addrMe
);
1279 LOCK(pfrom
->cs_SubVer
);
1280 pfrom
->strSubVer
= strSubVer
;
1281 pfrom
->cleanSubVer
= cleanSubVer
;
1283 pfrom
->nStartingHeight
= nStartingHeight
;
1284 pfrom
->fClient
= !(nServices
& NODE_NETWORK
);
1286 LOCK(pfrom
->cs_filter
);
1287 pfrom
->fRelayTxes
= fRelay
; // set to true after we get the first filter* message
1291 pfrom
->SetSendVersion(nSendVersion
);
1292 pfrom
->nVersion
= nVersion
;
1294 if((nServices
& NODE_WITNESS
))
1297 State(pfrom
->GetId())->fHaveWitness
= true;
1300 // Potentially mark this peer as a preferred download peer.
1303 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
1306 if (!pfrom
->fInbound
)
1308 // Advertise our address
1309 if (fListen
&& !IsInitialBlockDownload())
1311 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
1312 FastRandomContext insecure_rand
;
1313 if (addr
.IsRoutable())
1315 LogPrint("net", "ProcessMessages: advertising address %s\n", addr
.ToString());
1316 pfrom
->PushAddress(addr
, insecure_rand
);
1317 } else if (IsPeerAddrLocalGood(pfrom
)) {
1319 LogPrint("net", "ProcessMessages: advertising address %s\n", addr
.ToString());
1320 pfrom
->PushAddress(addr
, insecure_rand
);
1324 // Get recent addresses
1325 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
.GetAddressCount() < 1000)
1327 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make(NetMsgType::GETADDR
));
1328 pfrom
->fGetAddr
= true;
1330 connman
.MarkAddressGood(pfrom
->addr
);
1333 std::string remoteAddr
;
1335 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
1337 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
1338 cleanSubVer
, pfrom
->nVersion
,
1339 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->id
,
1342 int64_t nTimeOffset
= nTime
- GetTime();
1343 pfrom
->nTimeOffset
= nTimeOffset
;
1344 AddTimeData(pfrom
->addr
, nTimeOffset
);
1346 // If the peer is old enough to have the old alert system, send it the final alert.
1347 if (pfrom
->nVersion
<= 70012) {
1348 CDataStream
finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK
, PROTOCOL_VERSION
);
1349 connman
.PushMessage(pfrom
, CNetMsgMaker(nSendVersion
).Make("alert", finalAlert
));
1352 // Feeler connections exist only to verify if address is online.
1353 if (pfrom
->fFeeler
) {
1354 assert(pfrom
->fInbound
== false);
1355 pfrom
->fDisconnect
= true;
1361 else if (pfrom
->nVersion
== 0)
1363 // Must have a version message before anything else
1365 Misbehaving(pfrom
->GetId(), 1);
1369 // At this point, the outgoing message serialization version can't change.
1370 const CNetMsgMaker
msgMaker(pfrom
->GetSendVersion());
1372 if (strCommand
== NetMsgType::VERACK
)
1374 pfrom
->SetRecvVersion(std::min(pfrom
->nVersion
.load(), PROTOCOL_VERSION
));
1376 if (!pfrom
->fInbound
) {
1377 // Mark this node as currently connected, so we update its timestamp later.
1379 State(pfrom
->GetId())->fCurrentlyConnected
= true;
1382 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
1383 // Tell our peer we prefer to receive headers rather than inv's
1384 // We send this to non-NODE NETWORK peers as well, because even
1385 // non-NODE NETWORK peers can announce blocks (such as pruning
1387 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDHEADERS
));
1389 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
1390 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
1391 // However, we do not request new block announcements using
1392 // cmpctblock messages.
1393 // We send this to non-NODE NETWORK peers as well, because
1394 // they may wish to request compact blocks from us
1395 bool fAnnounceUsingCMPCTBLOCK
= false;
1396 uint64_t nCMPCTBLOCKVersion
= 2;
1397 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1398 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1399 nCMPCTBLOCKVersion
= 1;
1400 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
));
1402 pfrom
->fSuccessfullyConnected
= true;
1406 else if (strCommand
== NetMsgType::ADDR
)
1408 std::vector
<CAddress
> vAddr
;
1411 // Don't want addr from older versions unless seeding
1412 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
.GetAddressCount() > 1000)
1414 if (vAddr
.size() > 1000)
1417 Misbehaving(pfrom
->GetId(), 20);
1418 return error("message addr size() = %u", vAddr
.size());
1421 // Store the new addresses
1422 std::vector
<CAddress
> vAddrOk
;
1423 int64_t nNow
= GetAdjustedTime();
1424 int64_t nSince
= nNow
- 10 * 60;
1425 BOOST_FOREACH(CAddress
& addr
, vAddr
)
1427 if (interruptMsgProc
)
1430 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1433 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
1434 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
1435 pfrom
->AddAddressKnown(addr
);
1436 bool fReachable
= IsReachable(addr
);
1437 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
1439 // Relay to a limited number of other nodes
1440 RelayAddress(addr
, fReachable
, connman
);
1442 // Do not store addresses outside our network
1444 vAddrOk
.push_back(addr
);
1446 connman
.AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
1447 if (vAddr
.size() < 1000)
1448 pfrom
->fGetAddr
= false;
1449 if (pfrom
->fOneShot
)
1450 pfrom
->fDisconnect
= true;
1453 else if (strCommand
== NetMsgType::SENDHEADERS
)
1456 State(pfrom
->GetId())->fPreferHeaders
= true;
1459 else if (strCommand
== NetMsgType::SENDCMPCT
)
1461 bool fAnnounceUsingCMPCTBLOCK
= false;
1462 uint64_t nCMPCTBLOCKVersion
= 0;
1463 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
1464 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
1466 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
1467 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
1468 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
1469 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
1471 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
1472 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
1473 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
1474 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
1475 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
1477 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
1483 else if (strCommand
== NetMsgType::INV
)
1485 std::vector
<CInv
> vInv
;
1487 if (vInv
.size() > MAX_INV_SZ
)
1490 Misbehaving(pfrom
->GetId(), 20);
1491 return error("message inv size() = %u", vInv
.size());
1494 bool fBlocksOnly
= !fRelayTxes
;
1496 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
1497 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
1498 fBlocksOnly
= false;
1502 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus());
1504 std::vector
<CInv
> vToFetch
;
1506 for (unsigned int nInv
= 0; nInv
< vInv
.size(); nInv
++)
1508 CInv
&inv
= vInv
[nInv
];
1510 if (interruptMsgProc
)
1513 bool fAlreadyHave
= AlreadyHave(inv
);
1514 LogPrint("net", "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->id
);
1516 if (inv
.type
== MSG_TX
) {
1517 inv
.type
|= nFetchFlags
;
1520 if (inv
.type
== MSG_BLOCK
) {
1521 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
1522 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
1523 // We used to request the full block here, but since headers-announcements are now the
1524 // primary method of announcement on the network, and since, in the case that a node
1525 // fell back to inv we probably have a reorg which we should get the headers for first,
1526 // we now only provide a getheaders response here. When we receive the headers, we will
1527 // then ask for the blocks we need.
1528 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
));
1529 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->id
);
1534 pfrom
->AddInventoryKnown(inv
);
1536 LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->id
);
1537 else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload())
1541 // Track requests for our stuff
1542 GetMainSignals().Inventory(inv
.hash
);
1545 if (!vToFetch
.empty())
1546 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vToFetch
));
1550 else if (strCommand
== NetMsgType::GETDATA
)
1552 std::vector
<CInv
> vInv
;
1554 if (vInv
.size() > MAX_INV_SZ
)
1557 Misbehaving(pfrom
->GetId(), 20);
1558 return error("message getdata size() = %u", vInv
.size());
1561 if (fDebug
|| (vInv
.size() != 1))
1562 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->id
);
1564 if ((fDebug
&& vInv
.size() > 0) || (vInv
.size() == 1))
1565 LogPrint("net", "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->id
);
1567 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
1568 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1572 else if (strCommand
== NetMsgType::GETBLOCKS
)
1574 CBlockLocator locator
;
1576 vRecv
>> locator
>> hashStop
;
1578 // We might have announced the currently-being-connected tip using a
1579 // compact block, which resulted in the peer sending a getblocks
1580 // request, which we would otherwise respond to without the new block.
1581 // To avoid this situation we simply verify that we are on our best
1582 // known chain now. This is super overkill, but we handle it better
1583 // for getheaders requests, and there are no known nodes which support
1584 // compact blocks but still use getblocks to request blocks.
1586 std::shared_ptr
<const CBlock
> a_recent_block
;
1588 LOCK(cs_most_recent_block
);
1589 a_recent_block
= most_recent_block
;
1591 CValidationState dummy
;
1592 ActivateBestChain(dummy
, Params(), a_recent_block
);
1597 // Find the last block the caller has in the main chain
1598 const CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1600 // Send the rest of the chain
1602 pindex
= chainActive
.Next(pindex
);
1604 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), nLimit
, pfrom
->id
);
1605 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1607 if (pindex
->GetBlockHash() == hashStop
)
1609 LogPrint("net", " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1612 // If pruning, don't inv blocks unless we have on disk and are likely to still have
1613 // for some reasonable time window (1 hour) that block relay might require.
1614 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
1615 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
1617 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1620 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
1623 // When this block is requested, we'll send an inv that'll
1624 // trigger the peer to getblocks the next batch of inventory.
1625 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
1626 pfrom
->hashContinue
= pindex
->GetBlockHash();
1633 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
1635 BlockTransactionsRequest req
;
1638 std::shared_ptr
<const CBlock
> recent_block
;
1640 LOCK(cs_most_recent_block
);
1641 if (most_recent_block_hash
== req
.blockhash
)
1642 recent_block
= most_recent_block
;
1643 // Unlock cs_most_recent_block to avoid cs_main lock inversion
1646 SendBlockTransactions(*recent_block
, req
, pfrom
, connman
);
1652 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
1653 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
1654 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom
->id
);
1658 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
1659 // If an older block is requested (should never happen in practice,
1660 // but can happen in tests) send a block response instead of a
1661 // blocktxn response. Sending a full block response instead of a
1662 // small blocktxn response is preferable in the case where a peer
1663 // might maliciously send lots of getblocktxn requests to trigger
1664 // expensive disk reads, because it will require the peer to
1665 // actually receive all the data read from disk over the network.
1666 LogPrint("net", "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->id
, MAX_BLOCKTXN_DEPTH
);
1668 inv
.type
= State(pfrom
->GetId())->fWantsCmpctWitness
? MSG_WITNESS_BLOCK
: MSG_BLOCK
;
1669 inv
.hash
= req
.blockhash
;
1670 pfrom
->vRecvGetData
.push_back(inv
);
1671 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
1676 bool ret
= ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus());
1679 SendBlockTransactions(block
, req
, pfrom
, connman
);
1683 else if (strCommand
== NetMsgType::GETHEADERS
)
1685 CBlockLocator locator
;
1687 vRecv
>> locator
>> hashStop
;
1690 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
1691 LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->id
);
1695 CNodeState
*nodestate
= State(pfrom
->GetId());
1696 const CBlockIndex
* pindex
= NULL
;
1697 if (locator
.IsNull())
1699 // If locator is null, return the hashStop block
1700 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
1701 if (mi
== mapBlockIndex
.end())
1703 pindex
= (*mi
).second
;
1707 // Find the last block the caller has in the main chain
1708 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
1710 pindex
= chainActive
.Next(pindex
);
1713 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
1714 std::vector
<CBlock
> vHeaders
;
1715 int nLimit
= MAX_HEADERS_RESULTS
;
1716 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->id
);
1717 for (; pindex
; pindex
= chainActive
.Next(pindex
))
1719 vHeaders
.push_back(pindex
->GetBlockHeader());
1720 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
1723 // pindex can be NULL either if we sent chainActive.Tip() OR
1724 // if our peer has chainActive.Tip() (and thus we are sending an empty
1725 // headers message). In both cases it's safe to update
1726 // pindexBestHeaderSent to be our tip.
1728 // It is important that we simply reset the BestHeaderSent value here,
1729 // and not max(BestHeaderSent, newHeaderSent). We might have announced
1730 // the currently-being-connected tip using a compact block, which
1731 // resulted in the peer sending a headers request, which we respond to
1732 // without the new block. By resetting the BestHeaderSent, we ensure we
1733 // will re-announce the new block via headers (or compact blocks again)
1734 // in the SendMessages logic.
1735 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
1736 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
1740 else if (strCommand
== NetMsgType::TX
)
1742 // Stop processing the transaction early if
1743 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
1744 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
1746 LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom
->id
);
1750 std::deque
<COutPoint
> vWorkQueue
;
1751 std::vector
<uint256
> vEraseQueue
;
1752 CTransactionRef ptx
;
1754 const CTransaction
& tx
= *ptx
;
1756 CInv
inv(MSG_TX
, tx
.GetHash());
1757 pfrom
->AddInventoryKnown(inv
);
1761 bool fMissingInputs
= false;
1762 CValidationState state
;
1764 pfrom
->setAskFor
.erase(inv
.hash
);
1765 mapAlreadyAskedFor
.erase(inv
.hash
);
1767 std::list
<CTransactionRef
> lRemovedTxn
;
1769 if (!AlreadyHave(inv
) && AcceptToMemoryPool(mempool
, state
, ptx
, true, &fMissingInputs
, &lRemovedTxn
)) {
1770 mempool
.check(pcoinsTip
);
1771 RelayTransaction(tx
, connman
);
1772 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
1773 vWorkQueue
.emplace_back(inv
.hash
, i
);
1776 pfrom
->nLastTXTime
= GetTime();
1778 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
1780 tx
.GetHash().ToString(),
1781 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
1783 // Recursively process any orphan transactions that depended on this one
1784 std::set
<NodeId
> setMisbehaving
;
1785 while (!vWorkQueue
.empty()) {
1786 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
1787 vWorkQueue
.pop_front();
1788 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
1790 for (auto mi
= itByPrev
->second
.begin();
1791 mi
!= itByPrev
->second
.end();
1794 const CTransactionRef
& porphanTx
= (*mi
)->second
.tx
;
1795 const CTransaction
& orphanTx
= *porphanTx
;
1796 const uint256
& orphanHash
= orphanTx
.GetHash();
1797 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
1798 bool fMissingInputs2
= false;
1799 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
1800 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
1801 // anyone relaying LegitTxX banned)
1802 CValidationState stateDummy
;
1805 if (setMisbehaving
.count(fromPeer
))
1807 if (AcceptToMemoryPool(mempool
, stateDummy
, porphanTx
, true, &fMissingInputs2
, &lRemovedTxn
)) {
1808 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash
.ToString());
1809 RelayTransaction(orphanTx
, connman
);
1810 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
1811 vWorkQueue
.emplace_back(orphanHash
, i
);
1813 vEraseQueue
.push_back(orphanHash
);
1815 else if (!fMissingInputs2
)
1818 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
1820 // Punish peer that gave us an invalid orphan tx
1821 Misbehaving(fromPeer
, nDos
);
1822 setMisbehaving
.insert(fromPeer
);
1823 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash
.ToString());
1825 // Has inputs but not accepted to mempool
1826 // Probably non-standard or insufficient fee/priority
1827 LogPrint("mempool", " removed orphan tx %s\n", orphanHash
.ToString());
1828 vEraseQueue
.push_back(orphanHash
);
1829 if (!orphanTx
.HasWitness() && !stateDummy
.CorruptionPossible()) {
1830 // Do not use rejection cache for witness transactions or
1831 // witness-stripped transactions, as they can have been malleated.
1832 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1833 assert(recentRejects
);
1834 recentRejects
->insert(orphanHash
);
1837 mempool
.check(pcoinsTip
);
1841 BOOST_FOREACH(uint256 hash
, vEraseQueue
)
1842 EraseOrphanTx(hash
);
1844 else if (fMissingInputs
)
1846 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
1847 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1848 if (recentRejects
->contains(txin
.prevout
.hash
)) {
1849 fRejectedParents
= true;
1853 if (!fRejectedParents
) {
1854 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus());
1855 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1856 CInv
_inv(MSG_TX
| nFetchFlags
, txin
.prevout
.hash
);
1857 pfrom
->AddInventoryKnown(_inv
);
1858 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
1860 AddOrphanTx(ptx
, pfrom
->GetId());
1862 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
1863 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
1864 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
1866 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted
);
1868 LogPrint("mempool", "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
1869 // We will continue to reject this tx since it has rejected
1870 // parents so avoid re-requesting it from other peers.
1871 recentRejects
->insert(tx
.GetHash());
1874 if (!tx
.HasWitness() && !state
.CorruptionPossible()) {
1875 // Do not use rejection cache for witness transactions or
1876 // witness-stripped transactions, as they can have been malleated.
1877 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
1878 assert(recentRejects
);
1879 recentRejects
->insert(tx
.GetHash());
1880 if (RecursiveDynamicUsage(*ptx
) < 100000) {
1881 AddToCompactExtraTransactions(ptx
);
1883 } else if (tx
.HasWitness() && RecursiveDynamicUsage(*ptx
) < 100000) {
1884 AddToCompactExtraTransactions(ptx
);
1887 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
1888 // Always relay transactions received from whitelisted peers, even
1889 // if they were already in the mempool or rejected from it due
1890 // to policy, allowing the node to function as a gateway for
1891 // nodes hidden behind it.
1893 // Never relay transactions that we would assign a non-zero DoS
1894 // score for, as we expect peers to do the same with us in that
1897 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
1898 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->id
);
1899 RelayTransaction(tx
, connman
);
1901 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->id
, FormatStateMessage(state
));
1906 for (const CTransactionRef
& removedTx
: lRemovedTxn
)
1907 AddToCompactExtraTransactions(removedTx
);
1910 if (state
.IsInvalid(nDoS
))
1912 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
1914 FormatStateMessage(state
));
1915 if (state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
1916 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
1917 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
));
1919 Misbehaving(pfrom
->GetId(), nDoS
);
1925 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
1927 CBlockHeaderAndShortTxIDs cmpctblock
;
1928 vRecv
>> cmpctblock
;
1933 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
1934 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
1935 if (!IsInitialBlockDownload())
1936 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
1941 const CBlockIndex
*pindex
= NULL
;
1942 CValidationState state
;
1943 if (!ProcessNewBlockHeaders({cmpctblock
.header
}, state
, chainparams
, &pindex
)) {
1945 if (state
.IsInvalid(nDoS
)) {
1948 Misbehaving(pfrom
->GetId(), nDoS
);
1950 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->id
);
1955 // When we succeed in decoding a block's txids from a cmpctblock
1956 // message we typically jump to the BLOCKTXN handling code, with a
1957 // dummy (empty) BLOCKTXN message, to re-use the logic there in
1958 // completing processing of the putative block (without cs_main).
1959 bool fProcessBLOCKTXN
= false;
1960 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
1962 // If we end up treating this as a plain headers message, call that as well
1964 bool fRevertToHeaderProcessing
= false;
1965 CDataStream
vHeadersMsg(SER_NETWORK
, PROTOCOL_VERSION
);
1967 // Keep a CBlock for "optimistic" compactblock reconstructions (see
1969 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
1970 bool fBlockReconstructed
= false;
1974 // If AcceptBlockHeader returned true, it set pindex
1976 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
1978 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
1979 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
1981 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
1984 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
1985 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
1986 if (fAlreadyInFlight
) {
1987 // We requested this block for some reason, but our mempool will probably be useless
1988 // so we just grab the block via normal getdata
1989 std::vector
<CInv
> vInv(1);
1990 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
1991 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
1996 // If we're not close to tip yet, give up and let parallel block fetch work its magic
1997 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
2000 CNodeState
*nodestate
= State(pfrom
->GetId());
2002 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
2003 // Don't bother trying to process compact blocks from v1 peers
2004 // after segwit activates.
2008 // We want to be a bit conservative just to be extra careful about DoS
2009 // possibilities in compact block processing...
2010 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
2011 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
2012 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
2013 std::list
<QueuedBlock
>::iterator
* queuedBlockIt
= NULL
;
2014 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
, &queuedBlockIt
)) {
2015 if (!(*queuedBlockIt
)->partialBlock
)
2016 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
2018 // The block was already in flight using compact blocks from the same peer
2019 LogPrint("net", "Peer sent us compact block we were already syncing!\n");
2024 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
2025 ReadStatus status
= partialBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2026 if (status
== READ_STATUS_INVALID
) {
2027 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
2028 Misbehaving(pfrom
->GetId(), 100);
2029 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->id
);
2031 } else if (status
== READ_STATUS_FAILED
) {
2032 // Duplicate txindexes, the block is now in-flight, so just request it
2033 std::vector
<CInv
> vInv(1);
2034 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
2035 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2039 BlockTransactionsRequest req
;
2040 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
2041 if (!partialBlock
.IsTxAvailable(i
))
2042 req
.indexes
.push_back(i
);
2044 if (req
.indexes
.empty()) {
2045 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
2046 BlockTransactions txn
;
2047 txn
.blockhash
= cmpctblock
.header
.GetHash();
2049 fProcessBLOCKTXN
= true;
2051 req
.blockhash
= pindex
->GetBlockHash();
2052 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETBLOCKTXN
, req
));
2055 // This block is either already in flight from a different
2056 // peer, or this peer has too many blocks outstanding to
2058 // Optimistically try to reconstruct anyway since we might be
2059 // able to without any round trips.
2060 PartiallyDownloadedBlock
tempBlock(&mempool
);
2061 ReadStatus status
= tempBlock
.InitData(cmpctblock
, vExtraTxnForCompact
);
2062 if (status
!= READ_STATUS_OK
) {
2063 // TODO: don't ignore failures
2066 std::vector
<CTransactionRef
> dummy
;
2067 status
= tempBlock
.FillBlock(*pblock
, dummy
);
2068 if (status
== READ_STATUS_OK
) {
2069 fBlockReconstructed
= true;
2073 if (fAlreadyInFlight
) {
2074 // We requested this block, but its far into the future, so our
2075 // mempool will probably be useless - request the block normally
2076 std::vector
<CInv
> vInv(1);
2077 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
2078 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vInv
));
2081 // If this was an announce-cmpctblock, we want the same treatment as a header message
2082 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
2083 std::vector
<CBlock
> headers
;
2084 headers
.push_back(cmpctblock
.header
);
2085 vHeadersMsg
<< headers
;
2086 fRevertToHeaderProcessing
= true;
2091 if (fProcessBLOCKTXN
)
2092 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2094 if (fRevertToHeaderProcessing
)
2095 return ProcessMessage(pfrom
, NetMsgType::HEADERS
, vHeadersMsg
, nTimeReceived
, chainparams
, connman
, interruptMsgProc
);
2097 if (fBlockReconstructed
) {
2098 // If we got here, we were able to optimistically reconstruct a
2099 // block that is in flight from some other peer.
2102 mapBlockSource
.emplace(pblock
->GetHash(), std::make_pair(pfrom
->GetId(), false));
2104 bool fNewBlock
= false;
2105 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2107 pfrom
->nLastBlockTime
= GetTime();
2109 LOCK(cs_main
); // hold cs_main for CBlockIndex::IsValid()
2110 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
)) {
2111 // Clear download state for this block, which is in
2112 // process from some other peer. We do this after calling
2113 // ProcessNewBlock so that a malleated cmpctblock announcement
2114 // can't be used to interfere with block relay.
2115 MarkBlockAsReceived(pblock
->GetHash());
2121 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2123 BlockTransactions resp
;
2126 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2127 bool fBlockRead
= false;
2131 std::map
<uint256
, std::pair
<NodeId
, std::list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
2132 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
2133 it
->second
.first
!= pfrom
->GetId()) {
2134 LogPrint("net", "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->id
);
2138 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
2139 ReadStatus status
= partialBlock
.FillBlock(*pblock
, resp
.txn
);
2140 if (status
== READ_STATUS_INVALID
) {
2141 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
2142 Misbehaving(pfrom
->GetId(), 100);
2143 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->id
);
2145 } else if (status
== READ_STATUS_FAILED
) {
2146 // Might have collided, fall back to getdata now :(
2147 std::vector
<CInv
> invs
;
2148 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus()), resp
.blockhash
));
2149 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, invs
));
2151 // Block is either okay, or possibly we received
2152 // READ_STATUS_CHECKBLOCK_FAILED.
2153 // Note that CheckBlock can only fail for one of a few reasons:
2154 // 1. bad-proof-of-work (impossible here, because we've already
2155 // accepted the header)
2156 // 2. merkleroot doesn't match the transactions given (already
2157 // caught in FillBlock with READ_STATUS_FAILED, so
2159 // 3. the block is otherwise invalid (eg invalid coinbase,
2160 // block is too big, too many legacy sigops, etc).
2161 // So if CheckBlock failed, #3 is the only possibility.
2162 // Under BIP 152, we don't DoS-ban unless proof of work is
2163 // invalid (we don't require all the stateless checks to have
2164 // been run). This is handled below, so just treat this as
2165 // though the block was successfully read, and rely on the
2166 // handling in ProcessNewBlock to ensure the block index is
2167 // updated, reject messages go out, etc.
2168 MarkBlockAsReceived(resp
.blockhash
); // it is now an empty pointer
2170 // mapBlockSource is only used for sending reject messages and DoS scores,
2171 // so the race between here and cs_main in ProcessNewBlock is fine.
2172 // BIP 152 permits peers to relay compact blocks after validating
2173 // the header only; we should not punish peers if the block turns
2174 // out to be invalid.
2175 mapBlockSource
.emplace(resp
.blockhash
, std::make_pair(pfrom
->GetId(), false));
2177 } // Don't hold cs_main when we call into ProcessNewBlock
2179 bool fNewBlock
= false;
2180 // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
2181 // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
2182 ProcessNewBlock(chainparams
, pblock
, true, &fNewBlock
);
2184 pfrom
->nLastBlockTime
= GetTime();
2189 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
2191 std::vector
<CBlockHeader
> headers
;
2193 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
2194 unsigned int nCount
= ReadCompactSize(vRecv
);
2195 if (nCount
> MAX_HEADERS_RESULTS
) {
2197 Misbehaving(pfrom
->GetId(), 20);
2198 return error("headers message size = %u", nCount
);
2200 headers
.resize(nCount
);
2201 for (unsigned int n
= 0; n
< nCount
; n
++) {
2202 vRecv
>> headers
[n
];
2203 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
2207 // Nothing interesting. Stop asking this peers for more headers.
2211 const CBlockIndex
*pindexLast
= NULL
;
2214 CNodeState
*nodestate
= State(pfrom
->GetId());
2216 // If this looks like it could be a block announcement (nCount <
2217 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
2219 // - Send a getheaders message in response to try to connect the chain.
2220 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
2221 // don't connect before giving DoS points
2222 // - Once a headers message is received that is valid and does connect,
2223 // nUnconnectingHeaders gets reset back to 0.
2224 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
2225 nodestate
->nUnconnectingHeaders
++;
2226 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256()));
2227 LogPrint("net", "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
2228 headers
[0].GetHash().ToString(),
2229 headers
[0].hashPrevBlock
.ToString(),
2230 pindexBestHeader
->nHeight
,
2231 pfrom
->id
, nodestate
->nUnconnectingHeaders
);
2232 // Set hashLastUnknownBlock for this peer, so that if we
2233 // eventually get the headers - even from a different peer -
2234 // we can use this peer to download.
2235 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
2237 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
2238 Misbehaving(pfrom
->GetId(), 20);
2243 uint256 hashLastBlock
;
2244 for (const CBlockHeader
& header
: headers
) {
2245 if (!hashLastBlock
.IsNull() && header
.hashPrevBlock
!= hashLastBlock
) {
2246 Misbehaving(pfrom
->GetId(), 20);
2247 return error("non-continuous headers sequence");
2249 hashLastBlock
= header
.GetHash();
2253 CValidationState state
;
2254 if (!ProcessNewBlockHeaders(headers
, state
, chainparams
, &pindexLast
)) {
2256 if (state
.IsInvalid(nDoS
)) {
2259 Misbehaving(pfrom
->GetId(), nDoS
);
2261 return error("invalid header received");
2267 CNodeState
*nodestate
= State(pfrom
->GetId());
2268 if (nodestate
->nUnconnectingHeaders
> 0) {
2269 LogPrint("net", "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->id
, nodestate
->nUnconnectingHeaders
);
2271 nodestate
->nUnconnectingHeaders
= 0;
2274 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
2276 if (nCount
== MAX_HEADERS_RESULTS
) {
2277 // Headers message had its maximum size; the peer may have more headers.
2278 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
2279 // from there instead.
2280 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->id
, pfrom
->nStartingHeight
);
2281 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256()));
2284 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
2285 // If this set of headers is valid and ends in a block with at least as
2286 // much work as our tip, download as much as possible.
2287 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
2288 std::vector
<const CBlockIndex
*> vToFetch
;
2289 const CBlockIndex
*pindexWalk
= pindexLast
;
2290 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
2291 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2292 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
2293 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
2294 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
2295 // We don't have this block, and it's not yet in flight.
2296 vToFetch
.push_back(pindexWalk
);
2298 pindexWalk
= pindexWalk
->pprev
;
2300 // If pindexWalk still isn't on our main chain, we're looking at a
2301 // very large reorg at a time we think we're close to caught up to
2302 // the main chain -- this shouldn't really happen. Bail out on the
2303 // direct fetch and rely on parallel download instead.
2304 if (!chainActive
.Contains(pindexWalk
)) {
2305 LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
2306 pindexLast
->GetBlockHash().ToString(),
2307 pindexLast
->nHeight
);
2309 std::vector
<CInv
> vGetData
;
2310 // Download as much as possible, from earliest to latest.
2311 BOOST_REVERSE_FOREACH(const CBlockIndex
*pindex
, vToFetch
) {
2312 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
2313 // Can't download any more from this peer
2316 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus());
2317 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
2318 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
);
2319 LogPrint("net", "Requesting block %s from peer=%d\n",
2320 pindex
->GetBlockHash().ToString(), pfrom
->id
);
2322 if (vGetData
.size() > 1) {
2323 LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
2324 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
2326 if (vGetData
.size() > 0) {
2327 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
2328 // In any case, we want to download using a compact block, not a regular one
2329 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
2331 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
2338 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
2340 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
2343 LogPrint("net", "received block %s peer=%d\n", pblock
->GetHash().ToString(), pfrom
->id
);
2345 // Process all blocks from whitelisted peers, even if not requested,
2346 // unless we're still syncing with the network.
2347 // Such an unrequested block may still be processed, subject to the
2348 // conditions in AcceptBlock().
2349 bool forceProcessing
= pfrom
->fWhitelisted
&& !IsInitialBlockDownload();
2350 const uint256
hash(pblock
->GetHash());
2353 // Also always process if we requested the block explicitly, as we may
2354 // need it even though it is not a candidate for a new best tip.
2355 forceProcessing
|= MarkBlockAsReceived(hash
);
2356 // mapBlockSource is only used for sending reject messages and DoS scores,
2357 // so the race between here and cs_main in ProcessNewBlock is fine.
2358 mapBlockSource
.emplace(hash
, std::make_pair(pfrom
->GetId(), true));
2360 bool fNewBlock
= false;
2361 ProcessNewBlock(chainparams
, pblock
, forceProcessing
, &fNewBlock
);
2363 pfrom
->nLastBlockTime
= GetTime();
2367 else if (strCommand
== NetMsgType::GETADDR
)
2369 // This asymmetric behavior for inbound and outbound connections was introduced
2370 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
2371 // to users' AddrMan and later request them by sending getaddr messages.
2372 // Making nodes which are behind NAT and can only make outgoing connections ignore
2373 // the getaddr message mitigates the attack.
2374 if (!pfrom
->fInbound
) {
2375 LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->id
);
2379 // Only send one GetAddr response per connection to reduce resource waste
2380 // and discourage addr stamping of INV announcements.
2381 if (pfrom
->fSentAddr
) {
2382 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->id
);
2385 pfrom
->fSentAddr
= true;
2387 pfrom
->vAddrToSend
.clear();
2388 std::vector
<CAddress
> vAddr
= connman
.GetAddresses();
2389 FastRandomContext insecure_rand
;
2390 BOOST_FOREACH(const CAddress
&addr
, vAddr
)
2391 pfrom
->PushAddress(addr
, insecure_rand
);
2395 else if (strCommand
== NetMsgType::MEMPOOL
)
2397 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
2399 LogPrint("net", "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
2400 pfrom
->fDisconnect
= true;
2404 if (connman
.OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
2406 LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
2407 pfrom
->fDisconnect
= true;
2411 LOCK(pfrom
->cs_inventory
);
2412 pfrom
->fSendMempool
= true;
2416 else if (strCommand
== NetMsgType::PING
)
2418 if (pfrom
->nVersion
> BIP0031_VERSION
)
2422 // Echo the message back with the nonce. This allows for two useful features:
2424 // 1) A remote node can quickly check if the connection is operational
2425 // 2) Remote nodes can measure the latency of the network thread. If this node
2426 // is overloaded it won't respond to pings quickly and the remote node can
2427 // avoid sending us more work, like chain download requests.
2429 // The nonce stops the remote getting confused between different pings: without
2430 // it, if the remote node sends a ping once per second and this node takes 5
2431 // seconds to respond to each, the 5th ping the remote sends would appear to
2432 // return very quickly.
2433 connman
.PushMessage(pfrom
, msgMaker
.Make(NetMsgType::PONG
, nonce
));
2438 else if (strCommand
== NetMsgType::PONG
)
2440 int64_t pingUsecEnd
= nTimeReceived
;
2442 size_t nAvail
= vRecv
.in_avail();
2443 bool bPingFinished
= false;
2444 std::string sProblem
;
2446 if (nAvail
>= sizeof(nonce
)) {
2449 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
2450 if (pfrom
->nPingNonceSent
!= 0) {
2451 if (nonce
== pfrom
->nPingNonceSent
) {
2452 // Matching pong received, this ping is no longer outstanding
2453 bPingFinished
= true;
2454 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
2455 if (pingUsecTime
> 0) {
2456 // Successful ping time measurement, replace previous
2457 pfrom
->nPingUsecTime
= pingUsecTime
;
2458 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
.load(), pingUsecTime
);
2460 // This should never happen
2461 sProblem
= "Timing mishap";
2464 // Nonce mismatches are normal when pings are overlapping
2465 sProblem
= "Nonce mismatch";
2467 // This is most likely a bug in another implementation somewhere; cancel this ping
2468 bPingFinished
= true;
2469 sProblem
= "Nonce zero";
2473 sProblem
= "Unsolicited pong without ping";
2476 // This is most likely a bug in another implementation somewhere; cancel this ping
2477 bPingFinished
= true;
2478 sProblem
= "Short payload";
2481 if (!(sProblem
.empty())) {
2482 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
2485 pfrom
->nPingNonceSent
,
2489 if (bPingFinished
) {
2490 pfrom
->nPingNonceSent
= 0;
2495 else if (strCommand
== NetMsgType::FILTERLOAD
)
2497 CBloomFilter filter
;
2500 if (!filter
.IsWithinSizeConstraints())
2502 // There is no excuse for sending a too-large filter
2504 Misbehaving(pfrom
->GetId(), 100);
2508 LOCK(pfrom
->cs_filter
);
2509 delete pfrom
->pfilter
;
2510 pfrom
->pfilter
= new CBloomFilter(filter
);
2511 pfrom
->pfilter
->UpdateEmptyFull();
2512 pfrom
->fRelayTxes
= true;
2517 else if (strCommand
== NetMsgType::FILTERADD
)
2519 std::vector
<unsigned char> vData
;
2522 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
2523 // and thus, the maximum size any matched object can have) in a filteradd message
2525 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
2528 LOCK(pfrom
->cs_filter
);
2529 if (pfrom
->pfilter
) {
2530 pfrom
->pfilter
->insert(vData
);
2537 Misbehaving(pfrom
->GetId(), 100);
2542 else if (strCommand
== NetMsgType::FILTERCLEAR
)
2544 LOCK(pfrom
->cs_filter
);
2545 if (pfrom
->GetLocalServices() & NODE_BLOOM
) {
2546 delete pfrom
->pfilter
;
2547 pfrom
->pfilter
= new CBloomFilter();
2549 pfrom
->fRelayTxes
= true;
2553 else if (strCommand
== NetMsgType::REJECT
)
2557 std::string strMsg
; unsigned char ccode
; std::string strReason
;
2558 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
2560 std::ostringstream ss
;
2561 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
2563 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
2567 ss
<< ": hash " << hash
.ToString();
2569 LogPrint("net", "Reject %s\n", SanitizeString(ss
.str()));
2570 } catch (const std::ios_base::failure
&) {
2571 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
2572 LogPrint("net", "Unparseable reject message received\n");
2577 else if (strCommand
== NetMsgType::FEEFILTER
) {
2578 CAmount newFeeFilter
= 0;
2579 vRecv
>> newFeeFilter
;
2580 if (MoneyRange(newFeeFilter
)) {
2582 LOCK(pfrom
->cs_feeFilter
);
2583 pfrom
->minFeeFilter
= newFeeFilter
;
2585 LogPrint("net", "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->id
);
2589 else if (strCommand
== NetMsgType::NOTFOUND
) {
2590 // We do not care about the NOTFOUND message, but logging an Unknown Command
2591 // message would be undesirable as we transmit it ourselves.
2595 // Ignore unknown commands for extensibility
2596 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->id
);
2604 bool ProcessMessages(CNode
* pfrom
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2606 const CChainParams
& chainparams
= Params();
2609 // (4) message start
2615 bool fMoreWork
= false;
2617 if (!pfrom
->vRecvGetData
.empty())
2618 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
, interruptMsgProc
);
2620 if (pfrom
->fDisconnect
)
2623 // this maintains the order of responses
2624 if (!pfrom
->vRecvGetData
.empty()) return true;
2626 // Don't bother if send buffer is too full to respond anyway
2627 if (pfrom
->fPauseSend
)
2630 std::list
<CNetMessage
> msgs
;
2632 LOCK(pfrom
->cs_vProcessMsg
);
2633 if (pfrom
->vProcessMsg
.empty())
2635 // Just take one message
2636 msgs
.splice(msgs
.begin(), pfrom
->vProcessMsg
, pfrom
->vProcessMsg
.begin());
2637 pfrom
->nProcessQueueSize
-= msgs
.front().vRecv
.size() + CMessageHeader::HEADER_SIZE
;
2638 pfrom
->fPauseRecv
= pfrom
->nProcessQueueSize
> connman
.GetReceiveFloodSize();
2639 fMoreWork
= !pfrom
->vProcessMsg
.empty();
2641 CNetMessage
& msg(msgs
.front());
2643 msg
.SetVersion(pfrom
->GetRecvVersion());
2644 // Scan for message start
2645 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
2646 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->id
);
2647 pfrom
->fDisconnect
= true;
2652 CMessageHeader
& hdr
= msg
.hdr
;
2653 if (!hdr
.IsValid(chainparams
.MessageStart()))
2655 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->id
);
2658 std::string strCommand
= hdr
.GetCommand();
2661 unsigned int nMessageSize
= hdr
.nMessageSize
;
2664 CDataStream
& vRecv
= msg
.vRecv
;
2665 const uint256
& hash
= msg
.GetMessageHash();
2666 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
2668 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
2669 SanitizeString(strCommand
), nMessageSize
,
2670 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
2671 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
2679 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
, interruptMsgProc
);
2680 if (interruptMsgProc
)
2682 if (!pfrom
->vRecvGetData
.empty())
2685 catch (const std::ios_base::failure
& e
)
2687 connman
.PushMessage(pfrom
, CNetMsgMaker(INIT_PROTO_VERSION
).Make(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, std::string("error parsing message")));
2688 if (strstr(e
.what(), "end of data"))
2690 // Allow exceptions from under-length message on vRecv
2691 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());
2693 else if (strstr(e
.what(), "size too large"))
2695 // Allow exceptions from over-long size
2696 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2698 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
2700 // Allow exceptions from non-canonical encoding
2701 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
2705 PrintExceptionContinue(&e
, "ProcessMessages()");
2708 catch (const std::exception
& e
) {
2709 PrintExceptionContinue(&e
, "ProcessMessages()");
2711 PrintExceptionContinue(NULL
, "ProcessMessages()");
2715 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->id
);
2720 class CompareInvMempoolOrder
2724 CompareInvMempoolOrder(CTxMemPool
*_mempool
)
2729 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
2731 /* As std::make_heap produces a max-heap, we want the entries with the
2732 * fewest ancestors/highest fee to sort later. */
2733 return mp
->CompareDepthAndScore(*b
, *a
);
2737 bool SendMessages(CNode
* pto
, CConnman
& connman
, const std::atomic
<bool>& interruptMsgProc
)
2739 const Consensus::Params
& consensusParams
= Params().GetConsensus();
2741 // Don't send anything until the version handshake is complete
2742 if (!pto
->fSuccessfullyConnected
|| pto
->fDisconnect
)
2745 // If we get here, the outgoing message serialization version is set and can't change.
2746 const CNetMsgMaker
msgMaker(pto
->GetSendVersion());
2751 bool pingSend
= false;
2752 if (pto
->fPingQueued
) {
2753 // RPC ping request by user
2756 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
2757 // Ping automatically sent as a latency probe & keepalive.
2762 while (nonce
== 0) {
2763 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
2765 pto
->fPingQueued
= false;
2766 pto
->nPingUsecStart
= GetTimeMicros();
2767 if (pto
->nVersion
> BIP0031_VERSION
) {
2768 pto
->nPingNonceSent
= nonce
;
2769 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
, nonce
));
2771 // Peer is too old to support ping command with nonce, pong will never arrive.
2772 pto
->nPingNonceSent
= 0;
2773 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::PING
));
2777 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
2781 CNodeState
&state
= *State(pto
->GetId());
2783 BOOST_FOREACH(const CBlockReject
& reject
, state
.rejects
)
2784 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::REJECT
, (std::string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
));
2785 state
.rejects
.clear();
2787 if (state
.fShouldBan
) {
2788 state
.fShouldBan
= false;
2789 if (pto
->fWhitelisted
)
2790 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto
->addr
.ToString());
2791 else if (pto
->fAddnode
)
2792 LogPrintf("Warning: not punishing addnoded peer %s!\n", pto
->addr
.ToString());
2794 pto
->fDisconnect
= true;
2795 if (pto
->addr
.IsLocal())
2796 LogPrintf("Warning: not banning local peer %s!\n", pto
->addr
.ToString());
2799 connman
.Ban(pto
->addr
, BanReasonNodeMisbehaving
);
2805 // Address refresh broadcast
2806 int64_t nNow
= GetTimeMicros();
2807 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
2808 AdvertiseLocal(pto
);
2809 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
2815 if (pto
->nNextAddrSend
< nNow
) {
2816 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
2817 std::vector
<CAddress
> vAddr
;
2818 vAddr
.reserve(pto
->vAddrToSend
.size());
2819 BOOST_FOREACH(const CAddress
& addr
, pto
->vAddrToSend
)
2821 if (!pto
->addrKnown
.contains(addr
.GetKey()))
2823 pto
->addrKnown
.insert(addr
.GetKey());
2824 vAddr
.push_back(addr
);
2825 // receiver rejects addr messages larger than 1000
2826 if (vAddr
.size() >= 1000)
2828 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2833 pto
->vAddrToSend
.clear();
2835 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::ADDR
, vAddr
));
2836 // we only send the big addr message once
2837 if (pto
->vAddrToSend
.capacity() > 40)
2838 pto
->vAddrToSend
.shrink_to_fit();
2842 if (pindexBestHeader
== NULL
)
2843 pindexBestHeader
= chainActive
.Tip();
2844 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.
2845 if (!state
.fSyncStarted
&& !pto
->fClient
&& !fImporting
&& !fReindex
) {
2846 // Only actively request headers from a single peer, unless we're close to today.
2847 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
2848 state
.fSyncStarted
= true;
2850 const CBlockIndex
*pindexStart
= pindexBestHeader
;
2851 /* If possible, start at the block preceding the currently
2852 best known header. This ensures that we always get a
2853 non-empty list of headers back as long as the peer
2854 is up-to-date. With a non-empty response, we can initialise
2855 the peer's known best block. This wouldn't be possible
2856 if we requested starting at pindexBestHeader and
2857 got back an empty response. */
2858 if (pindexStart
->pprev
)
2859 pindexStart
= pindexStart
->pprev
;
2860 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->id
, pto
->nStartingHeight
);
2861 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256()));
2865 // Resend wallet transactions that haven't gotten in a block yet
2866 // Except during reindex, importing and IBD, when old wallet
2867 // transactions become unconfirmed and spams other nodes.
2868 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
2870 GetMainSignals().Broadcast(nTimeBestReceived
, &connman
);
2874 // Try sending block announcements via headers
2877 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
2878 // list of block hashes we're relaying, and our peer wants
2879 // headers announcements, then find the first header
2880 // not yet known to our peer but would connect, and send.
2881 // If no header would connect, or if we have too many
2882 // blocks, or if the peer doesn't want headers, just
2883 // add all to the inv queue.
2884 LOCK(pto
->cs_inventory
);
2885 std::vector
<CBlock
> vHeaders
;
2886 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
2887 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
2888 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
2889 const CBlockIndex
*pBestIndex
= NULL
; // last header queued for delivery
2890 ProcessBlockAvailability(pto
->id
); // ensure pindexBestKnownBlock is up-to-date
2892 if (!fRevertToInv
) {
2893 bool fFoundStartingHeader
= false;
2894 // Try to find first header that our peer doesn't have, and
2895 // then send all headers past that one. If we come across any
2896 // headers that aren't on chainActive, give up.
2897 BOOST_FOREACH(const uint256
&hash
, pto
->vBlockHashesToAnnounce
) {
2898 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
2899 assert(mi
!= mapBlockIndex
.end());
2900 const CBlockIndex
*pindex
= mi
->second
;
2901 if (chainActive
[pindex
->nHeight
] != pindex
) {
2902 // Bail out if we reorged away from this block
2903 fRevertToInv
= true;
2906 if (pBestIndex
!= NULL
&& pindex
->pprev
!= pBestIndex
) {
2907 // This means that the list of blocks to announce don't
2908 // connect to each other.
2909 // This shouldn't really be possible to hit during
2910 // regular operation (because reorgs should take us to
2911 // a chain that has some block not on the prior chain,
2912 // which should be caught by the prior check), but one
2913 // way this could happen is by using invalidateblock /
2914 // reconsiderblock repeatedly on the tip, causing it to
2915 // be added multiple times to vBlockHashesToAnnounce.
2916 // Robustly deal with this rare situation by reverting
2918 fRevertToInv
= true;
2921 pBestIndex
= pindex
;
2922 if (fFoundStartingHeader
) {
2923 // add this to the headers message
2924 vHeaders
.push_back(pindex
->GetBlockHeader());
2925 } else if (PeerHasHeader(&state
, pindex
)) {
2926 continue; // keep looking for the first new block
2927 } else if (pindex
->pprev
== NULL
|| PeerHasHeader(&state
, pindex
->pprev
)) {
2928 // Peer doesn't have this header but they do have the prior one.
2929 // Start sending headers.
2930 fFoundStartingHeader
= true;
2931 vHeaders
.push_back(pindex
->GetBlockHeader());
2933 // Peer doesn't have this header or the prior one -- nothing will
2934 // connect, so bail out.
2935 fRevertToInv
= true;
2940 if (!fRevertToInv
&& !vHeaders
.empty()) {
2941 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
2942 // We only send up to 1 block as header-and-ids, as otherwise
2943 // probably means we're doing an initial-ish-sync or they're slow
2944 LogPrint("net", "%s sending header-and-ids %s to peer=%d\n", __func__
,
2945 vHeaders
.front().GetHash().ToString(), pto
->id
);
2947 int nSendFlags
= state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
;
2949 bool fGotBlockFromCache
= false;
2951 LOCK(cs_most_recent_block
);
2952 if (most_recent_block_hash
== pBestIndex
->GetBlockHash()) {
2953 if (state
.fWantsCmpctWitness
)
2954 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, *most_recent_compact_block
));
2956 CBlockHeaderAndShortTxIDs
cmpctblock(*most_recent_block
, state
.fWantsCmpctWitness
);
2957 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
2959 fGotBlockFromCache
= true;
2962 if (!fGotBlockFromCache
) {
2964 bool ret
= ReadBlockFromDisk(block
, pBestIndex
, consensusParams
);
2966 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
2967 connman
.PushMessage(pto
, msgMaker
.Make(nSendFlags
, NetMsgType::CMPCTBLOCK
, cmpctblock
));
2969 state
.pindexBestHeaderSent
= pBestIndex
;
2970 } else if (state
.fPreferHeaders
) {
2971 if (vHeaders
.size() > 1) {
2972 LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
2974 vHeaders
.front().GetHash().ToString(),
2975 vHeaders
.back().GetHash().ToString(), pto
->id
);
2977 LogPrint("net", "%s: sending header %s to peer=%d\n", __func__
,
2978 vHeaders
.front().GetHash().ToString(), pto
->id
);
2980 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::HEADERS
, vHeaders
));
2981 state
.pindexBestHeaderSent
= pBestIndex
;
2983 fRevertToInv
= true;
2986 // If falling back to using an inv, just try to inv the tip.
2987 // The last entry in vBlockHashesToAnnounce was our tip at some point
2989 if (!pto
->vBlockHashesToAnnounce
.empty()) {
2990 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
2991 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
2992 assert(mi
!= mapBlockIndex
.end());
2993 const CBlockIndex
*pindex
= mi
->second
;
2995 // Warn if we're announcing a block that is not on the main chain.
2996 // This should be very rare and could be optimized out.
2997 // Just log for now.
2998 if (chainActive
[pindex
->nHeight
] != pindex
) {
2999 LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
3000 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
3003 // If the peer's chain has this block, don't inv it back.
3004 if (!PeerHasHeader(&state
, pindex
)) {
3005 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
3006 LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__
,
3007 pto
->id
, hashToAnnounce
.ToString());
3011 pto
->vBlockHashesToAnnounce
.clear();
3015 // Message: inventory
3017 std::vector
<CInv
> vInv
;
3019 LOCK(pto
->cs_inventory
);
3020 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
3023 BOOST_FOREACH(const uint256
& hash
, pto
->vInventoryBlockToSend
) {
3024 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
3025 if (vInv
.size() == MAX_INV_SZ
) {
3026 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3030 pto
->vInventoryBlockToSend
.clear();
3032 // Check whether periodic sends should happen
3033 bool fSendTrickle
= pto
->fWhitelisted
;
3034 if (pto
->nNextInvSend
< nNow
) {
3035 fSendTrickle
= true;
3036 // Use half the delay for outbound peers, as there is less privacy concern for them.
3037 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
3040 // Time to send but the peer has requested we not relay transactions.
3042 LOCK(pto
->cs_filter
);
3043 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
3046 // Respond to BIP35 mempool requests
3047 if (fSendTrickle
&& pto
->fSendMempool
) {
3048 auto vtxinfo
= mempool
.infoAll();
3049 pto
->fSendMempool
= false;
3050 CAmount filterrate
= 0;
3052 LOCK(pto
->cs_feeFilter
);
3053 filterrate
= pto
->minFeeFilter
;
3056 LOCK(pto
->cs_filter
);
3058 for (const auto& txinfo
: vtxinfo
) {
3059 const uint256
& hash
= txinfo
.tx
->GetHash();
3060 CInv
inv(MSG_TX
, hash
);
3061 pto
->setInventoryTxToSend
.erase(hash
);
3063 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
3067 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3069 pto
->filterInventoryKnown
.insert(hash
);
3070 vInv
.push_back(inv
);
3071 if (vInv
.size() == MAX_INV_SZ
) {
3072 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3076 pto
->timeLastMempoolReq
= GetTime();
3079 // Determine transactions to relay
3081 // Produce a vector with all candidates for sending
3082 std::vector
<std::set
<uint256
>::iterator
> vInvTx
;
3083 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
3084 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
3085 vInvTx
.push_back(it
);
3087 CAmount filterrate
= 0;
3089 LOCK(pto
->cs_feeFilter
);
3090 filterrate
= pto
->minFeeFilter
;
3092 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
3093 // A heap is used so that not all items need sorting if only a few are being sent.
3094 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
3095 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3096 // No reason to drain out at many times the network's capacity,
3097 // especially since we have many peers and some will draw much shorter delays.
3098 unsigned int nRelayedTransactions
= 0;
3099 LOCK(pto
->cs_filter
);
3100 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
3101 // Fetch the top element from the heap
3102 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
3103 std::set
<uint256
>::iterator it
= vInvTx
.back();
3106 // Remove it from the to-be-sent set
3107 pto
->setInventoryTxToSend
.erase(it
);
3108 // Check if not in the filter already
3109 if (pto
->filterInventoryKnown
.contains(hash
)) {
3112 // Not in the mempool anymore? don't bother sending it.
3113 auto txinfo
= mempool
.info(hash
);
3117 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
3120 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
3122 vInv
.push_back(CInv(MSG_TX
, hash
));
3123 nRelayedTransactions
++;
3125 // Expire old relay messages
3126 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
3128 mapRelay
.erase(vRelayExpiration
.front().second
);
3129 vRelayExpiration
.pop_front();
3132 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
3134 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
3137 if (vInv
.size() == MAX_INV_SZ
) {
3138 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3141 pto
->filterInventoryKnown
.insert(hash
);
3146 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::INV
, vInv
));
3148 // Detect whether we're stalling
3149 nNow
= GetTimeMicros();
3150 if (state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
3151 // Stalling only triggers when the block download window cannot move. During normal steady state,
3152 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
3153 // should only happen during initial block download.
3154 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->id
);
3155 pto
->fDisconnect
= true;
3158 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
3159 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
3160 // We compensate for other peers to prevent killing off peers due to our own downstream link
3161 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
3162 // to unreasonably increase our timeout.
3163 if (state
.vBlocksInFlight
.size() > 0) {
3164 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
3165 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
3166 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
3167 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->id
);
3168 pto
->fDisconnect
= true;
3174 // Message: getdata (blocks)
3176 std::vector
<CInv
> vGetData
;
3177 if (!pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
3178 std::vector
<const CBlockIndex
*> vToDownload
;
3179 NodeId staller
= -1;
3180 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
3181 BOOST_FOREACH(const CBlockIndex
*pindex
, vToDownload
) {
3182 uint32_t nFetchFlags
= GetFetchFlags(pto
, pindex
->pprev
, consensusParams
);
3183 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
3184 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), consensusParams
, pindex
);
3185 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
3186 pindex
->nHeight
, pto
->id
);
3188 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
3189 if (State(staller
)->nStallingSince
== 0) {
3190 State(staller
)->nStallingSince
= nNow
;
3191 LogPrint("net", "Stall started peer=%d\n", staller
);
3197 // Message: getdata (non-blocks)
3199 while (!pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
3201 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
3202 if (!AlreadyHave(inv
))
3205 LogPrint("net", "Requesting %s peer=%d\n", inv
.ToString(), pto
->id
);
3206 vGetData
.push_back(inv
);
3207 if (vGetData
.size() >= 1000)
3209 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3213 //If we're not going to ask, don't expect a response.
3214 pto
->setAskFor
.erase(inv
.hash
);
3216 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
3218 if (!vGetData
.empty())
3219 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::GETDATA
, vGetData
));
3222 // Message: feefilter
3224 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
3225 if (pto
->nVersion
>= FEEFILTER_VERSION
&& GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
3226 !(pto
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
3227 CAmount currentFilter
= mempool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
3228 int64_t timeNow
= GetTimeMicros();
3229 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
3230 static CFeeRate
default_feerate(DEFAULT_MIN_RELAY_TX_FEE
);
3231 static FeeFilterRounder
filterRounder(default_feerate
);
3232 CAmount filterToSend
= filterRounder
.round(currentFilter
);
3233 // If we don't allow free transactions, then we always have a fee filter of at least minRelayTxFee
3234 if (GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY
) <= 0)
3235 filterToSend
= std::max(filterToSend
, ::minRelayTxFee
.GetFeePerK());
3236 if (filterToSend
!= pto
->lastSentFeeFilter
) {
3237 connman
.PushMessage(pto
, msgMaker
.Make(NetMsgType::FEEFILTER
, filterToSend
));
3238 pto
->lastSentFeeFilter
= filterToSend
;
3240 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
3242 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
3243 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
3244 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
3245 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
3246 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
3253 class CNetProcessingCleanup
3256 CNetProcessingCleanup() {}
3257 ~CNetProcessingCleanup() {
3258 // orphan transactions
3259 mapOrphanTransactions
.clear();
3260 mapOrphanTransactionsByPrev
.clear();
3262 } instance_of_cnetprocessingcleanup
;