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.
9 #include "arith_uint256.h"
10 #include "blockencodings.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "consensus/consensus.h"
15 #include "consensus/merkle.h"
16 #include "consensus/validation.h"
19 #include "merkleblock.h"
21 #include "policy/fees.h"
22 #include "policy/policy.h"
24 #include "primitives/block.h"
25 #include "primitives/transaction.h"
27 #include "script/script.h"
28 #include "script/sigcache.h"
29 #include "script/standard.h"
30 #include "tinyformat.h"
32 #include "txmempool.h"
33 #include "ui_interface.h"
36 #include "utilmoneystr.h"
37 #include "utilstrencodings.h"
38 #include "validationinterface.h"
39 #include "versionbits.h"
44 #include <boost/algorithm/string/replace.hpp>
45 #include <boost/algorithm/string/join.hpp>
46 #include <boost/filesystem.hpp>
47 #include <boost/filesystem/fstream.hpp>
48 #include <boost/math/distributions/poisson.hpp>
49 #include <boost/thread.hpp>
54 # error "Bitcoin cannot be compiled without assertions."
61 CCriticalSection cs_main
;
63 BlockMap mapBlockIndex
;
65 CBlockIndex
*pindexBestHeader
= NULL
;
66 int64_t nTimeBestReceived
= 0;
67 CWaitableCriticalSection csBestBlock
;
68 CConditionVariable cvBlockChange
;
69 int nScriptCheckThreads
= 0;
70 bool fImporting
= false;
71 bool fReindex
= false;
72 bool fTxIndex
= false;
73 bool fHavePruned
= false;
74 bool fPruneMode
= false;
75 bool fIsBareMultisigStd
= DEFAULT_PERMIT_BAREMULTISIG
;
76 bool fRequireStandard
= true;
77 bool fCheckBlockIndex
= false;
78 bool fCheckpointsEnabled
= DEFAULT_CHECKPOINTS_ENABLED
;
79 size_t nCoinCacheUsage
= 5000 * 300;
80 uint64_t nPruneTarget
= 0;
81 int64_t nMaxTipAge
= DEFAULT_MAX_TIP_AGE
;
82 bool fEnableReplacement
= DEFAULT_ENABLE_REPLACEMENT
;
85 CFeeRate minRelayTxFee
= CFeeRate(DEFAULT_MIN_RELAY_TX_FEE
);
86 CAmount maxTxFee
= DEFAULT_TRANSACTION_MAXFEE
;
88 CTxMemPool
mempool(::minRelayTxFee
);
89 FeeFilterRounder
filterRounder(::minRelayTxFee
);
91 struct IteratorComparator
94 bool operator()(const I
& a
, const I
& b
)
105 map
<uint256
, COrphanTx
> mapOrphanTransactions
GUARDED_BY(cs_main
);
106 map
<COutPoint
, set
<map
<uint256
, COrphanTx
>::iterator
, IteratorComparator
>> mapOrphanTransactionsByPrev
GUARDED_BY(cs_main
);
107 void EraseOrphansFor(NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
);
109 static void CheckBlockIndex(const Consensus::Params
& consensusParams
);
111 /** Constant stuff for coinbase transactions we create: */
112 CScript COINBASE_FLAGS
;
114 const string strMessageMagic
= "Bitcoin Signed Message:\n";
116 static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY
= 0x3cac0035b5866b90ULL
; // SHA256("main address relay")[0:8]
121 struct CBlockIndexWorkComparator
123 bool operator()(CBlockIndex
*pa
, CBlockIndex
*pb
) const {
124 // First sort by most total work, ...
125 if (pa
->nChainWork
> pb
->nChainWork
) return false;
126 if (pa
->nChainWork
< pb
->nChainWork
) return true;
128 // ... then by earliest time received, ...
129 if (pa
->nSequenceId
< pb
->nSequenceId
) return false;
130 if (pa
->nSequenceId
> pb
->nSequenceId
) return true;
132 // Use pointer address as tie breaker (should only happen with blocks
133 // loaded from disk, as those all have id 0).
134 if (pa
< pb
) return false;
135 if (pa
> pb
) return true;
142 CBlockIndex
*pindexBestInvalid
;
145 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
146 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
147 * missing the data for the block.
149 set
<CBlockIndex
*, CBlockIndexWorkComparator
> setBlockIndexCandidates
;
150 /** Number of nodes with fSyncStarted. */
151 int nSyncStarted
= 0;
152 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
153 * Pruned nodes may have entries where B is missing data.
155 multimap
<CBlockIndex
*, CBlockIndex
*> mapBlocksUnlinked
;
157 CCriticalSection cs_LastBlockFile
;
158 std::vector
<CBlockFileInfo
> vinfoBlockFile
;
159 int nLastBlockFile
= 0;
160 /** Global flag to indicate we should check to see if there are
161 * block/undo files that should be deleted. Set on startup
162 * or if we allocate more file space when we're in prune mode
164 bool fCheckForPruning
= false;
167 * Every received block is assigned a unique and increasing identifier, so we
168 * know which one to give priority in case of a fork.
170 CCriticalSection cs_nBlockSequenceId
;
171 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
172 int32_t nBlockSequenceId
= 1;
173 /** Decreasing counter (used by subsequent preciousblock calls). */
174 int32_t nBlockReverseSequenceId
= -1;
175 /** chainwork for the last block that preciousblock has been applied to. */
176 arith_uint256 nLastPreciousChainwork
= 0;
179 * Sources of received blocks, saved to be able to send them reject
180 * messages or ban them when processing happens afterwards. Protected by
183 map
<uint256
, NodeId
> mapBlockSource
;
186 * Filter for transactions that were recently rejected by
187 * AcceptToMemoryPool. These are not rerequested until the chain tip
188 * changes, at which point the entire filter is reset. Protected by
191 * Without this filter we'd be re-requesting txs from each of our peers,
192 * increasing bandwidth consumption considerably. For instance, with 100
193 * peers, half of which relay a tx we don't accept, that might be a 50x
194 * bandwidth increase. A flooding attacker attempting to roll-over the
195 * filter using minimum-sized, 60byte, transactions might manage to send
196 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
197 * two minute window to send invs to us.
199 * Decreasing the false positive rate is fairly cheap, so we pick one in a
200 * million to make it highly unlikely for users to have issues with this
203 * Memory used: 1.3 MB
205 std::unique_ptr
<CRollingBloomFilter
> recentRejects
;
206 uint256 hashRecentRejectsChainTip
;
208 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
211 CBlockIndex
* pindex
; //!< Optional.
212 bool fValidatedHeaders
; //!< Whether this block has validated headers at the time of request.
213 std::unique_ptr
<PartiallyDownloadedBlock
> partialBlock
; //!< Optional, used for CMPCTBLOCK downloads
215 map
<uint256
, pair
<NodeId
, list
<QueuedBlock
>::iterator
> > mapBlocksInFlight
;
217 /** Stack of nodes which we have set to announce using compact blocks */
218 list
<NodeId
> lNodesAnnouncingHeaderAndIDs
;
220 /** Number of preferable block download peers. */
221 int nPreferredDownload
= 0;
223 /** Dirty block index entries. */
224 set
<CBlockIndex
*> setDirtyBlockIndex
;
226 /** Dirty block file entries. */
227 set
<int> setDirtyFileInfo
;
229 /** Number of peers from which we're downloading blocks. */
230 int nPeersWithValidatedDownloads
= 0;
232 /** Relay map, protected by cs_main. */
233 typedef std::map
<uint256
, std::shared_ptr
<const CTransaction
>> MapRelay
;
235 /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
236 std::deque
<std::pair
<int64_t, MapRelay::iterator
>> vRelayExpiration
;
239 //////////////////////////////////////////////////////////////////////////////
241 // Registration of network node signals.
246 struct CBlockReject
{
247 unsigned char chRejectCode
;
248 string strRejectReason
;
253 * Maintain validation-specific state about nodes, protected by cs_main, instead
254 * by CNode's own locks. This simplifies asynchronous operation, where
255 * processing of incoming data is done after the ProcessMessage call returns,
256 * and we're no longer holding the node's locks.
259 //! The peer's address
261 //! Whether we have a fully established connection.
262 bool fCurrentlyConnected
;
263 //! Accumulated misbehaviour score for this peer.
265 //! Whether this peer should be disconnected and banned (unless whitelisted).
267 //! String name of this peer (debugging/logging purposes).
269 //! List of asynchronously-determined block rejections to notify this peer about.
270 std::vector
<CBlockReject
> rejects
;
271 //! The best known block we know this peer has announced.
272 CBlockIndex
*pindexBestKnownBlock
;
273 //! The hash of the last unknown block this peer has announced.
274 uint256 hashLastUnknownBlock
;
275 //! The last full block we both have.
276 CBlockIndex
*pindexLastCommonBlock
;
277 //! The best header we have sent our peer.
278 CBlockIndex
*pindexBestHeaderSent
;
279 //! Length of current-streak of unconnecting headers announcements
280 int nUnconnectingHeaders
;
281 //! Whether we've started headers synchronization with this peer.
283 //! Since when we're stalling block download progress (in microseconds), or 0.
284 int64_t nStallingSince
;
285 list
<QueuedBlock
> vBlocksInFlight
;
286 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
287 int64_t nDownloadingSince
;
289 int nBlocksInFlightValidHeaders
;
290 //! Whether we consider this a preferred download peer.
291 bool fPreferredDownload
;
292 //! Whether this peer wants invs or headers (when possible) for block announcements.
294 //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
295 bool fPreferHeaderAndIDs
;
297 * Whether this peer will send us cmpctblocks if we request them.
298 * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
299 * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
301 bool fProvidesHeaderAndIDs
;
302 //! Whether this peer can give us witnesses
304 //! Whether this peer wants witnesses in cmpctblocks/blocktxns
305 bool fWantsCmpctWitness
;
307 * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
308 * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
310 bool fSupportsDesiredCmpctVersion
;
313 fCurrentlyConnected
= false;
316 pindexBestKnownBlock
= NULL
;
317 hashLastUnknownBlock
.SetNull();
318 pindexLastCommonBlock
= NULL
;
319 pindexBestHeaderSent
= NULL
;
320 nUnconnectingHeaders
= 0;
321 fSyncStarted
= false;
323 nDownloadingSince
= 0;
325 nBlocksInFlightValidHeaders
= 0;
326 fPreferredDownload
= false;
327 fPreferHeaders
= false;
328 fPreferHeaderAndIDs
= false;
329 fProvidesHeaderAndIDs
= false;
330 fHaveWitness
= false;
331 fWantsCmpctWitness
= false;
332 fSupportsDesiredCmpctVersion
= false;
336 /** Map maintaining per-node state. Requires cs_main. */
337 map
<NodeId
, CNodeState
> mapNodeState
;
340 CNodeState
*State(NodeId pnode
) {
341 map
<NodeId
, CNodeState
>::iterator it
= mapNodeState
.find(pnode
);
342 if (it
== mapNodeState
.end())
347 void UpdatePreferredDownload(CNode
* node
, CNodeState
* state
)
349 nPreferredDownload
-= state
->fPreferredDownload
;
351 // Whether this node should be marked as a preferred download node.
352 state
->fPreferredDownload
= (!node
->fInbound
|| node
->fWhitelisted
) && !node
->fOneShot
&& !node
->fClient
;
354 nPreferredDownload
+= state
->fPreferredDownload
;
357 void InitializeNode(NodeId nodeid
, const CNode
*pnode
) {
359 CNodeState
&state
= mapNodeState
.insert(std::make_pair(nodeid
, CNodeState())).first
->second
;
360 state
.name
= pnode
->addrName
;
361 state
.address
= pnode
->addr
;
364 void FinalizeNode(NodeId nodeid
, bool& fUpdateConnectionTime
) {
365 fUpdateConnectionTime
= false;
367 CNodeState
*state
= State(nodeid
);
369 if (state
->fSyncStarted
)
372 if (state
->nMisbehavior
== 0 && state
->fCurrentlyConnected
) {
373 fUpdateConnectionTime
= true;
376 BOOST_FOREACH(const QueuedBlock
& entry
, state
->vBlocksInFlight
) {
377 mapBlocksInFlight
.erase(entry
.hash
);
379 EraseOrphansFor(nodeid
);
380 nPreferredDownload
-= state
->fPreferredDownload
;
381 nPeersWithValidatedDownloads
-= (state
->nBlocksInFlightValidHeaders
!= 0);
382 assert(nPeersWithValidatedDownloads
>= 0);
384 mapNodeState
.erase(nodeid
);
386 if (mapNodeState
.empty()) {
387 // Do a consistency check after the last peer is removed.
388 assert(mapBlocksInFlight
.empty());
389 assert(nPreferredDownload
== 0);
390 assert(nPeersWithValidatedDownloads
== 0);
395 // Returns a bool indicating whether we requested this block.
396 // Also used if a block was /not/ received and timed out or started with another peer
397 bool MarkBlockAsReceived(const uint256
& hash
) {
398 map
<uint256
, pair
<NodeId
, list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
399 if (itInFlight
!= mapBlocksInFlight
.end()) {
400 CNodeState
*state
= State(itInFlight
->second
.first
);
401 state
->nBlocksInFlightValidHeaders
-= itInFlight
->second
.second
->fValidatedHeaders
;
402 if (state
->nBlocksInFlightValidHeaders
== 0 && itInFlight
->second
.second
->fValidatedHeaders
) {
403 // Last validated block on the queue was received.
404 nPeersWithValidatedDownloads
--;
406 if (state
->vBlocksInFlight
.begin() == itInFlight
->second
.second
) {
407 // First block on the queue was received, update the start download time for the next one
408 state
->nDownloadingSince
= std::max(state
->nDownloadingSince
, GetTimeMicros());
410 state
->vBlocksInFlight
.erase(itInFlight
->second
.second
);
411 state
->nBlocksInFlight
--;
412 state
->nStallingSince
= 0;
413 mapBlocksInFlight
.erase(itInFlight
);
420 // returns false, still setting pit, if the block was already in flight from the same peer
421 // pit will only be valid as long as the same cs_main lock is being held
422 bool MarkBlockAsInFlight(NodeId nodeid
, const uint256
& hash
, const Consensus::Params
& consensusParams
, CBlockIndex
*pindex
= NULL
, list
<QueuedBlock
>::iterator
**pit
= NULL
) {
423 CNodeState
*state
= State(nodeid
);
424 assert(state
!= NULL
);
426 // Short-circuit most stuff in case its from the same node
427 map
<uint256
, pair
<NodeId
, list
<QueuedBlock
>::iterator
> >::iterator itInFlight
= mapBlocksInFlight
.find(hash
);
428 if (itInFlight
!= mapBlocksInFlight
.end() && itInFlight
->second
.first
== nodeid
) {
429 *pit
= &itInFlight
->second
.second
;
433 // Make sure it's not listed somewhere already.
434 MarkBlockAsReceived(hash
);
436 list
<QueuedBlock
>::iterator it
= state
->vBlocksInFlight
.insert(state
->vBlocksInFlight
.end(),
437 {hash
, pindex
, pindex
!= NULL
, std::unique_ptr
<PartiallyDownloadedBlock
>(pit
? new PartiallyDownloadedBlock(&mempool
) : NULL
)});
438 state
->nBlocksInFlight
++;
439 state
->nBlocksInFlightValidHeaders
+= it
->fValidatedHeaders
;
440 if (state
->nBlocksInFlight
== 1) {
441 // We're starting a block download (batch) from this peer.
442 state
->nDownloadingSince
= GetTimeMicros();
444 if (state
->nBlocksInFlightValidHeaders
== 1 && pindex
!= NULL
) {
445 nPeersWithValidatedDownloads
++;
447 itInFlight
= mapBlocksInFlight
.insert(std::make_pair(hash
, std::make_pair(nodeid
, it
))).first
;
449 *pit
= &itInFlight
->second
.second
;
453 /** Check whether the last unknown block a peer advertised is not yet known. */
454 void ProcessBlockAvailability(NodeId nodeid
) {
455 CNodeState
*state
= State(nodeid
);
456 assert(state
!= NULL
);
458 if (!state
->hashLastUnknownBlock
.IsNull()) {
459 BlockMap::iterator itOld
= mapBlockIndex
.find(state
->hashLastUnknownBlock
);
460 if (itOld
!= mapBlockIndex
.end() && itOld
->second
->nChainWork
> 0) {
461 if (state
->pindexBestKnownBlock
== NULL
|| itOld
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
462 state
->pindexBestKnownBlock
= itOld
->second
;
463 state
->hashLastUnknownBlock
.SetNull();
468 /** Update tracking information about which blocks a peer is assumed to have. */
469 void UpdateBlockAvailability(NodeId nodeid
, const uint256
&hash
) {
470 CNodeState
*state
= State(nodeid
);
471 assert(state
!= NULL
);
473 ProcessBlockAvailability(nodeid
);
475 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
476 if (it
!= mapBlockIndex
.end() && it
->second
->nChainWork
> 0) {
477 // An actually better block was announced.
478 if (state
->pindexBestKnownBlock
== NULL
|| it
->second
->nChainWork
>= state
->pindexBestKnownBlock
->nChainWork
)
479 state
->pindexBestKnownBlock
= it
->second
;
481 // An unknown block was announced; just assume that the latest one is the best one.
482 state
->hashLastUnknownBlock
= hash
;
486 void MaybeSetPeerAsAnnouncingHeaderAndIDs(const CNodeState
* nodestate
, CNode
* pfrom
, CConnman
& connman
) {
487 if (!nodestate
->fSupportsDesiredCmpctVersion
) {
488 // Never ask from peers who can't provide witnesses.
491 if (nodestate
->fProvidesHeaderAndIDs
) {
492 for (std::list
<NodeId
>::iterator it
= lNodesAnnouncingHeaderAndIDs
.begin(); it
!= lNodesAnnouncingHeaderAndIDs
.end(); it
++) {
493 if (*it
== pfrom
->GetId()) {
494 lNodesAnnouncingHeaderAndIDs
.erase(it
);
495 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
499 bool fAnnounceUsingCMPCTBLOCK
= false;
500 uint64_t nCMPCTBLOCKVersion
= (pfrom
->GetLocalServices() & NODE_WITNESS
) ? 2 : 1;
501 if (lNodesAnnouncingHeaderAndIDs
.size() >= 3) {
502 // As per BIP152, we only get 3 of our peers to announce
503 // blocks using compact encodings.
504 bool found
= connman
.ForNode(lNodesAnnouncingHeaderAndIDs
.front(), [fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
](CNode
* pnodeStop
){
505 pnodeStop
->PushMessage(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
);
509 lNodesAnnouncingHeaderAndIDs
.pop_front();
511 fAnnounceUsingCMPCTBLOCK
= true;
512 pfrom
->PushMessage(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
);
513 lNodesAnnouncingHeaderAndIDs
.push_back(pfrom
->GetId());
518 bool CanDirectFetch(const Consensus::Params
&consensusParams
)
520 return chainActive
.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams
.nPowTargetSpacing
* 20;
524 bool PeerHasHeader(CNodeState
*state
, CBlockIndex
*pindex
)
526 if (state
->pindexBestKnownBlock
&& pindex
== state
->pindexBestKnownBlock
->GetAncestor(pindex
->nHeight
))
528 if (state
->pindexBestHeaderSent
&& pindex
== state
->pindexBestHeaderSent
->GetAncestor(pindex
->nHeight
))
533 /** Find the last common ancestor two blocks have.
534 * Both pa and pb must be non-NULL. */
535 CBlockIndex
* LastCommonAncestor(CBlockIndex
* pa
, CBlockIndex
* pb
) {
536 if (pa
->nHeight
> pb
->nHeight
) {
537 pa
= pa
->GetAncestor(pb
->nHeight
);
538 } else if (pb
->nHeight
> pa
->nHeight
) {
539 pb
= pb
->GetAncestor(pa
->nHeight
);
542 while (pa
!= pb
&& pa
&& pb
) {
547 // Eventually all chain branches meet at the genesis block.
552 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
553 * at most count entries. */
554 void FindNextBlocksToDownload(NodeId nodeid
, unsigned int count
, std::vector
<CBlockIndex
*>& vBlocks
, NodeId
& nodeStaller
, const Consensus::Params
& consensusParams
) {
558 vBlocks
.reserve(vBlocks
.size() + count
);
559 CNodeState
*state
= State(nodeid
);
560 assert(state
!= NULL
);
562 // Make sure pindexBestKnownBlock is up to date, we'll need it.
563 ProcessBlockAvailability(nodeid
);
565 if (state
->pindexBestKnownBlock
== NULL
|| state
->pindexBestKnownBlock
->nChainWork
< chainActive
.Tip()->nChainWork
) {
566 // This peer has nothing interesting.
570 if (state
->pindexLastCommonBlock
== NULL
) {
571 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
572 // Guessing wrong in either direction is not a problem.
573 state
->pindexLastCommonBlock
= chainActive
[std::min(state
->pindexBestKnownBlock
->nHeight
, chainActive
.Height())];
576 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
577 // of its current tip anymore. Go back enough to fix that.
578 state
->pindexLastCommonBlock
= LastCommonAncestor(state
->pindexLastCommonBlock
, state
->pindexBestKnownBlock
);
579 if (state
->pindexLastCommonBlock
== state
->pindexBestKnownBlock
)
582 std::vector
<CBlockIndex
*> vToFetch
;
583 CBlockIndex
*pindexWalk
= state
->pindexLastCommonBlock
;
584 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
585 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
586 // download that next block if the window were 1 larger.
587 int nWindowEnd
= state
->pindexLastCommonBlock
->nHeight
+ BLOCK_DOWNLOAD_WINDOW
;
588 int nMaxHeight
= std::min
<int>(state
->pindexBestKnownBlock
->nHeight
, nWindowEnd
+ 1);
589 NodeId waitingfor
= -1;
590 while (pindexWalk
->nHeight
< nMaxHeight
) {
591 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
592 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
593 // as iterating over ~100 CBlockIndex* entries anyway.
594 int nToFetch
= std::min(nMaxHeight
- pindexWalk
->nHeight
, std::max
<int>(count
- vBlocks
.size(), 128));
595 vToFetch
.resize(nToFetch
);
596 pindexWalk
= state
->pindexBestKnownBlock
->GetAncestor(pindexWalk
->nHeight
+ nToFetch
);
597 vToFetch
[nToFetch
- 1] = pindexWalk
;
598 for (unsigned int i
= nToFetch
- 1; i
> 0; i
--) {
599 vToFetch
[i
- 1] = vToFetch
[i
]->pprev
;
602 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
603 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
604 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
605 // already part of our chain (and therefore don't need it even if pruned).
606 BOOST_FOREACH(CBlockIndex
* pindex
, vToFetch
) {
607 if (!pindex
->IsValid(BLOCK_VALID_TREE
)) {
608 // We consider the chain that this peer is on invalid.
611 if (!State(nodeid
)->fHaveWitness
&& IsWitnessEnabled(pindex
->pprev
, consensusParams
)) {
612 // We wouldn't download this block or its descendants from this peer.
615 if (pindex
->nStatus
& BLOCK_HAVE_DATA
|| chainActive
.Contains(pindex
)) {
616 if (pindex
->nChainTx
)
617 state
->pindexLastCommonBlock
= pindex
;
618 } else if (mapBlocksInFlight
.count(pindex
->GetBlockHash()) == 0) {
619 // The block is not already downloaded, and not yet in flight.
620 if (pindex
->nHeight
> nWindowEnd
) {
621 // We reached the end of the window.
622 if (vBlocks
.size() == 0 && waitingfor
!= nodeid
) {
623 // We aren't able to fetch anything, but we would be if the download window was one larger.
624 nodeStaller
= waitingfor
;
628 vBlocks
.push_back(pindex
);
629 if (vBlocks
.size() == count
) {
632 } else if (waitingfor
== -1) {
633 // This is the first already-in-flight block.
634 waitingfor
= mapBlocksInFlight
[pindex
->GetBlockHash()].first
;
642 bool GetNodeStateStats(NodeId nodeid
, CNodeStateStats
&stats
) {
644 CNodeState
*state
= State(nodeid
);
647 stats
.nMisbehavior
= state
->nMisbehavior
;
648 stats
.nSyncHeight
= state
->pindexBestKnownBlock
? state
->pindexBestKnownBlock
->nHeight
: -1;
649 stats
.nCommonHeight
= state
->pindexLastCommonBlock
? state
->pindexLastCommonBlock
->nHeight
: -1;
650 BOOST_FOREACH(const QueuedBlock
& queue
, state
->vBlocksInFlight
) {
652 stats
.vHeightInFlight
.push_back(queue
.pindex
->nHeight
);
657 void RegisterNodeSignals(CNodeSignals
& nodeSignals
)
659 nodeSignals
.ProcessMessages
.connect(&ProcessMessages
);
660 nodeSignals
.SendMessages
.connect(&SendMessages
);
661 nodeSignals
.InitializeNode
.connect(&InitializeNode
);
662 nodeSignals
.FinalizeNode
.connect(&FinalizeNode
);
665 void UnregisterNodeSignals(CNodeSignals
& nodeSignals
)
667 nodeSignals
.ProcessMessages
.disconnect(&ProcessMessages
);
668 nodeSignals
.SendMessages
.disconnect(&SendMessages
);
669 nodeSignals
.InitializeNode
.disconnect(&InitializeNode
);
670 nodeSignals
.FinalizeNode
.disconnect(&FinalizeNode
);
673 CBlockIndex
* FindForkInGlobalIndex(const CChain
& chain
, const CBlockLocator
& locator
)
675 // Find the first block the caller has in the main chain
676 BOOST_FOREACH(const uint256
& hash
, locator
.vHave
) {
677 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
678 if (mi
!= mapBlockIndex
.end())
680 CBlockIndex
* pindex
= (*mi
).second
;
681 if (chain
.Contains(pindex
))
683 if (pindex
->GetAncestor(chain
.Height()) == chain
.Tip()) {
688 return chain
.Genesis();
691 CCoinsViewCache
*pcoinsTip
= NULL
;
692 CBlockTreeDB
*pblocktree
= NULL
;
694 //////////////////////////////////////////////////////////////////////////////
696 // mapOrphanTransactions
699 bool AddOrphanTx(const CTransaction
& tx
, NodeId peer
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
701 uint256 hash
= tx
.GetHash();
702 if (mapOrphanTransactions
.count(hash
))
705 // Ignore big transactions, to avoid a
706 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
707 // large transaction with a missing parent then we assume
708 // it will rebroadcast it later, after the parent transaction(s)
709 // have been mined or received.
710 // 100 orphans, each of which is at most 99,999 bytes big is
711 // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
712 unsigned int sz
= GetTransactionWeight(tx
);
713 if (sz
>= MAX_STANDARD_TX_WEIGHT
)
715 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz
, hash
.ToString());
719 auto ret
= mapOrphanTransactions
.emplace(hash
, COrphanTx
{tx
, peer
, GetTime() + ORPHAN_TX_EXPIRE_TIME
});
721 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
722 mapOrphanTransactionsByPrev
[txin
.prevout
].insert(ret
.first
);
725 LogPrint("mempool", "stored orphan tx %s (mapsz %u outsz %u)\n", hash
.ToString(),
726 mapOrphanTransactions
.size(), mapOrphanTransactionsByPrev
.size());
730 int static EraseOrphanTx(uint256 hash
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
732 map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.find(hash
);
733 if (it
== mapOrphanTransactions
.end())
735 BOOST_FOREACH(const CTxIn
& txin
, it
->second
.tx
.vin
)
737 auto itPrev
= mapOrphanTransactionsByPrev
.find(txin
.prevout
);
738 if (itPrev
== mapOrphanTransactionsByPrev
.end())
740 itPrev
->second
.erase(it
);
741 if (itPrev
->second
.empty())
742 mapOrphanTransactionsByPrev
.erase(itPrev
);
744 mapOrphanTransactions
.erase(it
);
748 void EraseOrphansFor(NodeId peer
)
751 map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
752 while (iter
!= mapOrphanTransactions
.end())
754 map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++; // increment to avoid iterator becoming invalid
755 if (maybeErase
->second
.fromPeer
== peer
)
757 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
.GetHash());
760 if (nErased
> 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased
, peer
);
764 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
766 unsigned int nEvicted
= 0;
767 static int64_t nNextSweep
;
768 int64_t nNow
= GetTime();
769 if (nNextSweep
<= nNow
) {
770 // Sweep out expired orphan pool entries:
772 int64_t nMinExpTime
= nNow
+ ORPHAN_TX_EXPIRE_TIME
- ORPHAN_TX_EXPIRE_INTERVAL
;
773 map
<uint256
, COrphanTx
>::iterator iter
= mapOrphanTransactions
.begin();
774 while (iter
!= mapOrphanTransactions
.end())
776 map
<uint256
, COrphanTx
>::iterator maybeErase
= iter
++;
777 if (maybeErase
->second
.nTimeExpire
<= nNow
) {
778 nErased
+= EraseOrphanTx(maybeErase
->second
.tx
.GetHash());
780 nMinExpTime
= std::min(maybeErase
->second
.nTimeExpire
, nMinExpTime
);
783 // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
784 nNextSweep
= nMinExpTime
+ ORPHAN_TX_EXPIRE_INTERVAL
;
785 if (nErased
> 0) LogPrint("mempool", "Erased %d orphan tx due to expiration\n", nErased
);
787 while (mapOrphanTransactions
.size() > nMaxOrphans
)
789 // Evict a random orphan:
790 uint256 randomhash
= GetRandHash();
791 map
<uint256
, COrphanTx
>::iterator it
= mapOrphanTransactions
.lower_bound(randomhash
);
792 if (it
== mapOrphanTransactions
.end())
793 it
= mapOrphanTransactions
.begin();
794 EraseOrphanTx(it
->first
);
800 bool IsFinalTx(const CTransaction
&tx
, int nBlockHeight
, int64_t nBlockTime
)
802 if (tx
.nLockTime
== 0)
804 if ((int64_t)tx
.nLockTime
< ((int64_t)tx
.nLockTime
< LOCKTIME_THRESHOLD
? (int64_t)nBlockHeight
: nBlockTime
))
806 for (const auto& txin
: tx
.vin
) {
807 if (!(txin
.nSequence
== CTxIn::SEQUENCE_FINAL
))
813 bool CheckFinalTx(const CTransaction
&tx
, int flags
)
815 AssertLockHeld(cs_main
);
817 // By convention a negative value for flags indicates that the
818 // current network-enforced consensus rules should be used. In
819 // a future soft-fork scenario that would mean checking which
820 // rules would be enforced for the next block and setting the
821 // appropriate flags. At the present time no soft-forks are
822 // scheduled, so no flags are set.
823 flags
= std::max(flags
, 0);
825 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
826 // nLockTime because when IsFinalTx() is called within
827 // CBlock::AcceptBlock(), the height of the block *being*
828 // evaluated is what is used. Thus if we want to know if a
829 // transaction can be part of the *next* block, we need to call
830 // IsFinalTx() with one more than chainActive.Height().
831 const int nBlockHeight
= chainActive
.Height() + 1;
833 // BIP113 will require that time-locked transactions have nLockTime set to
834 // less than the median time of the previous block they're contained in.
835 // When the next block is created its previous block will be the current
836 // chain tip, so we use that to calculate the median time passed to
837 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
838 const int64_t nBlockTime
= (flags
& LOCKTIME_MEDIAN_TIME_PAST
)
839 ? chainActive
.Tip()->GetMedianTimePast()
842 return IsFinalTx(tx
, nBlockHeight
, nBlockTime
);
846 * Calculates the block height and previous block's median time past at
847 * which the transaction will be considered final in the context of BIP 68.
848 * Also removes from the vector of input heights any entries which did not
849 * correspond to sequence locked inputs as they do not affect the calculation.
851 static std::pair
<int, int64_t> CalculateSequenceLocks(const CTransaction
&tx
, int flags
, std::vector
<int>* prevHeights
, const CBlockIndex
& block
)
853 assert(prevHeights
->size() == tx
.vin
.size());
855 // Will be set to the equivalent height- and time-based nLockTime
856 // values that would be necessary to satisfy all relative lock-
857 // time constraints given our view of block chain history.
858 // The semantics of nLockTime are the last invalid height/time, so
859 // use -1 to have the effect of any height or time being valid.
861 int64_t nMinTime
= -1;
863 // tx.nVersion is signed integer so requires cast to unsigned otherwise
864 // we would be doing a signed comparison and half the range of nVersion
865 // wouldn't support BIP 68.
866 bool fEnforceBIP68
= static_cast<uint32_t>(tx
.nVersion
) >= 2
867 && flags
& LOCKTIME_VERIFY_SEQUENCE
;
869 // Do not enforce sequence numbers as a relative lock time
870 // unless we have been instructed to
871 if (!fEnforceBIP68
) {
872 return std::make_pair(nMinHeight
, nMinTime
);
875 for (size_t txinIndex
= 0; txinIndex
< tx
.vin
.size(); txinIndex
++) {
876 const CTxIn
& txin
= tx
.vin
[txinIndex
];
878 // Sequence numbers with the most significant bit set are not
879 // treated as relative lock-times, nor are they given any
880 // consensus-enforced meaning at this point.
881 if (txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG
) {
882 // The height of this input is not relevant for sequence locks
883 (*prevHeights
)[txinIndex
] = 0;
887 int nCoinHeight
= (*prevHeights
)[txinIndex
];
889 if (txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG
) {
890 int64_t nCoinTime
= block
.GetAncestor(std::max(nCoinHeight
-1, 0))->GetMedianTimePast();
891 // NOTE: Subtract 1 to maintain nLockTime semantics
892 // BIP 68 relative lock times have the semantics of calculating
893 // the first block or time at which the transaction would be
894 // valid. When calculating the effective block time or height
895 // for the entire transaction, we switch to using the
896 // semantics of nLockTime which is the last invalid block
897 // time or height. Thus we subtract 1 from the calculated
900 // Time-based relative lock-times are measured from the
901 // smallest allowed timestamp of the block containing the
902 // txout being spent, which is the median time past of the
904 nMinTime
= std::max(nMinTime
, nCoinTime
+ (int64_t)((txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_MASK
) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY
) - 1);
906 nMinHeight
= std::max(nMinHeight
, nCoinHeight
+ (int)(txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_MASK
) - 1);
910 return std::make_pair(nMinHeight
, nMinTime
);
913 static bool EvaluateSequenceLocks(const CBlockIndex
& block
, std::pair
<int, int64_t> lockPair
)
916 int64_t nBlockTime
= block
.pprev
->GetMedianTimePast();
917 if (lockPair
.first
>= block
.nHeight
|| lockPair
.second
>= nBlockTime
)
923 bool SequenceLocks(const CTransaction
&tx
, int flags
, std::vector
<int>* prevHeights
, const CBlockIndex
& block
)
925 return EvaluateSequenceLocks(block
, CalculateSequenceLocks(tx
, flags
, prevHeights
, block
));
928 bool TestLockPointValidity(const LockPoints
* lp
)
930 AssertLockHeld(cs_main
);
932 // If there are relative lock times then the maxInputBlock will be set
933 // If there are no relative lock times, the LockPoints don't depend on the chain
934 if (lp
->maxInputBlock
) {
935 // Check whether chainActive is an extension of the block at which the LockPoints
936 // calculation was valid. If not LockPoints are no longer valid
937 if (!chainActive
.Contains(lp
->maxInputBlock
)) {
942 // LockPoints still valid
946 bool CheckSequenceLocks(const CTransaction
&tx
, int flags
, LockPoints
* lp
, bool useExistingLockPoints
)
948 AssertLockHeld(cs_main
);
949 AssertLockHeld(mempool
.cs
);
951 CBlockIndex
* tip
= chainActive
.Tip();
954 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
955 // height based locks because when SequenceLocks() is called within
956 // ConnectBlock(), the height of the block *being*
957 // evaluated is what is used.
958 // Thus if we want to know if a transaction can be part of the
959 // *next* block, we need to use one more than chainActive.Height()
960 index
.nHeight
= tip
->nHeight
+ 1;
962 std::pair
<int, int64_t> lockPair
;
963 if (useExistingLockPoints
) {
965 lockPair
.first
= lp
->height
;
966 lockPair
.second
= lp
->time
;
969 // pcoinsTip contains the UTXO set for chainActive.Tip()
970 CCoinsViewMemPool
viewMemPool(pcoinsTip
, mempool
);
971 std::vector
<int> prevheights
;
972 prevheights
.resize(tx
.vin
.size());
973 for (size_t txinIndex
= 0; txinIndex
< tx
.vin
.size(); txinIndex
++) {
974 const CTxIn
& txin
= tx
.vin
[txinIndex
];
976 if (!viewMemPool
.GetCoins(txin
.prevout
.hash
, coins
)) {
977 return error("%s: Missing input", __func__
);
979 if (coins
.nHeight
== MEMPOOL_HEIGHT
) {
980 // Assume all mempool transaction confirm in the next block
981 prevheights
[txinIndex
] = tip
->nHeight
+ 1;
983 prevheights
[txinIndex
] = coins
.nHeight
;
986 lockPair
= CalculateSequenceLocks(tx
, flags
, &prevheights
, index
);
988 lp
->height
= lockPair
.first
;
989 lp
->time
= lockPair
.second
;
990 // Also store the hash of the block with the highest height of
991 // all the blocks which have sequence locked prevouts.
992 // This hash needs to still be on the chain
993 // for these LockPoint calculations to be valid
994 // Note: It is impossible to correctly calculate a maxInputBlock
995 // if any of the sequence locked inputs depend on unconfirmed txs,
996 // except in the special case where the relative lock time/height
997 // is 0, which is equivalent to no sequence lock. Since we assume
998 // input height of tip+1 for mempool txs and test the resulting
999 // lockPair from CalculateSequenceLocks against tip+1. We know
1000 // EvaluateSequenceLocks will fail if there was a non-zero sequence
1001 // lock on a mempool input, so we can use the return value of
1002 // CheckSequenceLocks to indicate the LockPoints validity
1003 int maxInputHeight
= 0;
1004 BOOST_FOREACH(int height
, prevheights
) {
1005 // Can ignore mempool inputs since we'll fail if they had non-zero locks
1006 if (height
!= tip
->nHeight
+1) {
1007 maxInputHeight
= std::max(maxInputHeight
, height
);
1010 lp
->maxInputBlock
= tip
->GetAncestor(maxInputHeight
);
1013 return EvaluateSequenceLocks(index
, lockPair
);
1017 unsigned int GetLegacySigOpCount(const CTransaction
& tx
)
1019 unsigned int nSigOps
= 0;
1020 for (const auto& txin
: tx
.vin
)
1022 nSigOps
+= txin
.scriptSig
.GetSigOpCount(false);
1024 for (const auto& txout
: tx
.vout
)
1026 nSigOps
+= txout
.scriptPubKey
.GetSigOpCount(false);
1031 unsigned int GetP2SHSigOpCount(const CTransaction
& tx
, const CCoinsViewCache
& inputs
)
1033 if (tx
.IsCoinBase())
1036 unsigned int nSigOps
= 0;
1037 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
1039 const CTxOut
&prevout
= inputs
.GetOutputFor(tx
.vin
[i
]);
1040 if (prevout
.scriptPubKey
.IsPayToScriptHash())
1041 nSigOps
+= prevout
.scriptPubKey
.GetSigOpCount(tx
.vin
[i
].scriptSig
);
1046 int64_t GetTransactionSigOpCost(const CTransaction
& tx
, const CCoinsViewCache
& inputs
, int flags
)
1048 int64_t nSigOps
= GetLegacySigOpCount(tx
) * WITNESS_SCALE_FACTOR
;
1050 if (tx
.IsCoinBase())
1053 if (flags
& SCRIPT_VERIFY_P2SH
) {
1054 nSigOps
+= GetP2SHSigOpCount(tx
, inputs
) * WITNESS_SCALE_FACTOR
;
1057 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
1059 const CTxOut
&prevout
= inputs
.GetOutputFor(tx
.vin
[i
]);
1060 nSigOps
+= CountWitnessSigOps(tx
.vin
[i
].scriptSig
, prevout
.scriptPubKey
, i
< tx
.wit
.vtxinwit
.size() ? &tx
.wit
.vtxinwit
[i
].scriptWitness
: NULL
, flags
);
1069 bool CheckTransaction(const CTransaction
& tx
, CValidationState
&state
)
1071 // Basic checks that don't depend on any context
1073 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-vin-empty");
1074 if (tx
.vout
.empty())
1075 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-vout-empty");
1076 // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
1077 if (::GetSerializeSize(tx
, SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
) > MAX_BLOCK_BASE_SIZE
)
1078 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-oversize");
1080 // Check for negative or overflow output values
1081 CAmount nValueOut
= 0;
1082 for (const auto& txout
: tx
.vout
)
1084 if (txout
.nValue
< 0)
1085 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-vout-negative");
1086 if (txout
.nValue
> MAX_MONEY
)
1087 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-vout-toolarge");
1088 nValueOut
+= txout
.nValue
;
1089 if (!MoneyRange(nValueOut
))
1090 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-txouttotal-toolarge");
1093 // Check for duplicate inputs
1094 set
<COutPoint
> vInOutPoints
;
1095 for (const auto& txin
: tx
.vin
)
1097 if (vInOutPoints
.count(txin
.prevout
))
1098 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-inputs-duplicate");
1099 vInOutPoints
.insert(txin
.prevout
);
1102 if (tx
.IsCoinBase())
1104 if (tx
.vin
[0].scriptSig
.size() < 2 || tx
.vin
[0].scriptSig
.size() > 100)
1105 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-length");
1109 for (const auto& txin
: tx
.vin
)
1110 if (txin
.prevout
.IsNull())
1111 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-prevout-null");
1117 void LimitMempoolSize(CTxMemPool
& pool
, size_t limit
, unsigned long age
) {
1118 int expired
= pool
.Expire(GetTime() - age
);
1120 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired
);
1122 std::vector
<uint256
> vNoSpendsRemaining
;
1123 pool
.TrimToSize(limit
, &vNoSpendsRemaining
);
1124 BOOST_FOREACH(const uint256
& removed
, vNoSpendsRemaining
)
1125 pcoinsTip
->Uncache(removed
);
1128 /** Convert CValidationState to a human-readable message for logging */
1129 std::string
FormatStateMessage(const CValidationState
&state
)
1131 return strprintf("%s%s (code %i)",
1132 state
.GetRejectReason(),
1133 state
.GetDebugMessage().empty() ? "" : ", "+state
.GetDebugMessage(),
1134 state
.GetRejectCode());
1137 bool AcceptToMemoryPoolWorker(CTxMemPool
& pool
, CValidationState
& state
, const CTransaction
& tx
, bool fLimitFree
,
1138 bool* pfMissingInputs
, bool fOverrideMempoolLimit
, const CAmount
& nAbsurdFee
,
1139 std::vector
<uint256
>& vHashTxnToUncache
)
1141 const uint256 hash
= tx
.GetHash();
1142 AssertLockHeld(cs_main
);
1143 if (pfMissingInputs
)
1144 *pfMissingInputs
= false;
1146 if (!CheckTransaction(tx
, state
))
1147 return false; // state filled in by CheckTransaction
1149 // Coinbase is only valid in a block, not as a loose transaction
1150 if (tx
.IsCoinBase())
1151 return state
.DoS(100, false, REJECT_INVALID
, "coinbase");
1153 // Don't relay version 2 transactions until CSV is active, and we can be
1154 // sure that such transactions will be mined (unless we're on
1155 // -testnet/-regtest).
1156 const CChainParams
& chainparams
= Params();
1157 if (fRequireStandard
&& tx
.nVersion
>= 2 && VersionBitsTipState(chainparams
.GetConsensus(), Consensus::DEPLOYMENT_CSV
) != THRESHOLD_ACTIVE
) {
1158 return state
.DoS(0, false, REJECT_NONSTANDARD
, "premature-version2-tx");
1161 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
1162 bool witnessEnabled
= IsWitnessEnabled(chainActive
.Tip(), Params().GetConsensus());
1163 if (!GetBoolArg("-prematurewitness",false) && !tx
.wit
.IsNull() && !witnessEnabled
) {
1164 return state
.DoS(0, false, REJECT_NONSTANDARD
, "no-witness-yet", true);
1167 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1169 if (fRequireStandard
&& !IsStandardTx(tx
, reason
, witnessEnabled
))
1170 return state
.DoS(0, false, REJECT_NONSTANDARD
, reason
);
1172 // Only accept nLockTime-using transactions that can be mined in the next
1173 // block; we don't want our mempool filled up with transactions that can't
1175 if (!CheckFinalTx(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
))
1176 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-final");
1178 // is it already in the memory pool?
1179 if (pool
.exists(hash
))
1180 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-in-mempool");
1182 // Check for conflicts with in-memory transactions
1183 set
<uint256
> setConflicts
;
1185 LOCK(pool
.cs
); // protect pool.mapNextTx
1186 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
)
1188 auto itConflicting
= pool
.mapNextTx
.find(txin
.prevout
);
1189 if (itConflicting
!= pool
.mapNextTx
.end())
1191 const CTransaction
*ptxConflicting
= itConflicting
->second
;
1192 if (!setConflicts
.count(ptxConflicting
->GetHash()))
1194 // Allow opt-out of transaction replacement by setting
1195 // nSequence >= maxint-1 on all inputs.
1197 // maxint-1 is picked to still allow use of nLockTime by
1198 // non-replaceable transactions. All inputs rather than just one
1199 // is for the sake of multi-party protocols, where we don't
1200 // want a single party to be able to disable replacement.
1202 // The opt-out ignores descendants as anyone relying on
1203 // first-seen mempool behavior should be checking all
1204 // unconfirmed ancestors anyway; doing otherwise is hopelessly
1206 bool fReplacementOptOut
= true;
1207 if (fEnableReplacement
)
1209 BOOST_FOREACH(const CTxIn
&_txin
, ptxConflicting
->vin
)
1211 if (_txin
.nSequence
< std::numeric_limits
<unsigned int>::max()-1)
1213 fReplacementOptOut
= false;
1218 if (fReplacementOptOut
)
1219 return state
.Invalid(false, REJECT_CONFLICT
, "txn-mempool-conflict");
1221 setConflicts
.insert(ptxConflicting
->GetHash());
1229 CCoinsViewCache
view(&dummy
);
1231 CAmount nValueIn
= 0;
1235 CCoinsViewMemPool
viewMemPool(pcoinsTip
, pool
);
1236 view
.SetBackend(viewMemPool
);
1238 // do we already have it?
1239 bool fHadTxInCache
= pcoinsTip
->HaveCoinsInCache(hash
);
1240 if (view
.HaveCoins(hash
)) {
1242 vHashTxnToUncache
.push_back(hash
);
1243 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-known");
1246 // do all inputs exist?
1247 // Note that this does not check for the presence of actual outputs (see the next check for that),
1248 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1249 BOOST_FOREACH(const CTxIn txin
, tx
.vin
) {
1250 if (!pcoinsTip
->HaveCoinsInCache(txin
.prevout
.hash
))
1251 vHashTxnToUncache
.push_back(txin
.prevout
.hash
);
1252 if (!view
.HaveCoins(txin
.prevout
.hash
)) {
1253 if (pfMissingInputs
)
1254 *pfMissingInputs
= true;
1255 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
1259 // are the actual inputs available?
1260 if (!view
.HaveInputs(tx
))
1261 return state
.Invalid(false, REJECT_DUPLICATE
, "bad-txns-inputs-spent");
1263 // Bring the best block into scope
1264 view
.GetBestBlock();
1266 nValueIn
= view
.GetValueIn(tx
);
1268 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1269 view
.SetBackend(dummy
);
1271 // Only accept BIP68 sequence locked transactions that can be mined in the next
1272 // block; we don't want our mempool filled up with transactions that can't
1274 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
1275 // CoinsViewCache instead of create its own
1276 if (!CheckSequenceLocks(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
, &lp
))
1277 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-BIP68-final");
1280 // Check for non-standard pay-to-script-hash in inputs
1281 if (fRequireStandard
&& !AreInputsStandard(tx
, view
))
1282 return state
.Invalid(false, REJECT_NONSTANDARD
, "bad-txns-nonstandard-inputs");
1284 // Check for non-standard witness in P2WSH
1285 if (!tx
.wit
.IsNull() && fRequireStandard
&& !IsWitnessStandard(tx
, view
))
1286 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-witness-nonstandard", true);
1288 int64_t nSigOpsCost
= GetTransactionSigOpCost(tx
, view
, STANDARD_SCRIPT_VERIFY_FLAGS
);
1290 CAmount nValueOut
= tx
.GetValueOut();
1291 CAmount nFees
= nValueIn
-nValueOut
;
1292 // nModifiedFees includes any fee deltas from PrioritiseTransaction
1293 CAmount nModifiedFees
= nFees
;
1294 double nPriorityDummy
= 0;
1295 pool
.ApplyDeltas(hash
, nPriorityDummy
, nModifiedFees
);
1297 CAmount inChainInputValue
;
1298 double dPriority
= view
.GetPriority(tx
, chainActive
.Height(), inChainInputValue
);
1300 // Keep track of transactions that spend a coinbase, which we re-scan
1301 // during reorgs to ensure COINBASE_MATURITY is still met.
1302 bool fSpendsCoinbase
= false;
1303 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
) {
1304 const CCoins
*coins
= view
.AccessCoins(txin
.prevout
.hash
);
1305 if (coins
->IsCoinBase()) {
1306 fSpendsCoinbase
= true;
1311 CTxMemPoolEntry
entry(tx
, nFees
, GetTime(), dPriority
, chainActive
.Height(), pool
.HasNoInputsOf(tx
), inChainInputValue
, fSpendsCoinbase
, nSigOpsCost
, lp
);
1312 unsigned int nSize
= entry
.GetTxSize();
1314 // Check that the transaction doesn't have an excessive number of
1315 // sigops, making it impossible to mine. Since the coinbase transaction
1316 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1317 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1318 // merely non-standard transaction.
1319 if (nSigOpsCost
> MAX_STANDARD_TX_SIGOPS_COST
)
1320 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-txns-too-many-sigops", false,
1321 strprintf("%d", nSigOpsCost
));
1323 CAmount mempoolRejectFee
= pool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFee(nSize
);
1324 if (mempoolRejectFee
> 0 && nModifiedFees
< mempoolRejectFee
) {
1325 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool min fee not met", false, strprintf("%d < %d", nFees
, mempoolRejectFee
));
1326 } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY
) && nModifiedFees
< ::minRelayTxFee
.GetFee(nSize
) && !AllowFree(entry
.GetPriority(chainActive
.Height() + 1))) {
1327 // Require that free transactions have sufficient priority to be mined in the next block.
1328 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "insufficient priority");
1331 // Continuously rate-limit free (really, very-low-fee) transactions
1332 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1333 // be annoying or make others' transactions take longer to confirm.
1334 if (fLimitFree
&& nModifiedFees
< ::minRelayTxFee
.GetFee(nSize
))
1336 static CCriticalSection csFreeLimiter
;
1337 static double dFreeCount
;
1338 static int64_t nLastTime
;
1339 int64_t nNow
= GetTime();
1341 LOCK(csFreeLimiter
);
1343 // Use an exponentially decaying ~10-minute window:
1344 dFreeCount
*= pow(1.0 - 1.0/600.0, (double)(nNow
- nLastTime
));
1346 // -limitfreerelay unit is thousand-bytes-per-minute
1347 // At default rate it would take over a month to fill 1GB
1348 if (dFreeCount
+ nSize
>= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY
) * 10 * 1000)
1349 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "rate limited free transaction");
1350 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount
, dFreeCount
+nSize
);
1351 dFreeCount
+= nSize
;
1354 if (nAbsurdFee
&& nFees
> nAbsurdFee
)
1355 return state
.Invalid(false,
1356 REJECT_HIGHFEE
, "absurdly-high-fee",
1357 strprintf("%d > %d", nFees
, nAbsurdFee
));
1359 // Calculate in-mempool ancestors, up to a limit.
1360 CTxMemPool::setEntries setAncestors
;
1361 size_t nLimitAncestors
= GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
1362 size_t nLimitAncestorSize
= GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
1363 size_t nLimitDescendants
= GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
1364 size_t nLimitDescendantSize
= GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
1365 std::string errString
;
1366 if (!pool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
1367 return state
.DoS(0, false, REJECT_NONSTANDARD
, "too-long-mempool-chain", false, errString
);
1370 // A transaction that spends outputs that would be replaced by it is invalid. Now
1371 // that we have the set of all ancestors we can detect this
1372 // pathological case by making sure setConflicts and setAncestors don't
1374 BOOST_FOREACH(CTxMemPool::txiter ancestorIt
, setAncestors
)
1376 const uint256
&hashAncestor
= ancestorIt
->GetTx().GetHash();
1377 if (setConflicts
.count(hashAncestor
))
1379 return state
.DoS(10, false,
1380 REJECT_INVALID
, "bad-txns-spends-conflicting-tx", false,
1381 strprintf("%s spends conflicting transaction %s",
1383 hashAncestor
.ToString()));
1387 // Check if it's economically rational to mine this transaction rather
1388 // than the ones it replaces.
1389 CAmount nConflictingFees
= 0;
1390 size_t nConflictingSize
= 0;
1391 uint64_t nConflictingCount
= 0;
1392 CTxMemPool::setEntries allConflicting
;
1394 // If we don't hold the lock allConflicting might be incomplete; the
1395 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
1396 // mempool consistency for us.
1398 if (setConflicts
.size())
1400 CFeeRate
newFeeRate(nModifiedFees
, nSize
);
1401 set
<uint256
> setConflictsParents
;
1402 const int maxDescendantsToVisit
= 100;
1403 CTxMemPool::setEntries setIterConflicting
;
1404 BOOST_FOREACH(const uint256
&hashConflicting
, setConflicts
)
1406 CTxMemPool::txiter mi
= pool
.mapTx
.find(hashConflicting
);
1407 if (mi
== pool
.mapTx
.end())
1410 // Save these to avoid repeated lookups
1411 setIterConflicting
.insert(mi
);
1413 // Don't allow the replacement to reduce the feerate of the
1416 // We usually don't want to accept replacements with lower
1417 // feerates than what they replaced as that would lower the
1418 // feerate of the next block. Requiring that the feerate always
1419 // be increased is also an easy-to-reason about way to prevent
1420 // DoS attacks via replacements.
1422 // The mining code doesn't (currently) take children into
1423 // account (CPFP) so we only consider the feerates of
1424 // transactions being directly replaced, not their indirect
1425 // descendants. While that does mean high feerate children are
1426 // ignored when deciding whether or not to replace, we do
1427 // require the replacement to pay more overall fees too,
1428 // mitigating most cases.
1429 CFeeRate
oldFeeRate(mi
->GetModifiedFee(), mi
->GetTxSize());
1430 if (newFeeRate
<= oldFeeRate
)
1432 return state
.DoS(0, false,
1433 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
1434 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
1436 newFeeRate
.ToString(),
1437 oldFeeRate
.ToString()));
1440 BOOST_FOREACH(const CTxIn
&txin
, mi
->GetTx().vin
)
1442 setConflictsParents
.insert(txin
.prevout
.hash
);
1445 nConflictingCount
+= mi
->GetCountWithDescendants();
1447 // This potentially overestimates the number of actual descendants
1448 // but we just want to be conservative to avoid doing too much
1450 if (nConflictingCount
<= maxDescendantsToVisit
) {
1451 // If not too many to replace, then calculate the set of
1452 // transactions that would have to be evicted
1453 BOOST_FOREACH(CTxMemPool::txiter it
, setIterConflicting
) {
1454 pool
.CalculateDescendants(it
, allConflicting
);
1456 BOOST_FOREACH(CTxMemPool::txiter it
, allConflicting
) {
1457 nConflictingFees
+= it
->GetModifiedFee();
1458 nConflictingSize
+= it
->GetTxSize();
1461 return state
.DoS(0, false,
1462 REJECT_NONSTANDARD
, "too many potential replacements", false,
1463 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
1466 maxDescendantsToVisit
));
1469 for (unsigned int j
= 0; j
< tx
.vin
.size(); j
++)
1471 // We don't want to accept replacements that require low
1472 // feerate junk to be mined first. Ideally we'd keep track of
1473 // the ancestor feerates and make the decision based on that,
1474 // but for now requiring all new inputs to be confirmed works.
1475 if (!setConflictsParents
.count(tx
.vin
[j
].prevout
.hash
))
1477 // Rather than check the UTXO set - potentially expensive -
1478 // it's cheaper to just check if the new input refers to a
1479 // tx that's in the mempool.
1480 if (pool
.mapTx
.find(tx
.vin
[j
].prevout
.hash
) != pool
.mapTx
.end())
1481 return state
.DoS(0, false,
1482 REJECT_NONSTANDARD
, "replacement-adds-unconfirmed", false,
1483 strprintf("replacement %s adds unconfirmed input, idx %d",
1484 hash
.ToString(), j
));
1488 // The replacement must pay greater fees than the transactions it
1489 // replaces - if we did the bandwidth used by those conflicting
1490 // transactions would not be paid for.
1491 if (nModifiedFees
< nConflictingFees
)
1493 return state
.DoS(0, false,
1494 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
1495 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
1496 hash
.ToString(), FormatMoney(nModifiedFees
), FormatMoney(nConflictingFees
)));
1499 // Finally in addition to paying more fees than the conflicts the
1500 // new transaction must pay for its own bandwidth.
1501 CAmount nDeltaFees
= nModifiedFees
- nConflictingFees
;
1502 if (nDeltaFees
< ::minRelayTxFee
.GetFee(nSize
))
1504 return state
.DoS(0, false,
1505 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
1506 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
1508 FormatMoney(nDeltaFees
),
1509 FormatMoney(::minRelayTxFee
.GetFee(nSize
))));
1513 unsigned int scriptVerifyFlags
= STANDARD_SCRIPT_VERIFY_FLAGS
;
1514 if (!Params().RequireStandard()) {
1515 scriptVerifyFlags
= GetArg("-promiscuousmempoolflags", scriptVerifyFlags
);
1518 // Check against previous transactions
1519 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1520 PrecomputedTransactionData
txdata(tx
);
1521 if (!CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
, true, txdata
)) {
1522 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
1523 // need to turn both off, and compare against just turning off CLEANSTACK
1524 // to see if the failure is specifically due to witness validation.
1525 if (tx
.wit
.IsNull() && CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
& ~(SCRIPT_VERIFY_WITNESS
| SCRIPT_VERIFY_CLEANSTACK
), true, txdata
) &&
1526 !CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
& ~SCRIPT_VERIFY_CLEANSTACK
, true, txdata
)) {
1527 // Only the witness is missing, so the transaction itself may be fine.
1528 state
.SetCorruptionPossible();
1533 // Check again against just the consensus-critical mandatory script
1534 // verification flags, in case of bugs in the standard flags that cause
1535 // transactions to pass as valid when they're actually invalid. For
1536 // instance the STRICTENC flag was incorrectly allowing certain
1537 // CHECKSIG NOT scripts to pass, even though they were invalid.
1539 // There is a similar check in CreateNewBlock() to prevent creating
1540 // invalid blocks, however allowing such transactions into the mempool
1541 // can be exploited as a DoS attack.
1542 if (!CheckInputs(tx
, state
, view
, true, MANDATORY_SCRIPT_VERIFY_FLAGS
, true, txdata
))
1544 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
1545 __func__
, hash
.ToString(), FormatStateMessage(state
));
1548 // Remove conflicting transactions from the mempool
1549 BOOST_FOREACH(const CTxMemPool::txiter it
, allConflicting
)
1551 LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
1552 it
->GetTx().GetHash().ToString(),
1554 FormatMoney(nModifiedFees
- nConflictingFees
),
1555 (int)nSize
- (int)nConflictingSize
);
1557 pool
.RemoveStaged(allConflicting
, false);
1559 // Store transaction in memory
1560 pool
.addUnchecked(hash
, entry
, setAncestors
, !IsInitialBlockDownload());
1562 // trim mempool and check if tx was trimmed
1563 if (!fOverrideMempoolLimit
) {
1564 LimitMempoolSize(pool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
1565 if (!pool
.exists(hash
))
1566 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool full");
1570 GetMainSignals().SyncTransaction(tx
, NULL
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
1575 bool AcceptToMemoryPool(CTxMemPool
& pool
, CValidationState
&state
, const CTransaction
&tx
, bool fLimitFree
,
1576 bool* pfMissingInputs
, bool fOverrideMempoolLimit
, const CAmount nAbsurdFee
)
1578 std::vector
<uint256
> vHashTxToUncache
;
1579 bool res
= AcceptToMemoryPoolWorker(pool
, state
, tx
, fLimitFree
, pfMissingInputs
, fOverrideMempoolLimit
, nAbsurdFee
, vHashTxToUncache
);
1581 BOOST_FOREACH(const uint256
& hashTx
, vHashTxToUncache
)
1582 pcoinsTip
->Uncache(hashTx
);
1587 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1588 bool GetTransaction(const uint256
&hash
, CTransaction
&txOut
, const Consensus::Params
& consensusParams
, uint256
&hashBlock
, bool fAllowSlow
)
1590 CBlockIndex
*pindexSlow
= NULL
;
1594 std::shared_ptr
<const CTransaction
> ptx
= mempool
.get(hash
);
1603 if (pblocktree
->ReadTxIndex(hash
, postx
)) {
1604 CAutoFile
file(OpenBlockFile(postx
, true), SER_DISK
, CLIENT_VERSION
);
1606 return error("%s: OpenBlockFile failed", __func__
);
1607 CBlockHeader header
;
1610 fseek(file
.Get(), postx
.nTxOffset
, SEEK_CUR
);
1612 } catch (const std::exception
& e
) {
1613 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
1615 hashBlock
= header
.GetHash();
1616 if (txOut
.GetHash() != hash
)
1617 return error("%s: txid mismatch", __func__
);
1622 if (fAllowSlow
) { // use coin database to locate block that contains transaction, and scan it
1625 const CCoinsViewCache
& view
= *pcoinsTip
;
1626 const CCoins
* coins
= view
.AccessCoins(hash
);
1628 nHeight
= coins
->nHeight
;
1631 pindexSlow
= chainActive
[nHeight
];
1636 if (ReadBlockFromDisk(block
, pindexSlow
, consensusParams
)) {
1637 BOOST_FOREACH(const CTransaction
&tx
, block
.vtx
) {
1638 if (tx
.GetHash() == hash
) {
1640 hashBlock
= pindexSlow
->GetBlockHash();
1655 //////////////////////////////////////////////////////////////////////////////
1657 // CBlock and CBlockIndex
1660 bool WriteBlockToDisk(const CBlock
& block
, CDiskBlockPos
& pos
, const CMessageHeader::MessageStartChars
& messageStart
)
1662 // Open history file to append
1663 CAutoFile
fileout(OpenBlockFile(pos
), SER_DISK
, CLIENT_VERSION
);
1664 if (fileout
.IsNull())
1665 return error("WriteBlockToDisk: OpenBlockFile failed");
1667 // Write index header
1668 unsigned int nSize
= fileout
.GetSerializeSize(block
);
1669 fileout
<< FLATDATA(messageStart
) << nSize
;
1672 long fileOutPos
= ftell(fileout
.Get());
1674 return error("WriteBlockToDisk: ftell failed");
1675 pos
.nPos
= (unsigned int)fileOutPos
;
1681 bool ReadBlockFromDisk(CBlock
& block
, const CDiskBlockPos
& pos
, const Consensus::Params
& consensusParams
)
1685 // Open history file to read
1686 CAutoFile
filein(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
1687 if (filein
.IsNull())
1688 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos
.ToString());
1694 catch (const std::exception
& e
) {
1695 return error("%s: Deserialize or I/O error - %s at %s", __func__
, e
.what(), pos
.ToString());
1699 if (!CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
1700 return error("ReadBlockFromDisk: Errors in block header at %s", pos
.ToString());
1705 bool ReadBlockFromDisk(CBlock
& block
, const CBlockIndex
* pindex
, const Consensus::Params
& consensusParams
)
1707 if (!ReadBlockFromDisk(block
, pindex
->GetBlockPos(), consensusParams
))
1709 if (block
.GetHash() != pindex
->GetBlockHash())
1710 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1711 pindex
->ToString(), pindex
->GetBlockPos().ToString());
1715 CAmount
GetBlockSubsidy(int nHeight
, const Consensus::Params
& consensusParams
)
1717 int halvings
= nHeight
/ consensusParams
.nSubsidyHalvingInterval
;
1718 // Force block reward to zero when right shift is undefined.
1722 CAmount nSubsidy
= 50 * COIN
;
1723 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1724 nSubsidy
>>= halvings
;
1728 bool IsInitialBlockDownload()
1730 const CChainParams
& chainParams
= Params();
1732 // Once this function has returned false, it must remain false.
1733 static std::atomic
<bool> latchToFalse
{false};
1734 // Optimization: pre-test latch before taking the lock.
1735 if (latchToFalse
.load(std::memory_order_relaxed
))
1739 if (latchToFalse
.load(std::memory_order_relaxed
))
1741 if (fImporting
|| fReindex
)
1743 if (fCheckpointsEnabled
&& chainActive
.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams
.Checkpoints()))
1745 bool state
= (chainActive
.Height() < pindexBestHeader
->nHeight
- 24 * 6 ||
1746 std::max(chainActive
.Tip()->GetBlockTime(), pindexBestHeader
->GetBlockTime()) < GetTime() - nMaxTipAge
);
1748 latchToFalse
.store(true, std::memory_order_relaxed
);
1752 bool fLargeWorkForkFound
= false;
1753 bool fLargeWorkInvalidChainFound
= false;
1754 CBlockIndex
*pindexBestForkTip
= NULL
, *pindexBestForkBase
= NULL
;
1756 static void AlertNotify(const std::string
& strMessage
)
1758 uiInterface
.NotifyAlertChanged();
1759 std::string strCmd
= GetArg("-alertnotify", "");
1760 if (strCmd
.empty()) return;
1762 // Alert text should be plain ascii coming from a trusted source, but to
1763 // be safe we first strip anything not in safeChars, then add single quotes around
1764 // the whole string before passing it to the shell:
1765 std::string
singleQuote("'");
1766 std::string safeStatus
= SanitizeString(strMessage
);
1767 safeStatus
= singleQuote
+safeStatus
+singleQuote
;
1768 boost::replace_all(strCmd
, "%s", safeStatus
);
1770 boost::thread
t(runCommand
, strCmd
); // thread runs free
1773 void CheckForkWarningConditions()
1775 AssertLockHeld(cs_main
);
1776 // Before we get past initial download, we cannot reliably alert about forks
1777 // (we assume we don't get stuck on a fork before the last checkpoint)
1778 if (IsInitialBlockDownload())
1781 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1782 // of our head, drop it
1783 if (pindexBestForkTip
&& chainActive
.Height() - pindexBestForkTip
->nHeight
>= 72)
1784 pindexBestForkTip
= NULL
;
1786 if (pindexBestForkTip
|| (pindexBestInvalid
&& pindexBestInvalid
->nChainWork
> chainActive
.Tip()->nChainWork
+ (GetBlockProof(*chainActive
.Tip()) * 6)))
1788 if (!fLargeWorkForkFound
&& pindexBestForkBase
)
1790 std::string warning
= std::string("'Warning: Large-work fork detected, forking after block ") +
1791 pindexBestForkBase
->phashBlock
->ToString() + std::string("'");
1792 AlertNotify(warning
);
1794 if (pindexBestForkTip
&& pindexBestForkBase
)
1796 LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__
,
1797 pindexBestForkBase
->nHeight
, pindexBestForkBase
->phashBlock
->ToString(),
1798 pindexBestForkTip
->nHeight
, pindexBestForkTip
->phashBlock
->ToString());
1799 fLargeWorkForkFound
= true;
1803 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__
);
1804 fLargeWorkInvalidChainFound
= true;
1809 fLargeWorkForkFound
= false;
1810 fLargeWorkInvalidChainFound
= false;
1814 void CheckForkWarningConditionsOnNewFork(CBlockIndex
* pindexNewForkTip
)
1816 AssertLockHeld(cs_main
);
1817 // If we are on a fork that is sufficiently large, set a warning flag
1818 CBlockIndex
* pfork
= pindexNewForkTip
;
1819 CBlockIndex
* plonger
= chainActive
.Tip();
1820 while (pfork
&& pfork
!= plonger
)
1822 while (plonger
&& plonger
->nHeight
> pfork
->nHeight
)
1823 plonger
= plonger
->pprev
;
1824 if (pfork
== plonger
)
1826 pfork
= pfork
->pprev
;
1829 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1830 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1831 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1832 // hash rate operating on the fork.
1833 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1834 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1835 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1836 if (pfork
&& (!pindexBestForkTip
|| (pindexBestForkTip
&& pindexNewForkTip
->nHeight
> pindexBestForkTip
->nHeight
)) &&
1837 pindexNewForkTip
->nChainWork
- pfork
->nChainWork
> (GetBlockProof(*pfork
) * 7) &&
1838 chainActive
.Height() - pindexNewForkTip
->nHeight
< 72)
1840 pindexBestForkTip
= pindexNewForkTip
;
1841 pindexBestForkBase
= pfork
;
1844 CheckForkWarningConditions();
1847 // Requires cs_main.
1848 void Misbehaving(NodeId pnode
, int howmuch
)
1853 CNodeState
*state
= State(pnode
);
1857 state
->nMisbehavior
+= howmuch
;
1858 int banscore
= GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD
);
1859 if (state
->nMisbehavior
>= banscore
&& state
->nMisbehavior
- howmuch
< banscore
)
1861 LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
1862 state
->fShouldBan
= true;
1864 LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__
, state
->name
, pnode
, state
->nMisbehavior
-howmuch
, state
->nMisbehavior
);
1867 void static InvalidChainFound(CBlockIndex
* pindexNew
)
1869 if (!pindexBestInvalid
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
)
1870 pindexBestInvalid
= pindexNew
;
1872 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1873 pindexNew
->GetBlockHash().ToString(), pindexNew
->nHeight
,
1874 log(pindexNew
->nChainWork
.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1875 pindexNew
->GetBlockTime()));
1876 CBlockIndex
*tip
= chainActive
.Tip();
1878 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1879 tip
->GetBlockHash().ToString(), chainActive
.Height(), log(tip
->nChainWork
.getdouble())/log(2.0),
1880 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip
->GetBlockTime()));
1881 CheckForkWarningConditions();
1884 void static InvalidBlockFound(CBlockIndex
*pindex
, const CValidationState
&state
) {
1885 if (!state
.CorruptionPossible()) {
1886 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
1887 setDirtyBlockIndex
.insert(pindex
);
1888 setBlockIndexCandidates
.erase(pindex
);
1889 InvalidChainFound(pindex
);
1893 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, CTxUndo
&txundo
, int nHeight
)
1895 // mark inputs spent
1896 if (!tx
.IsCoinBase()) {
1897 txundo
.vprevout
.reserve(tx
.vin
.size());
1898 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
) {
1899 CCoinsModifier coins
= inputs
.ModifyCoins(txin
.prevout
.hash
);
1900 unsigned nPos
= txin
.prevout
.n
;
1902 if (nPos
>= coins
->vout
.size() || coins
->vout
[nPos
].IsNull())
1904 // mark an outpoint spent, and construct undo information
1905 txundo
.vprevout
.push_back(CTxInUndo(coins
->vout
[nPos
]));
1907 if (coins
->vout
.size() == 0) {
1908 CTxInUndo
& undo
= txundo
.vprevout
.back();
1909 undo
.nHeight
= coins
->nHeight
;
1910 undo
.fCoinBase
= coins
->fCoinBase
;
1911 undo
.nVersion
= coins
->nVersion
;
1916 inputs
.ModifyNewCoins(tx
.GetHash(), tx
.IsCoinBase())->FromTx(tx
, nHeight
);
1919 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, int nHeight
)
1922 UpdateCoins(tx
, inputs
, txundo
, nHeight
);
1925 bool CScriptCheck::operator()() {
1926 const CScript
&scriptSig
= ptxTo
->vin
[nIn
].scriptSig
;
1927 const CScriptWitness
*witness
= (nIn
< ptxTo
->wit
.vtxinwit
.size()) ? &ptxTo
->wit
.vtxinwit
[nIn
].scriptWitness
: NULL
;
1928 if (!VerifyScript(scriptSig
, scriptPubKey
, witness
, nFlags
, CachingTransactionSignatureChecker(ptxTo
, nIn
, amount
, cacheStore
, *txdata
), &error
)) {
1934 int GetSpendHeight(const CCoinsViewCache
& inputs
)
1937 CBlockIndex
* pindexPrev
= mapBlockIndex
.find(inputs
.GetBestBlock())->second
;
1938 return pindexPrev
->nHeight
+ 1;
1941 namespace Consensus
{
1942 bool CheckTxInputs(const CTransaction
& tx
, CValidationState
& state
, const CCoinsViewCache
& inputs
, int nSpendHeight
)
1944 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1945 // for an attacker to attempt to split the network.
1946 if (!inputs
.HaveInputs(tx
))
1947 return state
.Invalid(false, 0, "", "Inputs unavailable");
1949 CAmount nValueIn
= 0;
1951 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
1953 const COutPoint
&prevout
= tx
.vin
[i
].prevout
;
1954 const CCoins
*coins
= inputs
.AccessCoins(prevout
.hash
);
1957 // If prev is coinbase, check that it's matured
1958 if (coins
->IsCoinBase()) {
1959 if (nSpendHeight
- coins
->nHeight
< COINBASE_MATURITY
)
1960 return state
.Invalid(false,
1961 REJECT_INVALID
, "bad-txns-premature-spend-of-coinbase",
1962 strprintf("tried to spend coinbase at depth %d", nSpendHeight
- coins
->nHeight
));
1965 // Check for negative or overflow input values
1966 nValueIn
+= coins
->vout
[prevout
.n
].nValue
;
1967 if (!MoneyRange(coins
->vout
[prevout
.n
].nValue
) || !MoneyRange(nValueIn
))
1968 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-inputvalues-outofrange");
1972 if (nValueIn
< tx
.GetValueOut())
1973 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-in-belowout", false,
1974 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn
), FormatMoney(tx
.GetValueOut())));
1976 // Tally transaction fees
1977 CAmount nTxFee
= nValueIn
- tx
.GetValueOut();
1979 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-fee-negative");
1981 if (!MoneyRange(nFees
))
1982 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-fee-outofrange");
1985 }// namespace Consensus
1987 bool CheckInputs(const CTransaction
& tx
, CValidationState
&state
, const CCoinsViewCache
&inputs
, bool fScriptChecks
, unsigned int flags
, bool cacheStore
, PrecomputedTransactionData
& txdata
, std::vector
<CScriptCheck
> *pvChecks
)
1989 if (!tx
.IsCoinBase())
1991 if (!Consensus::CheckTxInputs(tx
, state
, inputs
, GetSpendHeight(inputs
)))
1995 pvChecks
->reserve(tx
.vin
.size());
1997 // The first loop above does all the inexpensive checks.
1998 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1999 // Helps prevent CPU exhaustion attacks.
2001 // Skip ECDSA signature verification when connecting blocks before the
2002 // last block chain checkpoint. Assuming the checkpoints are valid this
2003 // is safe because block merkle hashes are still computed and checked,
2004 // and any change will be caught at the next checkpoint. Of course, if
2005 // the checkpoint is for a chain that's invalid due to false scriptSigs
2006 // this optimization would allow an invalid chain to be accepted.
2007 if (fScriptChecks
) {
2008 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++) {
2009 const COutPoint
&prevout
= tx
.vin
[i
].prevout
;
2010 const CCoins
* coins
= inputs
.AccessCoins(prevout
.hash
);
2014 CScriptCheck
check(*coins
, tx
, i
, flags
, cacheStore
, &txdata
);
2016 pvChecks
->push_back(CScriptCheck());
2017 check
.swap(pvChecks
->back());
2018 } else if (!check()) {
2019 if (flags
& STANDARD_NOT_MANDATORY_VERIFY_FLAGS
) {
2020 // Check whether the failure was caused by a
2021 // non-mandatory script verification check, such as
2022 // non-standard DER encodings or non-null dummy
2023 // arguments; if so, don't trigger DoS protection to
2024 // avoid splitting the network between upgraded and
2025 // non-upgraded nodes.
2026 CScriptCheck
check2(*coins
, tx
, i
,
2027 flags
& ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS
, cacheStore
, &txdata
);
2029 return state
.Invalid(false, REJECT_NONSTANDARD
, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check
.GetScriptError())));
2031 // Failures of other flags indicate a transaction that is
2032 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
2033 // such nodes as they are not following the protocol. That
2034 // said during an upgrade careful thought should be taken
2035 // as to the correct behavior - we may want to continue
2036 // peering with non-upgraded nodes even after soft-fork
2037 // super-majority signaling has occurred.
2038 return state
.DoS(100,false, REJECT_INVALID
, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check
.GetScriptError())));
2049 bool UndoWriteToDisk(const CBlockUndo
& blockundo
, CDiskBlockPos
& pos
, const uint256
& hashBlock
, const CMessageHeader::MessageStartChars
& messageStart
)
2051 // Open history file to append
2052 CAutoFile
fileout(OpenUndoFile(pos
), SER_DISK
, CLIENT_VERSION
);
2053 if (fileout
.IsNull())
2054 return error("%s: OpenUndoFile failed", __func__
);
2056 // Write index header
2057 unsigned int nSize
= fileout
.GetSerializeSize(blockundo
);
2058 fileout
<< FLATDATA(messageStart
) << nSize
;
2061 long fileOutPos
= ftell(fileout
.Get());
2063 return error("%s: ftell failed", __func__
);
2064 pos
.nPos
= (unsigned int)fileOutPos
;
2065 fileout
<< blockundo
;
2067 // calculate & write checksum
2068 CHashWriter
hasher(SER_GETHASH
, PROTOCOL_VERSION
);
2069 hasher
<< hashBlock
;
2070 hasher
<< blockundo
;
2071 fileout
<< hasher
.GetHash();
2076 bool UndoReadFromDisk(CBlockUndo
& blockundo
, const CDiskBlockPos
& pos
, const uint256
& hashBlock
)
2078 // Open history file to read
2079 CAutoFile
filein(OpenUndoFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
2080 if (filein
.IsNull())
2081 return error("%s: OpenUndoFile failed", __func__
);
2084 uint256 hashChecksum
;
2086 filein
>> blockundo
;
2087 filein
>> hashChecksum
;
2089 catch (const std::exception
& e
) {
2090 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
2094 CHashWriter
hasher(SER_GETHASH
, PROTOCOL_VERSION
);
2095 hasher
<< hashBlock
;
2096 hasher
<< blockundo
;
2097 if (hashChecksum
!= hasher
.GetHash())
2098 return error("%s: Checksum mismatch", __func__
);
2103 /** Abort with a message */
2104 bool AbortNode(const std::string
& strMessage
, const std::string
& userMessage
="")
2106 strMiscWarning
= strMessage
;
2107 LogPrintf("*** %s\n", strMessage
);
2108 uiInterface
.ThreadSafeMessageBox(
2109 userMessage
.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage
,
2110 "", CClientUIInterface::MSG_ERROR
);
2115 bool AbortNode(CValidationState
& state
, const std::string
& strMessage
, const std::string
& userMessage
="")
2117 AbortNode(strMessage
, userMessage
);
2118 return state
.Error(strMessage
);
2124 * Apply the undo operation of a CTxInUndo to the given chain state.
2125 * @param undo The undo object.
2126 * @param view The coins view to which to apply the changes.
2127 * @param out The out point that corresponds to the tx input.
2128 * @return True on success.
2130 static bool ApplyTxInUndo(const CTxInUndo
& undo
, CCoinsViewCache
& view
, const COutPoint
& out
)
2134 CCoinsModifier coins
= view
.ModifyCoins(out
.hash
);
2135 if (undo
.nHeight
!= 0) {
2136 // undo data contains height: this is the last output of the prevout tx being spent
2137 if (!coins
->IsPruned())
2138 fClean
= fClean
&& error("%s: undo data overwriting existing transaction", __func__
);
2140 coins
->fCoinBase
= undo
.fCoinBase
;
2141 coins
->nHeight
= undo
.nHeight
;
2142 coins
->nVersion
= undo
.nVersion
;
2144 if (coins
->IsPruned())
2145 fClean
= fClean
&& error("%s: undo data adding output to missing transaction", __func__
);
2147 if (coins
->IsAvailable(out
.n
))
2148 fClean
= fClean
&& error("%s: undo data overwriting existing output", __func__
);
2149 if (coins
->vout
.size() < out
.n
+1)
2150 coins
->vout
.resize(out
.n
+1);
2151 coins
->vout
[out
.n
] = undo
.txout
;
2156 bool DisconnectBlock(const CBlock
& block
, CValidationState
& state
, const CBlockIndex
* pindex
, CCoinsViewCache
& view
, bool* pfClean
)
2158 assert(pindex
->GetBlockHash() == view
.GetBestBlock());
2165 CBlockUndo blockUndo
;
2166 CDiskBlockPos pos
= pindex
->GetUndoPos();
2168 return error("DisconnectBlock(): no undo data available");
2169 if (!UndoReadFromDisk(blockUndo
, pos
, pindex
->pprev
->GetBlockHash()))
2170 return error("DisconnectBlock(): failure reading undo data");
2172 if (blockUndo
.vtxundo
.size() + 1 != block
.vtx
.size())
2173 return error("DisconnectBlock(): block and undo data inconsistent");
2175 // undo transactions in reverse order
2176 for (int i
= block
.vtx
.size() - 1; i
>= 0; i
--) {
2177 const CTransaction
&tx
= block
.vtx
[i
];
2178 uint256 hash
= tx
.GetHash();
2180 // Check that all outputs are available and match the outputs in the block itself
2183 CCoinsModifier outs
= view
.ModifyCoins(hash
);
2184 outs
->ClearUnspendable();
2186 CCoins
outsBlock(tx
, pindex
->nHeight
);
2187 // The CCoins serialization does not serialize negative numbers.
2188 // No network rules currently depend on the version here, so an inconsistency is harmless
2189 // but it must be corrected before txout nversion ever influences a network rule.
2190 if (outsBlock
.nVersion
< 0)
2191 outs
->nVersion
= outsBlock
.nVersion
;
2192 if (*outs
!= outsBlock
)
2193 fClean
= fClean
&& error("DisconnectBlock(): added transaction mismatch? database corrupted");
2200 if (i
> 0) { // not coinbases
2201 const CTxUndo
&txundo
= blockUndo
.vtxundo
[i
-1];
2202 if (txundo
.vprevout
.size() != tx
.vin
.size())
2203 return error("DisconnectBlock(): transaction and undo data inconsistent");
2204 for (unsigned int j
= tx
.vin
.size(); j
-- > 0;) {
2205 const COutPoint
&out
= tx
.vin
[j
].prevout
;
2206 const CTxInUndo
&undo
= txundo
.vprevout
[j
];
2207 if (!ApplyTxInUndo(undo
, view
, out
))
2213 // move best block pointer to prevout block
2214 view
.SetBestBlock(pindex
->pprev
->GetBlockHash());
2224 void static FlushBlockFile(bool fFinalize
= false)
2226 LOCK(cs_LastBlockFile
);
2228 CDiskBlockPos
posOld(nLastBlockFile
, 0);
2230 FILE *fileOld
= OpenBlockFile(posOld
);
2233 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nSize
);
2234 FileCommit(fileOld
);
2238 fileOld
= OpenUndoFile(posOld
);
2241 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nUndoSize
);
2242 FileCommit(fileOld
);
2247 bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
);
2249 static CCheckQueue
<CScriptCheck
> scriptcheckqueue(128);
2251 void ThreadScriptCheck() {
2252 RenameThread("bitcoin-scriptch");
2253 scriptcheckqueue
.Thread();
2256 // Protected by cs_main
2257 VersionBitsCache versionbitscache
;
2259 int32_t ComputeBlockVersion(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
2262 int32_t nVersion
= VERSIONBITS_TOP_BITS
;
2264 for (int i
= 0; i
< (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS
; i
++) {
2265 ThresholdState state
= VersionBitsState(pindexPrev
, params
, (Consensus::DeploymentPos
)i
, versionbitscache
);
2266 if (state
== THRESHOLD_LOCKED_IN
|| state
== THRESHOLD_STARTED
) {
2267 nVersion
|= VersionBitsMask(params
, (Consensus::DeploymentPos
)i
);
2275 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
2277 class WarningBitsConditionChecker
: public AbstractThresholdConditionChecker
2283 WarningBitsConditionChecker(int bitIn
) : bit(bitIn
) {}
2285 int64_t BeginTime(const Consensus::Params
& params
) const { return 0; }
2286 int64_t EndTime(const Consensus::Params
& params
) const { return std::numeric_limits
<int64_t>::max(); }
2287 int Period(const Consensus::Params
& params
) const { return params
.nMinerConfirmationWindow
; }
2288 int Threshold(const Consensus::Params
& params
) const { return params
.nRuleChangeActivationThreshold
; }
2290 bool Condition(const CBlockIndex
* pindex
, const Consensus::Params
& params
) const
2292 return ((pindex
->nVersion
& VERSIONBITS_TOP_MASK
) == VERSIONBITS_TOP_BITS
) &&
2293 ((pindex
->nVersion
>> bit
) & 1) != 0 &&
2294 ((ComputeBlockVersion(pindex
->pprev
, params
) >> bit
) & 1) == 0;
2298 // Protected by cs_main
2299 static ThresholdConditionCache warningcache
[VERSIONBITS_NUM_BITS
];
2301 static int64_t nTimeCheck
= 0;
2302 static int64_t nTimeForks
= 0;
2303 static int64_t nTimeVerify
= 0;
2304 static int64_t nTimeConnect
= 0;
2305 static int64_t nTimeIndex
= 0;
2306 static int64_t nTimeCallbacks
= 0;
2307 static int64_t nTimeTotal
= 0;
2309 bool ConnectBlock(const CBlock
& block
, CValidationState
& state
, CBlockIndex
* pindex
,
2310 CCoinsViewCache
& view
, const CChainParams
& chainparams
, bool fJustCheck
)
2312 AssertLockHeld(cs_main
);
2314 int64_t nTimeStart
= GetTimeMicros();
2316 // Check it again in case a previous version let a bad block in
2317 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), !fJustCheck
, !fJustCheck
))
2318 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
2320 // verify that the view's current state corresponds to the previous block
2321 uint256 hashPrevBlock
= pindex
->pprev
== NULL
? uint256() : pindex
->pprev
->GetBlockHash();
2322 assert(hashPrevBlock
== view
.GetBestBlock());
2324 // Special case for the genesis block, skipping connection of its transactions
2325 // (its coinbase is unspendable)
2326 if (block
.GetHash() == chainparams
.GetConsensus().hashGenesisBlock
) {
2328 view
.SetBestBlock(pindex
->GetBlockHash());
2332 bool fScriptChecks
= true;
2333 if (fCheckpointsEnabled
) {
2334 CBlockIndex
*pindexLastCheckpoint
= Checkpoints::GetLastCheckpoint(chainparams
.Checkpoints());
2335 if (pindexLastCheckpoint
&& pindexLastCheckpoint
->GetAncestor(pindex
->nHeight
) == pindex
) {
2336 // This block is an ancestor of a checkpoint: disable script checks
2337 fScriptChecks
= false;
2341 int64_t nTime1
= GetTimeMicros(); nTimeCheck
+= nTime1
- nTimeStart
;
2342 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1
- nTimeStart
), nTimeCheck
* 0.000001);
2344 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2345 // unless those are already completely spent.
2346 // If such overwrites are allowed, coinbases and transactions depending upon those
2347 // can be duplicated to remove the ability to spend the first instance -- even after
2348 // being sent to another address.
2349 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
2350 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2351 // already refuses previously-known transaction ids entirely.
2352 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2353 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2354 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2355 // initial block download.
2356 bool fEnforceBIP30
= (!pindex
->phashBlock
) || // Enforce on CreateNewBlock invocations which don't have a hash.
2357 !((pindex
->nHeight
==91842 && pindex
->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2358 (pindex
->nHeight
==91880 && pindex
->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2360 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2361 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2362 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2363 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
2364 // duplicate transactions descending from the known pairs either.
2365 // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
2366 CBlockIndex
*pindexBIP34height
= pindex
->pprev
->GetAncestor(chainparams
.GetConsensus().BIP34Height
);
2367 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2368 fEnforceBIP30
= fEnforceBIP30
&& (!pindexBIP34height
|| !(pindexBIP34height
->GetBlockHash() == chainparams
.GetConsensus().BIP34Hash
));
2370 if (fEnforceBIP30
) {
2371 BOOST_FOREACH(const CTransaction
& tx
, block
.vtx
) {
2372 const CCoins
* coins
= view
.AccessCoins(tx
.GetHash());
2373 if (coins
&& !coins
->IsPruned())
2374 return state
.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2375 REJECT_INVALID
, "bad-txns-BIP30");
2379 // BIP16 didn't become active until Apr 1 2012
2380 int64_t nBIP16SwitchTime
= 1333238400;
2381 bool fStrictPayToScriptHash
= (pindex
->GetBlockTime() >= nBIP16SwitchTime
);
2383 unsigned int flags
= fStrictPayToScriptHash
? SCRIPT_VERIFY_P2SH
: SCRIPT_VERIFY_NONE
;
2385 // Start enforcing the DERSIG (BIP66) rule
2386 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP66Height
) {
2387 flags
|= SCRIPT_VERIFY_DERSIG
;
2390 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
2391 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP65Height
) {
2392 flags
|= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
;
2395 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
2396 int nLockTimeFlags
= 0;
2397 if (VersionBitsState(pindex
->pprev
, chainparams
.GetConsensus(), Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
2398 flags
|= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
;
2399 nLockTimeFlags
|= LOCKTIME_VERIFY_SEQUENCE
;
2402 // Start enforcing WITNESS rules using versionbits logic.
2403 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus())) {
2404 flags
|= SCRIPT_VERIFY_WITNESS
;
2405 flags
|= SCRIPT_VERIFY_NULLDUMMY
;
2408 int64_t nTime2
= GetTimeMicros(); nTimeForks
+= nTime2
- nTime1
;
2409 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2
- nTime1
), nTimeForks
* 0.000001);
2411 CBlockUndo blockundo
;
2413 CCheckQueueControl
<CScriptCheck
> control(fScriptChecks
&& nScriptCheckThreads
? &scriptcheckqueue
: NULL
);
2415 std::vector
<uint256
> vOrphanErase
;
2416 std::vector
<int> prevheights
;
2419 int64_t nSigOpsCost
= 0;
2420 CDiskTxPos
pos(pindex
->GetBlockPos(), GetSizeOfCompactSize(block
.vtx
.size()));
2421 std::vector
<std::pair
<uint256
, CDiskTxPos
> > vPos
;
2422 vPos
.reserve(block
.vtx
.size());
2423 blockundo
.vtxundo
.reserve(block
.vtx
.size() - 1);
2424 std::vector
<PrecomputedTransactionData
> txdata
;
2425 txdata
.reserve(block
.vtx
.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2426 for (unsigned int i
= 0; i
< block
.vtx
.size(); i
++)
2428 const CTransaction
&tx
= block
.vtx
[i
];
2430 nInputs
+= tx
.vin
.size();
2432 if (!tx
.IsCoinBase())
2434 if (!view
.HaveInputs(tx
))
2435 return state
.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2436 REJECT_INVALID
, "bad-txns-inputs-missingorspent");
2438 // Check that transaction is BIP68 final
2439 // BIP68 lock checks (as opposed to nLockTime checks) must
2440 // be in ConnectBlock because they require the UTXO set
2441 prevheights
.resize(tx
.vin
.size());
2442 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
2443 prevheights
[j
] = view
.AccessCoins(tx
.vin
[j
].prevout
.hash
)->nHeight
;
2446 // Which orphan pool entries must we evict?
2447 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
2448 auto itByPrev
= mapOrphanTransactionsByPrev
.find(tx
.vin
[j
].prevout
);
2449 if (itByPrev
== mapOrphanTransactionsByPrev
.end()) continue;
2450 for (auto mi
= itByPrev
->second
.begin(); mi
!= itByPrev
->second
.end(); ++mi
) {
2451 const CTransaction
& orphanTx
= (*mi
)->second
.tx
;
2452 const uint256
& orphanHash
= orphanTx
.GetHash();
2453 vOrphanErase
.push_back(orphanHash
);
2457 if (!SequenceLocks(tx
, nLockTimeFlags
, &prevheights
, *pindex
)) {
2458 return state
.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__
),
2459 REJECT_INVALID
, "bad-txns-nonfinal");
2463 // GetTransactionSigOpCost counts 3 types of sigops:
2464 // * legacy (always)
2465 // * p2sh (when P2SH enabled in flags and excludes coinbase)
2466 // * witness (when witness enabled in flags and excludes coinbase)
2467 nSigOpsCost
+= GetTransactionSigOpCost(tx
, view
, flags
);
2468 if (nSigOpsCost
> MAX_BLOCK_SIGOPS_COST
)
2469 return state
.DoS(100, error("ConnectBlock(): too many sigops"),
2470 REJECT_INVALID
, "bad-blk-sigops");
2472 txdata
.emplace_back(tx
);
2473 if (!tx
.IsCoinBase())
2475 nFees
+= view
.GetValueIn(tx
)-tx
.GetValueOut();
2477 std::vector
<CScriptCheck
> vChecks
;
2478 bool fCacheResults
= fJustCheck
; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2479 if (!CheckInputs(tx
, state
, view
, fScriptChecks
, flags
, fCacheResults
, txdata
[i
], nScriptCheckThreads
? &vChecks
: NULL
))
2480 return error("ConnectBlock(): CheckInputs on %s failed with %s",
2481 tx
.GetHash().ToString(), FormatStateMessage(state
));
2482 control
.Add(vChecks
);
2487 blockundo
.vtxundo
.push_back(CTxUndo());
2489 UpdateCoins(tx
, view
, i
== 0 ? undoDummy
: blockundo
.vtxundo
.back(), pindex
->nHeight
);
2491 vPos
.push_back(std::make_pair(tx
.GetHash(), pos
));
2492 pos
.nTxOffset
+= ::GetSerializeSize(tx
, SER_DISK
, CLIENT_VERSION
);
2494 int64_t nTime3
= GetTimeMicros(); nTimeConnect
+= nTime3
- nTime2
;
2495 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block
.vtx
.size(), 0.001 * (nTime3
- nTime2
), 0.001 * (nTime3
- nTime2
) / block
.vtx
.size(), nInputs
<= 1 ? 0 : 0.001 * (nTime3
- nTime2
) / (nInputs
-1), nTimeConnect
* 0.000001);
2497 CAmount blockReward
= nFees
+ GetBlockSubsidy(pindex
->nHeight
, chainparams
.GetConsensus());
2498 if (block
.vtx
[0].GetValueOut() > blockReward
)
2499 return state
.DoS(100,
2500 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2501 block
.vtx
[0].GetValueOut(), blockReward
),
2502 REJECT_INVALID
, "bad-cb-amount");
2504 if (!control
.Wait())
2505 return state
.DoS(100, false);
2506 int64_t nTime4
= GetTimeMicros(); nTimeVerify
+= nTime4
- nTime2
;
2507 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs
- 1, 0.001 * (nTime4
- nTime2
), nInputs
<= 1 ? 0 : 0.001 * (nTime4
- nTime2
) / (nInputs
-1), nTimeVerify
* 0.000001);
2512 // Write undo information to disk
2513 if (pindex
->GetUndoPos().IsNull() || !pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
2515 if (pindex
->GetUndoPos().IsNull()) {
2517 if (!FindUndoPos(state
, pindex
->nFile
, _pos
, ::GetSerializeSize(blockundo
, SER_DISK
, CLIENT_VERSION
) + 40))
2518 return error("ConnectBlock(): FindUndoPos failed");
2519 if (!UndoWriteToDisk(blockundo
, _pos
, pindex
->pprev
->GetBlockHash(), chainparams
.MessageStart()))
2520 return AbortNode(state
, "Failed to write undo data");
2522 // update nUndoPos in block index
2523 pindex
->nUndoPos
= _pos
.nPos
;
2524 pindex
->nStatus
|= BLOCK_HAVE_UNDO
;
2527 pindex
->RaiseValidity(BLOCK_VALID_SCRIPTS
);
2528 setDirtyBlockIndex
.insert(pindex
);
2532 if (!pblocktree
->WriteTxIndex(vPos
))
2533 return AbortNode(state
, "Failed to write transaction index");
2535 // add this block to the view's block chain
2536 view
.SetBestBlock(pindex
->GetBlockHash());
2538 int64_t nTime5
= GetTimeMicros(); nTimeIndex
+= nTime5
- nTime4
;
2539 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5
- nTime4
), nTimeIndex
* 0.000001);
2541 // Watch for changes to the previous coinbase transaction.
2542 static uint256 hashPrevBestCoinBase
;
2543 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase
);
2544 hashPrevBestCoinBase
= block
.vtx
[0].GetHash();
2546 // Erase orphan transactions include or precluded by this block
2547 if (vOrphanErase
.size()) {
2549 BOOST_FOREACH(uint256
&orphanHash
, vOrphanErase
) {
2550 nErased
+= EraseOrphanTx(orphanHash
);
2552 LogPrint("mempool", "Erased %d orphan tx included or conflicted by block\n", nErased
);
2555 int64_t nTime6
= GetTimeMicros(); nTimeCallbacks
+= nTime6
- nTime5
;
2556 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6
- nTime5
), nTimeCallbacks
* 0.000001);
2561 enum FlushStateMode
{
2563 FLUSH_STATE_IF_NEEDED
,
2564 FLUSH_STATE_PERIODIC
,
2569 * Update the on-disk chain state.
2570 * The caches and indexes are flushed depending on the mode we're called with
2571 * if they're too large, if it's been a while since the last write,
2572 * or always and in all cases if we're in prune mode and are deleting files.
2574 bool static FlushStateToDisk(CValidationState
&state
, FlushStateMode mode
) {
2575 const CChainParams
& chainparams
= Params();
2576 LOCK2(cs_main
, cs_LastBlockFile
);
2577 static int64_t nLastWrite
= 0;
2578 static int64_t nLastFlush
= 0;
2579 static int64_t nLastSetChain
= 0;
2580 std::set
<int> setFilesToPrune
;
2581 bool fFlushForPrune
= false;
2583 if (fPruneMode
&& fCheckForPruning
&& !fReindex
) {
2584 FindFilesToPrune(setFilesToPrune
, chainparams
.PruneAfterHeight());
2585 fCheckForPruning
= false;
2586 if (!setFilesToPrune
.empty()) {
2587 fFlushForPrune
= true;
2589 pblocktree
->WriteFlag("prunedblockfiles", true);
2594 int64_t nNow
= GetTimeMicros();
2595 // Avoid writing/flushing immediately after startup.
2596 if (nLastWrite
== 0) {
2599 if (nLastFlush
== 0) {
2602 if (nLastSetChain
== 0) {
2603 nLastSetChain
= nNow
;
2605 size_t cacheSize
= pcoinsTip
->DynamicMemoryUsage();
2606 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2607 bool fCacheLarge
= mode
== FLUSH_STATE_PERIODIC
&& cacheSize
* (10.0/9) > nCoinCacheUsage
;
2608 // The cache is over the limit, we have to write now.
2609 bool fCacheCritical
= mode
== FLUSH_STATE_IF_NEEDED
&& cacheSize
> nCoinCacheUsage
;
2610 // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
2611 bool fPeriodicWrite
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastWrite
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000;
2612 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2613 bool fPeriodicFlush
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastFlush
+ (int64_t)DATABASE_FLUSH_INTERVAL
* 1000000;
2614 // Combine all conditions that result in a full cache flush.
2615 bool fDoFullFlush
= (mode
== FLUSH_STATE_ALWAYS
) || fCacheLarge
|| fCacheCritical
|| fPeriodicFlush
|| fFlushForPrune
;
2616 // Write blocks and block index to disk.
2617 if (fDoFullFlush
|| fPeriodicWrite
) {
2618 // Depend on nMinDiskSpace to ensure we can write block index
2619 if (!CheckDiskSpace(0))
2620 return state
.Error("out of disk space");
2621 // First make sure all block and undo data is flushed to disk.
2623 // Then update all block file information (which may refer to block and undo files).
2625 std::vector
<std::pair
<int, const CBlockFileInfo
*> > vFiles
;
2626 vFiles
.reserve(setDirtyFileInfo
.size());
2627 for (set
<int>::iterator it
= setDirtyFileInfo
.begin(); it
!= setDirtyFileInfo
.end(); ) {
2628 vFiles
.push_back(make_pair(*it
, &vinfoBlockFile
[*it
]));
2629 setDirtyFileInfo
.erase(it
++);
2631 std::vector
<const CBlockIndex
*> vBlocks
;
2632 vBlocks
.reserve(setDirtyBlockIndex
.size());
2633 for (set
<CBlockIndex
*>::iterator it
= setDirtyBlockIndex
.begin(); it
!= setDirtyBlockIndex
.end(); ) {
2634 vBlocks
.push_back(*it
);
2635 setDirtyBlockIndex
.erase(it
++);
2637 if (!pblocktree
->WriteBatchSync(vFiles
, nLastBlockFile
, vBlocks
)) {
2638 return AbortNode(state
, "Files to write to block index database");
2641 // Finally remove any pruned files
2643 UnlinkPrunedFiles(setFilesToPrune
);
2646 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2648 // Typical CCoins structures on disk are around 128 bytes in size.
2649 // Pushing a new one to the database can cause it to be written
2650 // twice (once in the log, and once in the tables). This is already
2651 // an overestimation, as most will delete an existing entry or
2652 // overwrite one. Still, use a conservative safety factor of 2.
2653 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip
->GetCacheSize()))
2654 return state
.Error("out of disk space");
2655 // Flush the chainstate (which may refer to block index entries).
2656 if (!pcoinsTip
->Flush())
2657 return AbortNode(state
, "Failed to write to coin database");
2660 if (fDoFullFlush
|| ((mode
== FLUSH_STATE_ALWAYS
|| mode
== FLUSH_STATE_PERIODIC
) && nNow
> nLastSetChain
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000)) {
2661 // Update best block in wallet (so we can detect restored wallets).
2662 GetMainSignals().SetBestChain(chainActive
.GetLocator());
2663 nLastSetChain
= nNow
;
2665 } catch (const std::runtime_error
& e
) {
2666 return AbortNode(state
, std::string("System error while flushing: ") + e
.what());
2671 void FlushStateToDisk() {
2672 CValidationState state
;
2673 FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
);
2676 void PruneAndFlush() {
2677 CValidationState state
;
2678 fCheckForPruning
= true;
2679 FlushStateToDisk(state
, FLUSH_STATE_NONE
);
2682 /** Update chainActive and related internal data structures. */
2683 void static UpdateTip(CBlockIndex
*pindexNew
, const CChainParams
& chainParams
) {
2684 chainActive
.SetTip(pindexNew
);
2687 nTimeBestReceived
= GetTime();
2688 mempool
.AddTransactionsUpdated(1);
2690 cvBlockChange
.notify_all();
2692 static bool fWarned
= false;
2693 std::vector
<std::string
> warningMessages
;
2694 if (!IsInitialBlockDownload())
2697 const CBlockIndex
* pindex
= chainActive
.Tip();
2698 for (int bit
= 0; bit
< VERSIONBITS_NUM_BITS
; bit
++) {
2699 WarningBitsConditionChecker
checker(bit
);
2700 ThresholdState state
= checker
.GetStateFor(pindex
, chainParams
.GetConsensus(), warningcache
[bit
]);
2701 if (state
== THRESHOLD_ACTIVE
|| state
== THRESHOLD_LOCKED_IN
) {
2702 if (state
== THRESHOLD_ACTIVE
) {
2703 strMiscWarning
= strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit
);
2705 AlertNotify(strMiscWarning
);
2709 warningMessages
.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit
));
2713 // Check the version of the last 100 blocks to see if we need to upgrade:
2714 for (int i
= 0; i
< 100 && pindex
!= NULL
; i
++)
2716 int32_t nExpectedVersion
= ComputeBlockVersion(pindex
->pprev
, chainParams
.GetConsensus());
2717 if (pindex
->nVersion
> VERSIONBITS_LAST_OLD_BLOCK_VERSION
&& (pindex
->nVersion
& ~nExpectedVersion
) != 0)
2719 pindex
= pindex
->pprev
;
2722 warningMessages
.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded
));
2723 if (nUpgraded
> 100/2)
2725 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2726 strMiscWarning
= _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2728 AlertNotify(strMiscWarning
);
2733 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__
,
2734 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(), chainActive
.Tip()->nVersion
,
2735 log(chainActive
.Tip()->nChainWork
.getdouble())/log(2.0), (unsigned long)chainActive
.Tip()->nChainTx
,
2736 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
2737 Checkpoints::GuessVerificationProgress(chainParams
.Checkpoints(), chainActive
.Tip()), pcoinsTip
->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip
->GetCacheSize());
2738 if (!warningMessages
.empty())
2739 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages
, ", "));
2744 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2745 bool static DisconnectTip(CValidationState
& state
, const CChainParams
& chainparams
, bool fBare
= false)
2747 CBlockIndex
*pindexDelete
= chainActive
.Tip();
2748 assert(pindexDelete
);
2749 // Read block from disk.
2751 if (!ReadBlockFromDisk(block
, pindexDelete
, chainparams
.GetConsensus()))
2752 return AbortNode(state
, "Failed to read block");
2753 // Apply the block atomically to the chain state.
2754 int64_t nStart
= GetTimeMicros();
2756 CCoinsViewCache
view(pcoinsTip
);
2757 if (!DisconnectBlock(block
, state
, pindexDelete
, view
))
2758 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete
->GetBlockHash().ToString());
2759 assert(view
.Flush());
2761 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart
) * 0.001);
2762 // Write the chain state to disk, if necessary.
2763 if (!FlushStateToDisk(state
, FLUSH_STATE_IF_NEEDED
))
2767 // Resurrect mempool transactions from the disconnected block.
2768 std::vector
<uint256
> vHashUpdate
;
2769 BOOST_FOREACH(const CTransaction
&tx
, block
.vtx
) {
2770 // ignore validation errors in resurrected transactions
2771 CValidationState stateDummy
;
2772 if (tx
.IsCoinBase() || !AcceptToMemoryPool(mempool
, stateDummy
, tx
, false, NULL
, true)) {
2773 mempool
.removeRecursive(tx
);
2774 } else if (mempool
.exists(tx
.GetHash())) {
2775 vHashUpdate
.push_back(tx
.GetHash());
2778 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2779 // no in-mempool children, which is generally not true when adding
2780 // previously-confirmed transactions back to the mempool.
2781 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2782 // block that were added back and cleans up the mempool state.
2783 mempool
.UpdateTransactionsFromBlock(vHashUpdate
);
2786 // Update chainActive and related variables.
2787 UpdateTip(pindexDelete
->pprev
, chainparams
);
2788 // Let wallets know transactions went from 1-confirmed to
2789 // 0-confirmed or conflicted:
2790 BOOST_FOREACH(const CTransaction
&tx
, block
.vtx
) {
2791 GetMainSignals().SyncTransaction(tx
, pindexDelete
->pprev
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
2796 static int64_t nTimeReadFromDisk
= 0;
2797 static int64_t nTimeConnectTotal
= 0;
2798 static int64_t nTimeFlush
= 0;
2799 static int64_t nTimeChainState
= 0;
2800 static int64_t nTimePostConnect
= 0;
2803 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2804 * corresponding to pindexNew, to bypass loading it again from disk.
2806 bool static ConnectTip(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexNew
, const CBlock
* pblock
, std::list
<CTransaction
> &txConflicted
, std::vector
<std::tuple
<CTransaction
,CBlockIndex
*,int>> &txChanged
)
2808 assert(pindexNew
->pprev
== chainActive
.Tip());
2809 // Read block from disk.
2810 int64_t nTime1
= GetTimeMicros();
2813 if (!ReadBlockFromDisk(block
, pindexNew
, chainparams
.GetConsensus()))
2814 return AbortNode(state
, "Failed to read block");
2817 // Apply the block atomically to the chain state.
2818 int64_t nTime2
= GetTimeMicros(); nTimeReadFromDisk
+= nTime2
- nTime1
;
2820 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2
- nTime1
) * 0.001, nTimeReadFromDisk
* 0.000001);
2822 CCoinsViewCache
view(pcoinsTip
);
2823 bool rv
= ConnectBlock(*pblock
, state
, pindexNew
, view
, chainparams
);
2824 GetMainSignals().BlockChecked(*pblock
, state
);
2826 if (state
.IsInvalid())
2827 InvalidBlockFound(pindexNew
, state
);
2828 return error("ConnectTip(): ConnectBlock %s failed", pindexNew
->GetBlockHash().ToString());
2830 nTime3
= GetTimeMicros(); nTimeConnectTotal
+= nTime3
- nTime2
;
2831 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3
- nTime2
) * 0.001, nTimeConnectTotal
* 0.000001);
2832 assert(view
.Flush());
2834 int64_t nTime4
= GetTimeMicros(); nTimeFlush
+= nTime4
- nTime3
;
2835 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4
- nTime3
) * 0.001, nTimeFlush
* 0.000001);
2836 // Write the chain state to disk, if necessary.
2837 if (!FlushStateToDisk(state
, FLUSH_STATE_IF_NEEDED
))
2839 int64_t nTime5
= GetTimeMicros(); nTimeChainState
+= nTime5
- nTime4
;
2840 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5
- nTime4
) * 0.001, nTimeChainState
* 0.000001);
2841 // Remove conflicting transactions from the mempool.;
2842 mempool
.removeForBlock(pblock
->vtx
, pindexNew
->nHeight
, &txConflicted
, !IsInitialBlockDownload());
2843 // Update chainActive & related variables.
2844 UpdateTip(pindexNew
, chainparams
);
2846 for(unsigned int i
=0; i
< pblock
->vtx
.size(); i
++)
2847 txChanged
.emplace_back(pblock
->vtx
[i
], pindexNew
, i
);
2849 int64_t nTime6
= GetTimeMicros(); nTimePostConnect
+= nTime6
- nTime5
; nTimeTotal
+= nTime6
- nTime1
;
2850 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6
- nTime5
) * 0.001, nTimePostConnect
* 0.000001);
2851 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6
- nTime1
) * 0.001, nTimeTotal
* 0.000001);
2856 * Return the tip of the chain with the most work in it, that isn't
2857 * known to be invalid (it's however far from certain to be valid).
2859 static CBlockIndex
* FindMostWorkChain() {
2861 CBlockIndex
*pindexNew
= NULL
;
2863 // Find the best candidate header.
2865 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::reverse_iterator it
= setBlockIndexCandidates
.rbegin();
2866 if (it
== setBlockIndexCandidates
.rend())
2871 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2872 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2873 CBlockIndex
*pindexTest
= pindexNew
;
2874 bool fInvalidAncestor
= false;
2875 while (pindexTest
&& !chainActive
.Contains(pindexTest
)) {
2876 assert(pindexTest
->nChainTx
|| pindexTest
->nHeight
== 0);
2878 // Pruned nodes may have entries in setBlockIndexCandidates for
2879 // which block files have been deleted. Remove those as candidates
2880 // for the most work chain if we come across them; we can't switch
2881 // to a chain unless we have all the non-active-chain parent blocks.
2882 bool fFailedChain
= pindexTest
->nStatus
& BLOCK_FAILED_MASK
;
2883 bool fMissingData
= !(pindexTest
->nStatus
& BLOCK_HAVE_DATA
);
2884 if (fFailedChain
|| fMissingData
) {
2885 // Candidate chain is not usable (either invalid or missing data)
2886 if (fFailedChain
&& (pindexBestInvalid
== NULL
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
))
2887 pindexBestInvalid
= pindexNew
;
2888 CBlockIndex
*pindexFailed
= pindexNew
;
2889 // Remove the entire chain from the set.
2890 while (pindexTest
!= pindexFailed
) {
2892 pindexFailed
->nStatus
|= BLOCK_FAILED_CHILD
;
2893 } else if (fMissingData
) {
2894 // If we're missing data, then add back to mapBlocksUnlinked,
2895 // so that if the block arrives in the future we can try adding
2896 // to setBlockIndexCandidates again.
2897 mapBlocksUnlinked
.insert(std::make_pair(pindexFailed
->pprev
, pindexFailed
));
2899 setBlockIndexCandidates
.erase(pindexFailed
);
2900 pindexFailed
= pindexFailed
->pprev
;
2902 setBlockIndexCandidates
.erase(pindexTest
);
2903 fInvalidAncestor
= true;
2906 pindexTest
= pindexTest
->pprev
;
2908 if (!fInvalidAncestor
)
2913 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2914 static void PruneBlockIndexCandidates() {
2915 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2916 // reorganization to a better block fails.
2917 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::iterator it
= setBlockIndexCandidates
.begin();
2918 while (it
!= setBlockIndexCandidates
.end() && setBlockIndexCandidates
.value_comp()(*it
, chainActive
.Tip())) {
2919 setBlockIndexCandidates
.erase(it
++);
2921 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2922 assert(!setBlockIndexCandidates
.empty());
2926 * Try to make some progress towards making pindexMostWork the active block.
2927 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2929 static bool ActivateBestChainStep(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexMostWork
, const CBlock
* pblock
, bool& fInvalidFound
, std::list
<CTransaction
>& txConflicted
, std::vector
<std::tuple
<CTransaction
,CBlockIndex
*,int>>& txChanged
)
2931 AssertLockHeld(cs_main
);
2932 const CBlockIndex
*pindexOldTip
= chainActive
.Tip();
2933 const CBlockIndex
*pindexFork
= chainActive
.FindFork(pindexMostWork
);
2935 // Disconnect active blocks which are no longer in the best chain.
2936 bool fBlocksDisconnected
= false;
2937 while (chainActive
.Tip() && chainActive
.Tip() != pindexFork
) {
2938 if (!DisconnectTip(state
, chainparams
))
2940 fBlocksDisconnected
= true;
2943 // Build list of new blocks to connect.
2944 std::vector
<CBlockIndex
*> vpindexToConnect
;
2945 bool fContinue
= true;
2946 int nHeight
= pindexFork
? pindexFork
->nHeight
: -1;
2947 while (fContinue
&& nHeight
!= pindexMostWork
->nHeight
) {
2948 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2949 // a few blocks along the way.
2950 int nTargetHeight
= std::min(nHeight
+ 32, pindexMostWork
->nHeight
);
2951 vpindexToConnect
.clear();
2952 vpindexToConnect
.reserve(nTargetHeight
- nHeight
);
2953 CBlockIndex
*pindexIter
= pindexMostWork
->GetAncestor(nTargetHeight
);
2954 while (pindexIter
&& pindexIter
->nHeight
!= nHeight
) {
2955 vpindexToConnect
.push_back(pindexIter
);
2956 pindexIter
= pindexIter
->pprev
;
2958 nHeight
= nTargetHeight
;
2960 // Connect new blocks.
2961 BOOST_REVERSE_FOREACH(CBlockIndex
*pindexConnect
, vpindexToConnect
) {
2962 if (!ConnectTip(state
, chainparams
, pindexConnect
, pindexConnect
== pindexMostWork
? pblock
: NULL
, txConflicted
, txChanged
)) {
2963 if (state
.IsInvalid()) {
2964 // The block violates a consensus rule.
2965 if (!state
.CorruptionPossible())
2966 InvalidChainFound(vpindexToConnect
.back());
2967 state
= CValidationState();
2968 fInvalidFound
= true;
2972 // A system error occurred (disk space, database error, ...).
2976 PruneBlockIndexCandidates();
2977 if (!pindexOldTip
|| chainActive
.Tip()->nChainWork
> pindexOldTip
->nChainWork
) {
2978 // We're in a better position than we were. Return temporarily to release the lock.
2986 if (fBlocksDisconnected
) {
2987 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
2988 LimitMempoolSize(mempool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
2990 mempool
.check(pcoinsTip
);
2992 // Callbacks/notifications for a new best chain.
2994 CheckForkWarningConditionsOnNewFork(vpindexToConnect
.back());
2996 CheckForkWarningConditions();
3001 static void NotifyHeaderTip() {
3002 bool fNotify
= false;
3003 bool fInitialBlockDownload
= false;
3004 static CBlockIndex
* pindexHeaderOld
= NULL
;
3005 CBlockIndex
* pindexHeader
= NULL
;
3008 pindexHeader
= pindexBestHeader
;
3010 if (pindexHeader
!= pindexHeaderOld
) {
3012 fInitialBlockDownload
= IsInitialBlockDownload();
3013 pindexHeaderOld
= pindexHeader
;
3016 // Send block tip changed notifications without cs_main
3018 uiInterface
.NotifyHeaderTip(fInitialBlockDownload
, pindexHeader
);
3023 * Make the best chain active, in multiple steps. The result is either failure
3024 * or an activated best chain. pblock is either NULL or a pointer to a block
3025 * that is already loaded (to avoid loading it again from disk).
3027 bool ActivateBestChain(CValidationState
&state
, const CChainParams
& chainparams
, const CBlock
*pblock
) {
3028 CBlockIndex
*pindexMostWork
= NULL
;
3029 CBlockIndex
*pindexNewTip
= NULL
;
3030 std::vector
<std::tuple
<CTransaction
,CBlockIndex
*,int>> txChanged
;
3032 txChanged
.reserve(pblock
->vtx
.size());
3035 boost::this_thread::interruption_point();
3036 if (ShutdownRequested())
3039 const CBlockIndex
*pindexFork
;
3040 std::list
<CTransaction
> txConflicted
;
3041 bool fInitialDownload
;
3044 CBlockIndex
*pindexOldTip
= chainActive
.Tip();
3045 if (pindexMostWork
== NULL
) {
3046 pindexMostWork
= FindMostWorkChain();
3049 // Whether we have anything to do at all.
3050 if (pindexMostWork
== NULL
|| pindexMostWork
== chainActive
.Tip())
3053 bool fInvalidFound
= false;
3054 if (!ActivateBestChainStep(state
, chainparams
, pindexMostWork
, pblock
&& pblock
->GetHash() == pindexMostWork
->GetBlockHash() ? pblock
: NULL
, fInvalidFound
, txConflicted
, txChanged
))
3057 if (fInvalidFound
) {
3058 // Wipe cache, we may need another branch now.
3059 pindexMostWork
= NULL
;
3061 pindexNewTip
= chainActive
.Tip();
3062 pindexFork
= chainActive
.FindFork(pindexOldTip
);
3063 fInitialDownload
= IsInitialBlockDownload();
3065 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3067 // Notifications/callbacks that can run without cs_main
3069 // throw all transactions though the signal-interface
3070 // while _not_ holding the cs_main lock
3071 BOOST_FOREACH(const CTransaction
&tx
, txConflicted
)
3073 GetMainSignals().SyncTransaction(tx
, pindexNewTip
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
3075 // ... and about transactions that got confirmed:
3076 for(unsigned int i
= 0; i
< txChanged
.size(); i
++)
3077 GetMainSignals().SyncTransaction(std::get
<0>(txChanged
[i
]), std::get
<1>(txChanged
[i
]), std::get
<2>(txChanged
[i
]));
3079 // Notify external listeners about the new tip.
3080 GetMainSignals().UpdatedBlockTip(pindexNewTip
, pindexFork
, fInitialDownload
);
3082 // Always notify the UI if a new block tip was connected
3083 if (pindexFork
!= pindexNewTip
) {
3084 uiInterface
.NotifyBlockTip(fInitialDownload
, pindexNewTip
);
3086 } while (pindexNewTip
!= pindexMostWork
);
3087 CheckBlockIndex(chainparams
.GetConsensus());
3089 // Write changes periodically to disk, after relay.
3090 if (!FlushStateToDisk(state
, FLUSH_STATE_PERIODIC
)) {
3098 bool PreciousBlock(CValidationState
& state
, const CChainParams
& params
, CBlockIndex
*pindex
)
3102 if (pindex
->nChainWork
< chainActive
.Tip()->nChainWork
) {
3103 // Nothing to do, this block is not at the tip.
3106 if (chainActive
.Tip()->nChainWork
> nLastPreciousChainwork
) {
3107 // The chain has been extended since the last call, reset the counter.
3108 nBlockReverseSequenceId
= -1;
3110 nLastPreciousChainwork
= chainActive
.Tip()->nChainWork
;
3111 setBlockIndexCandidates
.erase(pindex
);
3112 pindex
->nSequenceId
= nBlockReverseSequenceId
;
3113 if (nBlockReverseSequenceId
> std::numeric_limits
<int32_t>::min()) {
3114 // We can't keep reducing the counter if somebody really wants to
3115 // call preciousblock 2**31-1 times on the same set of tips...
3116 nBlockReverseSequenceId
--;
3118 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindex
->nChainTx
) {
3119 setBlockIndexCandidates
.insert(pindex
);
3120 PruneBlockIndexCandidates();
3124 return ActivateBestChain(state
, params
);
3127 bool InvalidateBlock(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
*pindex
)
3129 AssertLockHeld(cs_main
);
3131 // Mark the block itself as invalid.
3132 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
3133 setDirtyBlockIndex
.insert(pindex
);
3134 setBlockIndexCandidates
.erase(pindex
);
3136 while (chainActive
.Contains(pindex
)) {
3137 CBlockIndex
*pindexWalk
= chainActive
.Tip();
3138 pindexWalk
->nStatus
|= BLOCK_FAILED_CHILD
;
3139 setDirtyBlockIndex
.insert(pindexWalk
);
3140 setBlockIndexCandidates
.erase(pindexWalk
);
3141 // ActivateBestChain considers blocks already in chainActive
3142 // unconditionally valid already, so force disconnect away from it.
3143 if (!DisconnectTip(state
, chainparams
)) {
3144 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
3149 LimitMempoolSize(mempool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
3151 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3153 BlockMap::iterator it
= mapBlockIndex
.begin();
3154 while (it
!= mapBlockIndex
.end()) {
3155 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& !setBlockIndexCandidates
.value_comp()(it
->second
, chainActive
.Tip())) {
3156 setBlockIndexCandidates
.insert(it
->second
);
3161 InvalidChainFound(pindex
);
3162 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
3166 bool ResetBlockFailureFlags(CBlockIndex
*pindex
) {
3167 AssertLockHeld(cs_main
);
3169 int nHeight
= pindex
->nHeight
;
3171 // Remove the invalidity flag from this block and all its descendants.
3172 BlockMap::iterator it
= mapBlockIndex
.begin();
3173 while (it
!= mapBlockIndex
.end()) {
3174 if (!it
->second
->IsValid() && it
->second
->GetAncestor(nHeight
) == pindex
) {
3175 it
->second
->nStatus
&= ~BLOCK_FAILED_MASK
;
3176 setDirtyBlockIndex
.insert(it
->second
);
3177 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& setBlockIndexCandidates
.value_comp()(chainActive
.Tip(), it
->second
)) {
3178 setBlockIndexCandidates
.insert(it
->second
);
3180 if (it
->second
== pindexBestInvalid
) {
3181 // Reset invalid block marker if it was pointing to one of those.
3182 pindexBestInvalid
= NULL
;
3188 // Remove the invalidity flag from all ancestors too.
3189 while (pindex
!= NULL
) {
3190 if (pindex
->nStatus
& BLOCK_FAILED_MASK
) {
3191 pindex
->nStatus
&= ~BLOCK_FAILED_MASK
;
3192 setDirtyBlockIndex
.insert(pindex
);
3194 pindex
= pindex
->pprev
;
3199 CBlockIndex
* AddToBlockIndex(const CBlockHeader
& block
)
3201 // Check for duplicate
3202 uint256 hash
= block
.GetHash();
3203 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
3204 if (it
!= mapBlockIndex
.end())
3207 // Construct new block index object
3208 CBlockIndex
* pindexNew
= new CBlockIndex(block
);
3210 // We assign the sequence id to blocks only when the full data is available,
3211 // to avoid miners withholding blocks but broadcasting headers, to get a
3212 // competitive advantage.
3213 pindexNew
->nSequenceId
= 0;
3214 BlockMap::iterator mi
= mapBlockIndex
.insert(make_pair(hash
, pindexNew
)).first
;
3215 pindexNew
->phashBlock
= &((*mi
).first
);
3216 BlockMap::iterator miPrev
= mapBlockIndex
.find(block
.hashPrevBlock
);
3217 if (miPrev
!= mapBlockIndex
.end())
3219 pindexNew
->pprev
= (*miPrev
).second
;
3220 pindexNew
->nHeight
= pindexNew
->pprev
->nHeight
+ 1;
3221 pindexNew
->BuildSkip();
3223 pindexNew
->nChainWork
= (pindexNew
->pprev
? pindexNew
->pprev
->nChainWork
: 0) + GetBlockProof(*pindexNew
);
3224 pindexNew
->RaiseValidity(BLOCK_VALID_TREE
);
3225 if (pindexBestHeader
== NULL
|| pindexBestHeader
->nChainWork
< pindexNew
->nChainWork
)
3226 pindexBestHeader
= pindexNew
;
3228 setDirtyBlockIndex
.insert(pindexNew
);
3233 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3234 bool ReceivedBlockTransactions(const CBlock
&block
, CValidationState
& state
, CBlockIndex
*pindexNew
, const CDiskBlockPos
& pos
)
3236 pindexNew
->nTx
= block
.vtx
.size();
3237 pindexNew
->nChainTx
= 0;
3238 pindexNew
->nFile
= pos
.nFile
;
3239 pindexNew
->nDataPos
= pos
.nPos
;
3240 pindexNew
->nUndoPos
= 0;
3241 pindexNew
->nStatus
|= BLOCK_HAVE_DATA
;
3242 if (IsWitnessEnabled(pindexNew
->pprev
, Params().GetConsensus())) {
3243 pindexNew
->nStatus
|= BLOCK_OPT_WITNESS
;
3245 pindexNew
->RaiseValidity(BLOCK_VALID_TRANSACTIONS
);
3246 setDirtyBlockIndex
.insert(pindexNew
);
3248 if (pindexNew
->pprev
== NULL
|| pindexNew
->pprev
->nChainTx
) {
3249 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3250 deque
<CBlockIndex
*> queue
;
3251 queue
.push_back(pindexNew
);
3253 // Recursively process any descendant blocks that now may be eligible to be connected.
3254 while (!queue
.empty()) {
3255 CBlockIndex
*pindex
= queue
.front();
3257 pindex
->nChainTx
= (pindex
->pprev
? pindex
->pprev
->nChainTx
: 0) + pindex
->nTx
;
3259 LOCK(cs_nBlockSequenceId
);
3260 pindex
->nSequenceId
= nBlockSequenceId
++;
3262 if (chainActive
.Tip() == NULL
|| !setBlockIndexCandidates
.value_comp()(pindex
, chainActive
.Tip())) {
3263 setBlockIndexCandidates
.insert(pindex
);
3265 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
);
3266 while (range
.first
!= range
.second
) {
3267 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator it
= range
.first
;
3268 queue
.push_back(it
->second
);
3270 mapBlocksUnlinked
.erase(it
);
3274 if (pindexNew
->pprev
&& pindexNew
->pprev
->IsValid(BLOCK_VALID_TREE
)) {
3275 mapBlocksUnlinked
.insert(std::make_pair(pindexNew
->pprev
, pindexNew
));
3282 bool FindBlockPos(CValidationState
&state
, CDiskBlockPos
&pos
, unsigned int nAddSize
, unsigned int nHeight
, uint64_t nTime
, bool fKnown
= false)
3284 LOCK(cs_LastBlockFile
);
3286 unsigned int nFile
= fKnown
? pos
.nFile
: nLastBlockFile
;
3287 if (vinfoBlockFile
.size() <= nFile
) {
3288 vinfoBlockFile
.resize(nFile
+ 1);
3292 while (vinfoBlockFile
[nFile
].nSize
+ nAddSize
>= MAX_BLOCKFILE_SIZE
) {
3294 if (vinfoBlockFile
.size() <= nFile
) {
3295 vinfoBlockFile
.resize(nFile
+ 1);
3299 pos
.nPos
= vinfoBlockFile
[nFile
].nSize
;
3302 if ((int)nFile
!= nLastBlockFile
) {
3304 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile
, vinfoBlockFile
[nLastBlockFile
].ToString());
3306 FlushBlockFile(!fKnown
);
3307 nLastBlockFile
= nFile
;
3310 vinfoBlockFile
[nFile
].AddBlock(nHeight
, nTime
);
3312 vinfoBlockFile
[nFile
].nSize
= std::max(pos
.nPos
+ nAddSize
, vinfoBlockFile
[nFile
].nSize
);
3314 vinfoBlockFile
[nFile
].nSize
+= nAddSize
;
3317 unsigned int nOldChunks
= (pos
.nPos
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
3318 unsigned int nNewChunks
= (vinfoBlockFile
[nFile
].nSize
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
3319 if (nNewChunks
> nOldChunks
) {
3321 fCheckForPruning
= true;
3322 if (CheckDiskSpace(nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
)) {
3323 FILE *file
= OpenBlockFile(pos
);
3325 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks
* BLOCKFILE_CHUNK_SIZE
, pos
.nFile
);
3326 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
);
3331 return state
.Error("out of disk space");
3335 setDirtyFileInfo
.insert(nFile
);
3339 bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
)
3343 LOCK(cs_LastBlockFile
);
3345 unsigned int nNewSize
;
3346 pos
.nPos
= vinfoBlockFile
[nFile
].nUndoSize
;
3347 nNewSize
= vinfoBlockFile
[nFile
].nUndoSize
+= nAddSize
;
3348 setDirtyFileInfo
.insert(nFile
);
3350 unsigned int nOldChunks
= (pos
.nPos
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
3351 unsigned int nNewChunks
= (nNewSize
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
3352 if (nNewChunks
> nOldChunks
) {
3354 fCheckForPruning
= true;
3355 if (CheckDiskSpace(nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
)) {
3356 FILE *file
= OpenUndoFile(pos
);
3358 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks
* UNDOFILE_CHUNK_SIZE
, pos
.nFile
);
3359 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
);
3364 return state
.Error("out of disk space");
3370 bool CheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
)
3372 // Check proof of work matches claimed amount
3373 if (fCheckPOW
&& !CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
3374 return state
.DoS(50, false, REJECT_INVALID
, "high-hash", false, "proof of work failed");
3379 bool CheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
, bool fCheckMerkleRoot
)
3381 // These are checks that are independent of context.
3386 // Check that the header is valid (particularly PoW). This is mostly
3387 // redundant with the call in AcceptBlockHeader.
3388 if (!CheckBlockHeader(block
, state
, consensusParams
, fCheckPOW
))
3391 // Check the merkle root.
3392 if (fCheckMerkleRoot
) {
3394 uint256 hashMerkleRoot2
= BlockMerkleRoot(block
, &mutated
);
3395 if (block
.hashMerkleRoot
!= hashMerkleRoot2
)
3396 return state
.DoS(100, false, REJECT_INVALID
, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
3398 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3399 // of transactions in a block without affecting the merkle root of a block,
3400 // while still invalidating it.
3402 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-duplicate", true, "duplicate transaction");
3405 // All potential-corruption validation must be done before we do any
3406 // transaction validation, as otherwise we may mark the header as invalid
3407 // because we receive the wrong transactions for it.
3408 // Note that witness malleability is checked in ContextualCheckBlock, so no
3409 // checks that use witness data may be performed here.
3412 if (block
.vtx
.empty() || block
.vtx
.size() > MAX_BLOCK_BASE_SIZE
|| ::GetSerializeSize(block
, SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
) > MAX_BLOCK_BASE_SIZE
)
3413 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-length", false, "size limits failed");
3415 // First transaction must be coinbase, the rest must not be
3416 if (block
.vtx
.empty() || !block
.vtx
[0].IsCoinBase())
3417 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-missing", false, "first tx is not coinbase");
3418 for (unsigned int i
= 1; i
< block
.vtx
.size(); i
++)
3419 if (block
.vtx
[i
].IsCoinBase())
3420 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-multiple", false, "more than one coinbase");
3422 // Check transactions
3423 for (const auto& tx
: block
.vtx
)
3424 if (!CheckTransaction(tx
, state
))
3425 return state
.Invalid(false, state
.GetRejectCode(), state
.GetRejectReason(),
3426 strprintf("Transaction check failed (tx hash %s) %s", tx
.GetHash().ToString(), state
.GetDebugMessage()));
3428 unsigned int nSigOps
= 0;
3429 for (const auto& tx
: block
.vtx
)
3431 nSigOps
+= GetLegacySigOpCount(tx
);
3433 if (nSigOps
* WITNESS_SCALE_FACTOR
> MAX_BLOCK_SIGOPS_COST
)
3434 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3436 if (fCheckPOW
&& fCheckMerkleRoot
)
3437 block
.fChecked
= true;
3442 static bool CheckIndexAgainstCheckpoint(const CBlockIndex
* pindexPrev
, CValidationState
& state
, const CChainParams
& chainparams
, const uint256
& hash
)
3444 if (*pindexPrev
->phashBlock
== chainparams
.GetConsensus().hashGenesisBlock
)
3447 int nHeight
= pindexPrev
->nHeight
+1;
3448 // Don't accept any forks from the main chain prior to last checkpoint
3449 CBlockIndex
* pcheckpoint
= Checkpoints::GetLastCheckpoint(chainparams
.Checkpoints());
3450 if (pcheckpoint
&& nHeight
< pcheckpoint
->nHeight
)
3451 return state
.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__
, nHeight
));
3456 bool IsWitnessEnabled(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
3459 return (VersionBitsState(pindexPrev
, params
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
);
3462 // Compute at which vout of the block's coinbase transaction the witness
3463 // commitment occurs, or -1 if not found.
3464 static int GetWitnessCommitmentIndex(const CBlock
& block
)
3467 for (size_t o
= 0; o
< block
.vtx
[0].vout
.size(); o
++) {
3468 if (block
.vtx
[0].vout
[o
].scriptPubKey
.size() >= 38 && block
.vtx
[0].vout
[o
].scriptPubKey
[0] == OP_RETURN
&& block
.vtx
[0].vout
[o
].scriptPubKey
[1] == 0x24 && block
.vtx
[0].vout
[o
].scriptPubKey
[2] == 0xaa && block
.vtx
[0].vout
[o
].scriptPubKey
[3] == 0x21 && block
.vtx
[0].vout
[o
].scriptPubKey
[4] == 0xa9 && block
.vtx
[0].vout
[o
].scriptPubKey
[5] == 0xed) {
3475 void UpdateUncommittedBlockStructures(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
3477 int commitpos
= GetWitnessCommitmentIndex(block
);
3478 static const std::vector
<unsigned char> nonce(32, 0x00);
3479 if (commitpos
!= -1 && IsWitnessEnabled(pindexPrev
, consensusParams
) && block
.vtx
[0].wit
.IsEmpty()) {
3480 block
.vtx
[0].wit
.vtxinwit
.resize(1);
3481 block
.vtx
[0].wit
.vtxinwit
[0].scriptWitness
.stack
.resize(1);
3482 block
.vtx
[0].wit
.vtxinwit
[0].scriptWitness
.stack
[0] = nonce
;
3486 std::vector
<unsigned char> GenerateCoinbaseCommitment(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
3488 std::vector
<unsigned char> commitment
;
3489 int commitpos
= GetWitnessCommitmentIndex(block
);
3490 bool fHaveWitness
= false;
3491 for (size_t t
= 1; t
< block
.vtx
.size(); t
++) {
3492 if (!block
.vtx
[t
].wit
.IsNull()) {
3493 fHaveWitness
= true;
3497 std::vector
<unsigned char> ret(32, 0x00);
3498 if (fHaveWitness
&& IsWitnessEnabled(pindexPrev
, consensusParams
)) {
3499 if (commitpos
== -1) {
3500 uint256 witnessroot
= BlockWitnessMerkleRoot(block
, NULL
);
3501 CHash256().Write(witnessroot
.begin(), 32).Write(&ret
[0], 32).Finalize(witnessroot
.begin());
3504 out
.scriptPubKey
.resize(38);
3505 out
.scriptPubKey
[0] = OP_RETURN
;
3506 out
.scriptPubKey
[1] = 0x24;
3507 out
.scriptPubKey
[2] = 0xaa;
3508 out
.scriptPubKey
[3] = 0x21;
3509 out
.scriptPubKey
[4] = 0xa9;
3510 out
.scriptPubKey
[5] = 0xed;
3511 memcpy(&out
.scriptPubKey
[6], witnessroot
.begin(), 32);
3512 commitment
= std::vector
<unsigned char>(out
.scriptPubKey
.begin(), out
.scriptPubKey
.end());
3513 const_cast<std::vector
<CTxOut
>*>(&block
.vtx
[0].vout
)->push_back(out
);
3514 block
.vtx
[0].UpdateHash();
3517 UpdateUncommittedBlockStructures(block
, pindexPrev
, consensusParams
);
3521 bool ContextualCheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
, int64_t nAdjustedTime
)
3523 const int nHeight
= pindexPrev
== NULL
? 0 : pindexPrev
->nHeight
+ 1;
3524 // Check proof of work
3525 if (block
.nBits
!= GetNextWorkRequired(pindexPrev
, &block
, consensusParams
))
3526 return state
.DoS(100, false, REJECT_INVALID
, "bad-diffbits", false, "incorrect proof of work");
3528 // Check timestamp against prev
3529 if (block
.GetBlockTime() <= pindexPrev
->GetMedianTimePast())
3530 return state
.Invalid(false, REJECT_INVALID
, "time-too-old", "block's timestamp is too early");
3533 if (block
.GetBlockTime() > nAdjustedTime
+ 2 * 60 * 60)
3534 return state
.Invalid(false, REJECT_INVALID
, "time-too-new", "block timestamp too far in the future");
3536 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3537 // check for version 2, 3 and 4 upgrades
3538 if((block
.nVersion
< 2 && nHeight
>= consensusParams
.BIP34Height
) ||
3539 (block
.nVersion
< 3 && nHeight
>= consensusParams
.BIP66Height
) ||
3540 (block
.nVersion
< 4 && nHeight
>= consensusParams
.BIP65Height
))
3541 return state
.Invalid(false, REJECT_OBSOLETE
, strprintf("bad-version(0x%08x)", block
.nVersion
),
3542 strprintf("rejected nVersion=0x%08x block", block
.nVersion
));
3547 bool ContextualCheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
)
3549 const int nHeight
= pindexPrev
== NULL
? 0 : pindexPrev
->nHeight
+ 1;
3551 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3552 int nLockTimeFlags
= 0;
3553 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
3554 nLockTimeFlags
|= LOCKTIME_MEDIAN_TIME_PAST
;
3557 int64_t nLockTimeCutoff
= (nLockTimeFlags
& LOCKTIME_MEDIAN_TIME_PAST
)
3558 ? pindexPrev
->GetMedianTimePast()
3559 : block
.GetBlockTime();
3561 // Check that all transactions are finalized
3562 for (const auto& tx
: block
.vtx
) {
3563 if (!IsFinalTx(tx
, nHeight
, nLockTimeCutoff
)) {
3564 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-nonfinal", false, "non-final transaction");
3568 // Enforce rule that the coinbase starts with serialized block height
3569 if (nHeight
>= consensusParams
.BIP34Height
)
3571 CScript expect
= CScript() << nHeight
;
3572 if (block
.vtx
[0].vin
[0].scriptSig
.size() < expect
.size() ||
3573 !std::equal(expect
.begin(), expect
.end(), block
.vtx
[0].vin
[0].scriptSig
.begin())) {
3574 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-height", false, "block height mismatch in coinbase");
3578 // Validation for witness commitments.
3579 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3580 // coinbase (where 0x0000....0000 is used instead).
3581 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3582 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3583 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3584 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3585 // multiple, the last one is used.
3586 bool fHaveWitness
= false;
3587 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
) {
3588 int commitpos
= GetWitnessCommitmentIndex(block
);
3589 if (commitpos
!= -1) {
3590 bool malleated
= false;
3591 uint256 hashWitness
= BlockWitnessMerkleRoot(block
, &malleated
);
3592 // The malleation check is ignored; as the transaction tree itself
3593 // already does not permit it, it is impossible to trigger in the
3595 if (block
.vtx
[0].wit
.vtxinwit
.size() != 1 || block
.vtx
[0].wit
.vtxinwit
[0].scriptWitness
.stack
.size() != 1 || block
.vtx
[0].wit
.vtxinwit
[0].scriptWitness
.stack
[0].size() != 32) {
3596 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__
));
3598 CHash256().Write(hashWitness
.begin(), 32).Write(&block
.vtx
[0].wit
.vtxinwit
[0].scriptWitness
.stack
[0][0], 32).Finalize(hashWitness
.begin());
3599 if (memcmp(hashWitness
.begin(), &block
.vtx
[0].vout
[commitpos
].scriptPubKey
[6], 32)) {
3600 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__
));
3602 fHaveWitness
= true;
3606 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3607 if (!fHaveWitness
) {
3608 for (size_t i
= 0; i
< block
.vtx
.size(); i
++) {
3609 if (!block
.vtx
[i
].wit
.IsNull()) {
3610 return state
.DoS(100, false, REJECT_INVALID
, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__
));
3615 // After the coinbase witness nonce and commitment are verified,
3616 // we can check if the block weight passes (before we've checked the
3617 // coinbase witness, it would be possible for the weight to be too
3618 // large by filling up the coinbase witness, which doesn't change
3619 // the block hash, so we couldn't mark the block as permanently
3621 if (GetBlockWeight(block
) > MAX_BLOCK_WEIGHT
) {
3622 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__
));
3628 static bool AcceptBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
=NULL
)
3630 AssertLockHeld(cs_main
);
3631 // Check for duplicate
3632 uint256 hash
= block
.GetHash();
3633 BlockMap::iterator miSelf
= mapBlockIndex
.find(hash
);
3634 CBlockIndex
*pindex
= NULL
;
3635 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
) {
3637 if (miSelf
!= mapBlockIndex
.end()) {
3638 // Block header is already known.
3639 pindex
= miSelf
->second
;
3642 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
3643 return state
.Invalid(error("%s: block %s is marked invalid", __func__
, hash
.ToString()), 0, "duplicate");
3647 if (!CheckBlockHeader(block
, state
, chainparams
.GetConsensus()))
3648 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
3650 // Get prev block index
3651 CBlockIndex
* pindexPrev
= NULL
;
3652 BlockMap::iterator mi
= mapBlockIndex
.find(block
.hashPrevBlock
);
3653 if (mi
== mapBlockIndex
.end())
3654 return state
.DoS(10, error("%s: prev block not found", __func__
), 0, "bad-prevblk");
3655 pindexPrev
= (*mi
).second
;
3656 if (pindexPrev
->nStatus
& BLOCK_FAILED_MASK
)
3657 return state
.DoS(100, error("%s: prev block invalid", __func__
), REJECT_INVALID
, "bad-prevblk");
3660 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, hash
))
3661 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
3663 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
3664 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
3667 pindex
= AddToBlockIndex(block
);
3675 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3676 static bool AcceptBlock(const CBlock
& block
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
, bool fRequested
, const CDiskBlockPos
* dbp
, bool* fNewBlock
)
3678 if (fNewBlock
) *fNewBlock
= false;
3679 AssertLockHeld(cs_main
);
3681 CBlockIndex
*pindexDummy
= NULL
;
3682 CBlockIndex
*&pindex
= ppindex
? *ppindex
: pindexDummy
;
3684 if (!AcceptBlockHeader(block
, state
, chainparams
, &pindex
))
3687 // Try to process all requested blocks that we don't have, but only
3688 // process an unrequested block if it's new and has enough work to
3689 // advance our tip, and isn't too many blocks ahead.
3690 bool fAlreadyHave
= pindex
->nStatus
& BLOCK_HAVE_DATA
;
3691 bool fHasMoreWork
= (chainActive
.Tip() ? pindex
->nChainWork
> chainActive
.Tip()->nChainWork
: true);
3692 // Blocks that are too out-of-order needlessly limit the effectiveness of
3693 // pruning, because pruning will not delete block files that contain any
3694 // blocks which are too close in height to the tip. Apply this test
3695 // regardless of whether pruning is enabled; it should generally be safe to
3696 // not process unrequested blocks.
3697 bool fTooFarAhead
= (pindex
->nHeight
> int(chainActive
.Height() + MIN_BLOCKS_TO_KEEP
));
3699 // TODO: deal better with return value and error conditions for duplicate
3700 // and unrequested blocks.
3701 if (fAlreadyHave
) return true;
3702 if (!fRequested
) { // If we didn't ask for it:
3703 if (pindex
->nTx
!= 0) return true; // This is a previously-processed block that was pruned
3704 if (!fHasMoreWork
) return true; // Don't process less-work chains
3705 if (fTooFarAhead
) return true; // Block height is too high
3707 if (fNewBlock
) *fNewBlock
= true;
3709 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), GetAdjustedTime()) ||
3710 !ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindex
->pprev
)) {
3711 if (state
.IsInvalid() && !state
.CorruptionPossible()) {
3712 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
3713 setDirtyBlockIndex
.insert(pindex
);
3715 return error("%s: %s", __func__
, FormatStateMessage(state
));
3718 int nHeight
= pindex
->nHeight
;
3720 // Write block to history file
3722 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
3723 CDiskBlockPos blockPos
;
3726 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, nHeight
, block
.GetBlockTime(), dbp
!= NULL
))
3727 return error("AcceptBlock(): FindBlockPos failed");
3729 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
3730 AbortNode(state
, "Failed to write block");
3731 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
))
3732 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3733 } catch (const std::runtime_error
& e
) {
3734 return AbortNode(state
, std::string("System error: ") + e
.what());
3737 if (fCheckForPruning
)
3738 FlushStateToDisk(state
, FLUSH_STATE_NONE
); // we just allocated more disk space for block files
3743 bool ProcessNewBlock(CValidationState
& state
, const CChainParams
& chainparams
, CNode
* pfrom
, const CBlock
* pblock
, bool fForceProcessing
, const CDiskBlockPos
* dbp
)
3747 bool fRequested
= MarkBlockAsReceived(pblock
->GetHash());
3748 fRequested
|= fForceProcessing
;
3751 CBlockIndex
*pindex
= NULL
;
3752 bool fNewBlock
= false;
3753 bool ret
= AcceptBlock(*pblock
, state
, chainparams
, &pindex
, fRequested
, dbp
, &fNewBlock
);
3754 if (pindex
&& pfrom
) {
3755 mapBlockSource
[pindex
->GetBlockHash()] = pfrom
->GetId();
3756 if (fNewBlock
) pfrom
->nLastBlockTime
= GetTime();
3758 CheckBlockIndex(chainparams
.GetConsensus());
3760 return error("%s: AcceptBlock FAILED", __func__
);
3765 if (!ActivateBestChain(state
, chainparams
, pblock
))
3766 return error("%s: ActivateBestChain failed", __func__
);
3771 bool TestBlockValidity(CValidationState
& state
, const CChainParams
& chainparams
, const CBlock
& block
, CBlockIndex
* pindexPrev
, bool fCheckPOW
, bool fCheckMerkleRoot
)
3773 AssertLockHeld(cs_main
);
3774 assert(pindexPrev
&& pindexPrev
== chainActive
.Tip());
3775 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, block
.GetHash()))
3776 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
3778 CCoinsViewCache
viewNew(pcoinsTip
);
3779 CBlockIndex
indexDummy(block
);
3780 indexDummy
.pprev
= pindexPrev
;
3781 indexDummy
.nHeight
= pindexPrev
->nHeight
+ 1;
3783 // NOTE: CheckBlockHeader is called by CheckBlock
3784 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
3785 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__
, FormatStateMessage(state
));
3786 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), fCheckPOW
, fCheckMerkleRoot
))
3787 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
3788 if (!ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindexPrev
))
3789 return error("%s: Consensus::ContextualCheckBlock: %s", __func__
, FormatStateMessage(state
));
3790 if (!ConnectBlock(block
, state
, &indexDummy
, viewNew
, chainparams
, true))
3792 assert(state
.IsValid());
3798 * BLOCK PRUNING CODE
3801 /* Calculate the amount of disk space the block & undo files currently use */
3802 uint64_t CalculateCurrentUsage()
3804 uint64_t retval
= 0;
3805 BOOST_FOREACH(const CBlockFileInfo
&file
, vinfoBlockFile
) {
3806 retval
+= file
.nSize
+ file
.nUndoSize
;
3811 /* Prune a block file (modify associated database entries)*/
3812 void PruneOneBlockFile(const int fileNumber
)
3814 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); ++it
) {
3815 CBlockIndex
* pindex
= it
->second
;
3816 if (pindex
->nFile
== fileNumber
) {
3817 pindex
->nStatus
&= ~BLOCK_HAVE_DATA
;
3818 pindex
->nStatus
&= ~BLOCK_HAVE_UNDO
;
3820 pindex
->nDataPos
= 0;
3821 pindex
->nUndoPos
= 0;
3822 setDirtyBlockIndex
.insert(pindex
);
3824 // Prune from mapBlocksUnlinked -- any block we prune would have
3825 // to be downloaded again in order to consider its chain, at which
3826 // point it would be considered as a candidate for
3827 // mapBlocksUnlinked or setBlockIndexCandidates.
3828 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
3829 while (range
.first
!= range
.second
) {
3830 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator _it
= range
.first
;
3832 if (_it
->second
== pindex
) {
3833 mapBlocksUnlinked
.erase(_it
);
3839 vinfoBlockFile
[fileNumber
].SetNull();
3840 setDirtyFileInfo
.insert(fileNumber
);
3844 void UnlinkPrunedFiles(std::set
<int>& setFilesToPrune
)
3846 for (set
<int>::iterator it
= setFilesToPrune
.begin(); it
!= setFilesToPrune
.end(); ++it
) {
3847 CDiskBlockPos
pos(*it
, 0);
3848 boost::filesystem::remove(GetBlockPosFilename(pos
, "blk"));
3849 boost::filesystem::remove(GetBlockPosFilename(pos
, "rev"));
3850 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__
, *it
);
3854 /* Calculate the block/rev files that should be deleted to remain under target*/
3855 void FindFilesToPrune(std::set
<int>& setFilesToPrune
, uint64_t nPruneAfterHeight
)
3857 LOCK2(cs_main
, cs_LastBlockFile
);
3858 if (chainActive
.Tip() == NULL
|| nPruneTarget
== 0) {
3861 if ((uint64_t)chainActive
.Tip()->nHeight
<= nPruneAfterHeight
) {
3865 unsigned int nLastBlockWeCanPrune
= chainActive
.Tip()->nHeight
- MIN_BLOCKS_TO_KEEP
;
3866 uint64_t nCurrentUsage
= CalculateCurrentUsage();
3867 // We don't check to prune until after we've allocated new space for files
3868 // So we should leave a buffer under our target to account for another allocation
3869 // before the next pruning.
3870 uint64_t nBuffer
= BLOCKFILE_CHUNK_SIZE
+ UNDOFILE_CHUNK_SIZE
;
3871 uint64_t nBytesToPrune
;
3874 if (nCurrentUsage
+ nBuffer
>= nPruneTarget
) {
3875 for (int fileNumber
= 0; fileNumber
< nLastBlockFile
; fileNumber
++) {
3876 nBytesToPrune
= vinfoBlockFile
[fileNumber
].nSize
+ vinfoBlockFile
[fileNumber
].nUndoSize
;
3878 if (vinfoBlockFile
[fileNumber
].nSize
== 0)
3881 if (nCurrentUsage
+ nBuffer
< nPruneTarget
) // are we below our target?
3884 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3885 if (vinfoBlockFile
[fileNumber
].nHeightLast
> nLastBlockWeCanPrune
)
3888 PruneOneBlockFile(fileNumber
);
3889 // Queue up the files for removal
3890 setFilesToPrune
.insert(fileNumber
);
3891 nCurrentUsage
-= nBytesToPrune
;
3896 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3897 nPruneTarget
/1024/1024, nCurrentUsage
/1024/1024,
3898 ((int64_t)nPruneTarget
- (int64_t)nCurrentUsage
)/1024/1024,
3899 nLastBlockWeCanPrune
, count
);
3902 bool CheckDiskSpace(uint64_t nAdditionalBytes
)
3904 uint64_t nFreeBytesAvailable
= boost::filesystem::space(GetDataDir()).available
;
3906 // Check for nMinDiskSpace bytes (currently 50MB)
3907 if (nFreeBytesAvailable
< nMinDiskSpace
+ nAdditionalBytes
)
3908 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3913 FILE* OpenDiskFile(const CDiskBlockPos
&pos
, const char *prefix
, bool fReadOnly
)
3917 boost::filesystem::path path
= GetBlockPosFilename(pos
, prefix
);
3918 boost::filesystem::create_directories(path
.parent_path());
3919 FILE* file
= fopen(path
.string().c_str(), "rb+");
3920 if (!file
&& !fReadOnly
)
3921 file
= fopen(path
.string().c_str(), "wb+");
3923 LogPrintf("Unable to open file %s\n", path
.string());
3927 if (fseek(file
, pos
.nPos
, SEEK_SET
)) {
3928 LogPrintf("Unable to seek to position %u of %s\n", pos
.nPos
, path
.string());
3936 FILE* OpenBlockFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3937 return OpenDiskFile(pos
, "blk", fReadOnly
);
3940 FILE* OpenUndoFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3941 return OpenDiskFile(pos
, "rev", fReadOnly
);
3944 boost::filesystem::path
GetBlockPosFilename(const CDiskBlockPos
&pos
, const char *prefix
)
3946 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix
, pos
.nFile
);
3949 CBlockIndex
* InsertBlockIndex(uint256 hash
)
3955 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
3956 if (mi
!= mapBlockIndex
.end())
3957 return (*mi
).second
;
3960 CBlockIndex
* pindexNew
= new CBlockIndex();
3962 throw runtime_error(std::string(__func__
) + ": new CBlockIndex failed");
3963 mi
= mapBlockIndex
.insert(make_pair(hash
, pindexNew
)).first
;
3964 pindexNew
->phashBlock
= &((*mi
).first
);
3969 bool static LoadBlockIndexDB()
3971 const CChainParams
& chainparams
= Params();
3972 if (!pblocktree
->LoadBlockIndexGuts(InsertBlockIndex
))
3975 boost::this_thread::interruption_point();
3977 // Calculate nChainWork
3978 vector
<pair
<int, CBlockIndex
*> > vSortedByHeight
;
3979 vSortedByHeight
.reserve(mapBlockIndex
.size());
3980 BOOST_FOREACH(const PAIRTYPE(uint256
, CBlockIndex
*)& item
, mapBlockIndex
)
3982 CBlockIndex
* pindex
= item
.second
;
3983 vSortedByHeight
.push_back(make_pair(pindex
->nHeight
, pindex
));
3985 sort(vSortedByHeight
.begin(), vSortedByHeight
.end());
3986 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex
*)& item
, vSortedByHeight
)
3988 CBlockIndex
* pindex
= item
.second
;
3989 pindex
->nChainWork
= (pindex
->pprev
? pindex
->pprev
->nChainWork
: 0) + GetBlockProof(*pindex
);
3990 // We can link the chain of blocks for which we've received transactions at some point.
3991 // Pruned nodes may have deleted the block.
3992 if (pindex
->nTx
> 0) {
3993 if (pindex
->pprev
) {
3994 if (pindex
->pprev
->nChainTx
) {
3995 pindex
->nChainTx
= pindex
->pprev
->nChainTx
+ pindex
->nTx
;
3997 pindex
->nChainTx
= 0;
3998 mapBlocksUnlinked
.insert(std::make_pair(pindex
->pprev
, pindex
));
4001 pindex
->nChainTx
= pindex
->nTx
;
4004 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && (pindex
->nChainTx
|| pindex
->pprev
== NULL
))
4005 setBlockIndexCandidates
.insert(pindex
);
4006 if (pindex
->nStatus
& BLOCK_FAILED_MASK
&& (!pindexBestInvalid
|| pindex
->nChainWork
> pindexBestInvalid
->nChainWork
))
4007 pindexBestInvalid
= pindex
;
4009 pindex
->BuildSkip();
4010 if (pindex
->IsValid(BLOCK_VALID_TREE
) && (pindexBestHeader
== NULL
|| CBlockIndexWorkComparator()(pindexBestHeader
, pindex
)))
4011 pindexBestHeader
= pindex
;
4014 // Load block file info
4015 pblocktree
->ReadLastBlockFile(nLastBlockFile
);
4016 vinfoBlockFile
.resize(nLastBlockFile
+ 1);
4017 LogPrintf("%s: last block file = %i\n", __func__
, nLastBlockFile
);
4018 for (int nFile
= 0; nFile
<= nLastBlockFile
; nFile
++) {
4019 pblocktree
->ReadBlockFileInfo(nFile
, vinfoBlockFile
[nFile
]);
4021 LogPrintf("%s: last block file info: %s\n", __func__
, vinfoBlockFile
[nLastBlockFile
].ToString());
4022 for (int nFile
= nLastBlockFile
+ 1; true; nFile
++) {
4023 CBlockFileInfo info
;
4024 if (pblocktree
->ReadBlockFileInfo(nFile
, info
)) {
4025 vinfoBlockFile
.push_back(info
);
4031 // Check presence of blk files
4032 LogPrintf("Checking all blk files are present...\n");
4033 set
<int> setBlkDataFiles
;
4034 BOOST_FOREACH(const PAIRTYPE(uint256
, CBlockIndex
*)& item
, mapBlockIndex
)
4036 CBlockIndex
* pindex
= item
.second
;
4037 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) {
4038 setBlkDataFiles
.insert(pindex
->nFile
);
4041 for (std::set
<int>::iterator it
= setBlkDataFiles
.begin(); it
!= setBlkDataFiles
.end(); it
++)
4043 CDiskBlockPos
pos(*it
, 0);
4044 if (CAutoFile(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
).IsNull()) {
4049 // Check whether we have ever pruned block & undo files
4050 pblocktree
->ReadFlag("prunedblockfiles", fHavePruned
);
4052 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4054 // Check whether we need to continue reindexing
4055 bool fReindexing
= false;
4056 pblocktree
->ReadReindexing(fReindexing
);
4057 fReindex
|= fReindexing
;
4059 // Check whether we have a transaction index
4060 pblocktree
->ReadFlag("txindex", fTxIndex
);
4061 LogPrintf("%s: transaction index %s\n", __func__
, fTxIndex
? "enabled" : "disabled");
4063 // Load pointer to end of best chain
4064 BlockMap::iterator it
= mapBlockIndex
.find(pcoinsTip
->GetBestBlock());
4065 if (it
== mapBlockIndex
.end())
4067 chainActive
.SetTip(it
->second
);
4069 PruneBlockIndexCandidates();
4071 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__
,
4072 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(),
4073 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
4074 Checkpoints::GuessVerificationProgress(chainparams
.Checkpoints(), chainActive
.Tip()));
4079 CVerifyDB::CVerifyDB()
4081 uiInterface
.ShowProgress(_("Verifying blocks..."), 0);
4084 CVerifyDB::~CVerifyDB()
4086 uiInterface
.ShowProgress("", 100);
4089 bool CVerifyDB::VerifyDB(const CChainParams
& chainparams
, CCoinsView
*coinsview
, int nCheckLevel
, int nCheckDepth
)
4092 if (chainActive
.Tip() == NULL
|| chainActive
.Tip()->pprev
== NULL
)
4095 // Verify blocks in the best chain
4096 if (nCheckDepth
<= 0)
4097 nCheckDepth
= 1000000000; // suffices until the year 19000
4098 if (nCheckDepth
> chainActive
.Height())
4099 nCheckDepth
= chainActive
.Height();
4100 nCheckLevel
= std::max(0, std::min(4, nCheckLevel
));
4101 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth
, nCheckLevel
);
4102 CCoinsViewCache
coins(coinsview
);
4103 CBlockIndex
* pindexState
= chainActive
.Tip();
4104 CBlockIndex
* pindexFailure
= NULL
;
4105 int nGoodTransactions
= 0;
4106 CValidationState state
;
4108 LogPrintf("[0%%]...");
4109 for (CBlockIndex
* pindex
= chainActive
.Tip(); pindex
&& pindex
->pprev
; pindex
= pindex
->pprev
)
4111 boost::this_thread::interruption_point();
4112 int percentageDone
= std::max(1, std::min(99, (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* (nCheckLevel
>= 4 ? 50 : 100))));
4113 if (reportDone
< percentageDone
/10) {
4114 // report every 10% step
4115 LogPrintf("[%d%%]...", percentageDone
);
4116 reportDone
= percentageDone
/10;
4118 uiInterface
.ShowProgress(_("Verifying blocks..."), percentageDone
);
4119 if (pindex
->nHeight
< chainActive
.Height()-nCheckDepth
)
4121 if (fPruneMode
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) {
4122 // If pruning, only go back as far as we have data.
4123 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex
->nHeight
);
4127 // check level 0: read from disk
4128 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
4129 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
4130 // check level 1: verify block validity
4131 if (nCheckLevel
>= 1 && !CheckBlock(block
, state
, chainparams
.GetConsensus()))
4132 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__
,
4133 pindex
->nHeight
, pindex
->GetBlockHash().ToString(), FormatStateMessage(state
));
4134 // check level 2: verify undo validity
4135 if (nCheckLevel
>= 2 && pindex
) {
4137 CDiskBlockPos pos
= pindex
->GetUndoPos();
4138 if (!pos
.IsNull()) {
4139 if (!UndoReadFromDisk(undo
, pos
, pindex
->pprev
->GetBlockHash()))
4140 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
4143 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4144 if (nCheckLevel
>= 3 && pindex
== pindexState
&& (coins
.DynamicMemoryUsage() + pcoinsTip
->DynamicMemoryUsage()) <= nCoinCacheUsage
) {
4146 if (!DisconnectBlock(block
, state
, pindex
, coins
, &fClean
))
4147 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
4148 pindexState
= pindex
->pprev
;
4150 nGoodTransactions
= 0;
4151 pindexFailure
= pindex
;
4153 nGoodTransactions
+= block
.vtx
.size();
4155 if (ShutdownRequested())
4159 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive
.Height() - pindexFailure
->nHeight
+ 1, nGoodTransactions
);
4161 // check level 4: try reconnecting blocks
4162 if (nCheckLevel
>= 4) {
4163 CBlockIndex
*pindex
= pindexState
;
4164 while (pindex
!= chainActive
.Tip()) {
4165 boost::this_thread::interruption_point();
4166 uiInterface
.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* 50))));
4167 pindex
= chainActive
.Next(pindex
);
4169 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
4170 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
4171 if (!ConnectBlock(block
, state
, pindex
, coins
, chainparams
))
4172 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
4176 LogPrintf("[DONE].\n");
4177 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive
.Height() - pindexState
->nHeight
, nGoodTransactions
);
4182 bool RewindBlockIndex(const CChainParams
& params
)
4187 while (nHeight
<= chainActive
.Height()) {
4188 if (IsWitnessEnabled(chainActive
[nHeight
- 1], params
.GetConsensus()) && !(chainActive
[nHeight
]->nStatus
& BLOCK_OPT_WITNESS
)) {
4194 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4195 CValidationState state
;
4196 CBlockIndex
* pindex
= chainActive
.Tip();
4197 while (chainActive
.Height() >= nHeight
) {
4198 if (fPruneMode
&& !(chainActive
.Tip()->nStatus
& BLOCK_HAVE_DATA
)) {
4199 // If pruning, don't try rewinding past the HAVE_DATA point;
4200 // since older blocks can't be served anyway, there's
4201 // no need to walk further, and trying to DisconnectTip()
4202 // will fail (and require a needless reindex/redownload
4203 // of the blockchain).
4206 if (!DisconnectTip(state
, params
, true)) {
4207 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex
->nHeight
);
4209 // Occasionally flush state to disk.
4210 if (!FlushStateToDisk(state
, FLUSH_STATE_PERIODIC
))
4214 // Reduce validity flag and have-data flags.
4215 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4216 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4217 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
4218 CBlockIndex
* pindexIter
= it
->second
;
4220 // Note: If we encounter an insufficiently validated block that
4221 // is on chainActive, it must be because we are a pruning node, and
4222 // this block or some successor doesn't HAVE_DATA, so we were unable to
4223 // rewind all the way. Blocks remaining on chainActive at this point
4224 // must not have their validity reduced.
4225 if (IsWitnessEnabled(pindexIter
->pprev
, params
.GetConsensus()) && !(pindexIter
->nStatus
& BLOCK_OPT_WITNESS
) && !chainActive
.Contains(pindexIter
)) {
4227 pindexIter
->nStatus
= std::min
<unsigned int>(pindexIter
->nStatus
& BLOCK_VALID_MASK
, BLOCK_VALID_TREE
) | (pindexIter
->nStatus
& ~BLOCK_VALID_MASK
);
4228 // Remove have-data flags.
4229 pindexIter
->nStatus
&= ~(BLOCK_HAVE_DATA
| BLOCK_HAVE_UNDO
);
4230 // Remove storage location.
4231 pindexIter
->nFile
= 0;
4232 pindexIter
->nDataPos
= 0;
4233 pindexIter
->nUndoPos
= 0;
4234 // Remove various other things
4235 pindexIter
->nTx
= 0;
4236 pindexIter
->nChainTx
= 0;
4237 pindexIter
->nSequenceId
= 0;
4238 // Make sure it gets written.
4239 setDirtyBlockIndex
.insert(pindexIter
);
4241 setBlockIndexCandidates
.erase(pindexIter
);
4242 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> ret
= mapBlocksUnlinked
.equal_range(pindexIter
->pprev
);
4243 while (ret
.first
!= ret
.second
) {
4244 if (ret
.first
->second
== pindexIter
) {
4245 mapBlocksUnlinked
.erase(ret
.first
++);
4250 } else if (pindexIter
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindexIter
->nChainTx
) {
4251 setBlockIndexCandidates
.insert(pindexIter
);
4255 PruneBlockIndexCandidates();
4257 CheckBlockIndex(params
.GetConsensus());
4259 if (!FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
)) {
4266 void UnloadBlockIndex()
4269 setBlockIndexCandidates
.clear();
4270 chainActive
.SetTip(NULL
);
4271 pindexBestInvalid
= NULL
;
4272 pindexBestHeader
= NULL
;
4274 mapOrphanTransactions
.clear();
4275 mapOrphanTransactionsByPrev
.clear();
4277 mapBlocksUnlinked
.clear();
4278 vinfoBlockFile
.clear();
4280 nBlockSequenceId
= 1;
4281 mapBlockSource
.clear();
4282 mapBlocksInFlight
.clear();
4283 nPreferredDownload
= 0;
4284 setDirtyBlockIndex
.clear();
4285 setDirtyFileInfo
.clear();
4286 mapNodeState
.clear();
4287 recentRejects
.reset(NULL
);
4288 versionbitscache
.Clear();
4289 for (int b
= 0; b
< VERSIONBITS_NUM_BITS
; b
++) {
4290 warningcache
[b
].clear();
4293 BOOST_FOREACH(BlockMap::value_type
& entry
, mapBlockIndex
) {
4294 delete entry
.second
;
4296 mapBlockIndex
.clear();
4297 fHavePruned
= false;
4300 bool LoadBlockIndex()
4302 // Load block index from databases
4303 if (!fReindex
&& !LoadBlockIndexDB())
4308 bool InitBlockIndex(const CChainParams
& chainparams
)
4312 // Initialize global variables that cannot be constructed at startup.
4313 recentRejects
.reset(new CRollingBloomFilter(120000, 0.000001));
4315 // Check whether we're already initialized
4316 if (chainActive
.Genesis() != NULL
)
4319 // Use the provided setting for -txindex in the new database
4320 fTxIndex
= GetBoolArg("-txindex", DEFAULT_TXINDEX
);
4321 pblocktree
->WriteFlag("txindex", fTxIndex
);
4322 LogPrintf("Initializing databases...\n");
4324 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4327 CBlock
&block
= const_cast<CBlock
&>(chainparams
.GenesisBlock());
4328 // Start new block file
4329 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
4330 CDiskBlockPos blockPos
;
4331 CValidationState state
;
4332 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, 0, block
.GetBlockTime()))
4333 return error("LoadBlockIndex(): FindBlockPos failed");
4334 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
4335 return error("LoadBlockIndex(): writing genesis block to disk failed");
4336 CBlockIndex
*pindex
= AddToBlockIndex(block
);
4337 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
))
4338 return error("LoadBlockIndex(): genesis block not accepted");
4339 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4340 return FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
);
4341 } catch (const std::runtime_error
& e
) {
4342 return error("LoadBlockIndex(): failed to initialize block database: %s", e
.what());
4349 bool LoadExternalBlockFile(const CChainParams
& chainparams
, FILE* fileIn
, CDiskBlockPos
*dbp
)
4351 // Map of disk positions for blocks with unknown parent (only used for reindex)
4352 static std::multimap
<uint256
, CDiskBlockPos
> mapBlocksUnknownParent
;
4353 int64_t nStart
= GetTimeMillis();
4357 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4358 CBufferedFile
blkdat(fileIn
, 2*MAX_BLOCK_SERIALIZED_SIZE
, MAX_BLOCK_SERIALIZED_SIZE
+8, SER_DISK
, CLIENT_VERSION
);
4359 uint64_t nRewind
= blkdat
.GetPos();
4360 while (!blkdat
.eof()) {
4361 boost::this_thread::interruption_point();
4363 blkdat
.SetPos(nRewind
);
4364 nRewind
++; // start one byte further next time, in case of failure
4365 blkdat
.SetLimit(); // remove former limit
4366 unsigned int nSize
= 0;
4369 unsigned char buf
[CMessageHeader::MESSAGE_START_SIZE
];
4370 blkdat
.FindByte(chainparams
.MessageStart()[0]);
4371 nRewind
= blkdat
.GetPos()+1;
4372 blkdat
>> FLATDATA(buf
);
4373 if (memcmp(buf
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
))
4377 if (nSize
< 80 || nSize
> MAX_BLOCK_SERIALIZED_SIZE
)
4379 } catch (const std::exception
&) {
4380 // no valid block header found; don't complain
4385 uint64_t nBlockPos
= blkdat
.GetPos();
4387 dbp
->nPos
= nBlockPos
;
4388 blkdat
.SetLimit(nBlockPos
+ nSize
);
4389 blkdat
.SetPos(nBlockPos
);
4392 nRewind
= blkdat
.GetPos();
4394 // detect out of order blocks, and store them for later
4395 uint256 hash
= block
.GetHash();
4396 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
.find(block
.hashPrevBlock
) == mapBlockIndex
.end()) {
4397 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__
, hash
.ToString(),
4398 block
.hashPrevBlock
.ToString());
4400 mapBlocksUnknownParent
.insert(std::make_pair(block
.hashPrevBlock
, *dbp
));
4404 // process in case the block isn't known yet
4405 if (mapBlockIndex
.count(hash
) == 0 || (mapBlockIndex
[hash
]->nStatus
& BLOCK_HAVE_DATA
) == 0) {
4407 CValidationState state
;
4408 if (AcceptBlock(block
, state
, chainparams
, NULL
, true, dbp
, NULL
))
4410 if (state
.IsError())
4412 } else if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
[hash
]->nHeight
% 1000 == 0) {
4413 LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash
.ToString(), mapBlockIndex
[hash
]->nHeight
);
4416 // Activate the genesis block so normal node progress can continue
4417 if (hash
== chainparams
.GetConsensus().hashGenesisBlock
) {
4418 CValidationState state
;
4419 if (!ActivateBestChain(state
, chainparams
)) {
4426 // Recursively process earlier encountered successors of this block
4427 deque
<uint256
> queue
;
4428 queue
.push_back(hash
);
4429 while (!queue
.empty()) {
4430 uint256 head
= queue
.front();
4432 std::pair
<std::multimap
<uint256
, CDiskBlockPos
>::iterator
, std::multimap
<uint256
, CDiskBlockPos
>::iterator
> range
= mapBlocksUnknownParent
.equal_range(head
);
4433 while (range
.first
!= range
.second
) {
4434 std::multimap
<uint256
, CDiskBlockPos
>::iterator it
= range
.first
;
4435 if (ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus()))
4437 LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__
, block
.GetHash().ToString(),
4440 CValidationState dummy
;
4441 if (AcceptBlock(block
, dummy
, chainparams
, NULL
, true, &it
->second
, NULL
))
4444 queue
.push_back(block
.GetHash());
4448 mapBlocksUnknownParent
.erase(it
);
4452 } catch (const std::exception
& e
) {
4453 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__
, e
.what());
4456 } catch (const std::runtime_error
& e
) {
4457 AbortNode(std::string("System error: ") + e
.what());
4460 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded
, GetTimeMillis() - nStart
);
4464 void static CheckBlockIndex(const Consensus::Params
& consensusParams
)
4466 if (!fCheckBlockIndex
) {
4472 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4473 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4474 // iterating the block tree require that chainActive has been initialized.)
4475 if (chainActive
.Height() < 0) {
4476 assert(mapBlockIndex
.size() <= 1);
4480 // Build forward-pointing map of the entire block tree.
4481 std::multimap
<CBlockIndex
*,CBlockIndex
*> forward
;
4482 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
4483 forward
.insert(std::make_pair(it
->second
->pprev
, it
->second
));
4486 assert(forward
.size() == mapBlockIndex
.size());
4488 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeGenesis
= forward
.equal_range(NULL
);
4489 CBlockIndex
*pindex
= rangeGenesis
.first
->second
;
4490 rangeGenesis
.first
++;
4491 assert(rangeGenesis
.first
== rangeGenesis
.second
); // There is only one index entry with parent NULL.
4493 // Iterate over the entire block tree, using depth-first search.
4494 // Along the way, remember whether there are blocks on the path from genesis
4495 // block being explored which are the first to have certain properties.
4498 CBlockIndex
* pindexFirstInvalid
= NULL
; // Oldest ancestor of pindex which is invalid.
4499 CBlockIndex
* pindexFirstMissing
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4500 CBlockIndex
* pindexFirstNeverProcessed
= NULL
; // Oldest ancestor of pindex for which nTx == 0.
4501 CBlockIndex
* pindexFirstNotTreeValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4502 CBlockIndex
* pindexFirstNotTransactionsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4503 CBlockIndex
* pindexFirstNotChainValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4504 CBlockIndex
* pindexFirstNotScriptsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4505 while (pindex
!= NULL
) {
4507 if (pindexFirstInvalid
== NULL
&& pindex
->nStatus
& BLOCK_FAILED_VALID
) pindexFirstInvalid
= pindex
;
4508 if (pindexFirstMissing
== NULL
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) pindexFirstMissing
= pindex
;
4509 if (pindexFirstNeverProcessed
== NULL
&& pindex
->nTx
== 0) pindexFirstNeverProcessed
= pindex
;
4510 if (pindex
->pprev
!= NULL
&& pindexFirstNotTreeValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TREE
) pindexFirstNotTreeValid
= pindex
;
4511 if (pindex
->pprev
!= NULL
&& pindexFirstNotTransactionsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TRANSACTIONS
) pindexFirstNotTransactionsValid
= pindex
;
4512 if (pindex
->pprev
!= NULL
&& pindexFirstNotChainValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_CHAIN
) pindexFirstNotChainValid
= pindex
;
4513 if (pindex
->pprev
!= NULL
&& pindexFirstNotScriptsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_SCRIPTS
) pindexFirstNotScriptsValid
= pindex
;
4515 // Begin: actual consistency checks.
4516 if (pindex
->pprev
== NULL
) {
4517 // Genesis block checks.
4518 assert(pindex
->GetBlockHash() == consensusParams
.hashGenesisBlock
); // Genesis block's hash must match.
4519 assert(pindex
== chainActive
.Genesis()); // The current active chain's genesis block must be this block.
4521 if (pindex
->nChainTx
== 0) assert(pindex
->nSequenceId
<= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4522 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4523 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4525 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4526 assert(!(pindex
->nStatus
& BLOCK_HAVE_DATA
) == (pindex
->nTx
== 0));
4527 assert(pindexFirstMissing
== pindexFirstNeverProcessed
);
4529 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4530 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) assert(pindex
->nTx
> 0);
4532 if (pindex
->nStatus
& BLOCK_HAVE_UNDO
) assert(pindex
->nStatus
& BLOCK_HAVE_DATA
);
4533 assert(((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TRANSACTIONS
) == (pindex
->nTx
> 0)); // This is pruning-independent.
4534 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4535 assert((pindexFirstNeverProcessed
!= NULL
) == (pindex
->nChainTx
== 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4536 assert((pindexFirstNotTransactionsValid
!= NULL
) == (pindex
->nChainTx
== 0));
4537 assert(pindex
->nHeight
== nHeight
); // nHeight must be consistent.
4538 assert(pindex
->pprev
== NULL
|| pindex
->nChainWork
>= pindex
->pprev
->nChainWork
); // For every block except the genesis block, the chainwork must be larger than the parent's.
4539 assert(nHeight
< 2 || (pindex
->pskip
&& (pindex
->pskip
->nHeight
< nHeight
))); // The pskip pointer must point back for all but the first 2 blocks.
4540 assert(pindexFirstNotTreeValid
== NULL
); // All mapBlockIndex entries must at least be TREE valid
4541 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TREE
) assert(pindexFirstNotTreeValid
== NULL
); // TREE valid implies all parents are TREE valid
4542 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_CHAIN
) assert(pindexFirstNotChainValid
== NULL
); // CHAIN valid implies all parents are CHAIN valid
4543 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_SCRIPTS
) assert(pindexFirstNotScriptsValid
== NULL
); // SCRIPTS valid implies all parents are SCRIPTS valid
4544 if (pindexFirstInvalid
== NULL
) {
4545 // Checks for not-invalid blocks.
4546 assert((pindex
->nStatus
& BLOCK_FAILED_MASK
) == 0); // The failed mask cannot be set for blocks without invalid parents.
4548 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && pindexFirstNeverProcessed
== NULL
) {
4549 if (pindexFirstInvalid
== NULL
) {
4550 // If this block sorts at least as good as the current tip and
4551 // is valid and we have all data for its parents, it must be in
4552 // setBlockIndexCandidates. chainActive.Tip() must also be there
4553 // even if some data has been pruned.
4554 if (pindexFirstMissing
== NULL
|| pindex
== chainActive
.Tip()) {
4555 assert(setBlockIndexCandidates
.count(pindex
));
4557 // If some parent is missing, then it could be that this block was in
4558 // setBlockIndexCandidates but had to be removed because of the missing data.
4559 // In this case it must be in mapBlocksUnlinked -- see test below.
4561 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4562 assert(setBlockIndexCandidates
.count(pindex
) == 0);
4564 // Check whether this block is in mapBlocksUnlinked.
4565 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeUnlinked
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
4566 bool foundInUnlinked
= false;
4567 while (rangeUnlinked
.first
!= rangeUnlinked
.second
) {
4568 assert(rangeUnlinked
.first
->first
== pindex
->pprev
);
4569 if (rangeUnlinked
.first
->second
== pindex
) {
4570 foundInUnlinked
= true;
4573 rangeUnlinked
.first
++;
4575 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
!= NULL
&& pindexFirstInvalid
== NULL
) {
4576 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4577 assert(foundInUnlinked
);
4579 if (!(pindex
->nStatus
& BLOCK_HAVE_DATA
)) assert(!foundInUnlinked
); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4580 if (pindexFirstMissing
== NULL
) assert(!foundInUnlinked
); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4581 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
== NULL
&& pindexFirstMissing
!= NULL
) {
4582 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4583 assert(fHavePruned
); // We must have pruned.
4584 // This block may have entered mapBlocksUnlinked if:
4585 // - it has a descendant that at some point had more work than the
4587 // - we tried switching to that descendant but were missing
4588 // data for some intermediate block between chainActive and the
4590 // So if this block is itself better than chainActive.Tip() and it wasn't in
4591 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4592 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && setBlockIndexCandidates
.count(pindex
) == 0) {
4593 if (pindexFirstInvalid
== NULL
) {
4594 assert(foundInUnlinked
);
4598 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4599 // End: actual consistency checks.
4601 // Try descending into the first subnode.
4602 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> range
= forward
.equal_range(pindex
);
4603 if (range
.first
!= range
.second
) {
4604 // A subnode was found.
4605 pindex
= range
.first
->second
;
4609 // This is a leaf node.
4610 // Move upwards until we reach a node of which we have not yet visited the last child.
4612 // We are going to either move to a parent or a sibling of pindex.
4613 // If pindex was the first with a certain property, unset the corresponding variable.
4614 if (pindex
== pindexFirstInvalid
) pindexFirstInvalid
= NULL
;
4615 if (pindex
== pindexFirstMissing
) pindexFirstMissing
= NULL
;
4616 if (pindex
== pindexFirstNeverProcessed
) pindexFirstNeverProcessed
= NULL
;
4617 if (pindex
== pindexFirstNotTreeValid
) pindexFirstNotTreeValid
= NULL
;
4618 if (pindex
== pindexFirstNotTransactionsValid
) pindexFirstNotTransactionsValid
= NULL
;
4619 if (pindex
== pindexFirstNotChainValid
) pindexFirstNotChainValid
= NULL
;
4620 if (pindex
== pindexFirstNotScriptsValid
) pindexFirstNotScriptsValid
= NULL
;
4622 CBlockIndex
* pindexPar
= pindex
->pprev
;
4623 // Find which child we just visited.
4624 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangePar
= forward
.equal_range(pindexPar
);
4625 while (rangePar
.first
->second
!= pindex
) {
4626 assert(rangePar
.first
!= rangePar
.second
); // Our parent must have at least the node we're coming from as child.
4629 // Proceed to the next one.
4631 if (rangePar
.first
!= rangePar
.second
) {
4632 // Move to the sibling.
4633 pindex
= rangePar
.first
->second
;
4644 // Check that we actually traversed the entire map.
4645 assert(nNodes
== forward
.size());
4648 std::string
GetWarnings(const std::string
& strFor
)
4650 string strStatusBar
;
4653 const string uiAlertSeperator
= "<hr />";
4655 if (!CLIENT_VERSION_IS_RELEASE
) {
4656 strStatusBar
= "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
4657 strGUI
= _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4660 if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE
))
4661 strStatusBar
= strRPC
= strGUI
= "testsafemode enabled";
4663 // Misc warnings like out of disk space and clock is wrong
4664 if (strMiscWarning
!= "")
4666 strStatusBar
= strMiscWarning
;
4667 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + strMiscWarning
;
4670 if (fLargeWorkForkFound
)
4672 strStatusBar
= strRPC
= "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
4673 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4675 else if (fLargeWorkInvalidChainFound
)
4677 strStatusBar
= strRPC
= "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
4678 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
4681 if (strFor
== "gui")
4683 else if (strFor
== "statusbar")
4684 return strStatusBar
;
4685 else if (strFor
== "rpc")
4687 assert(!"GetWarnings(): invalid parameter");
4698 //////////////////////////////////////////////////////////////////////////////
4700 // blockchain -> download logic notification
4703 void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex
*pindexNew
, const CBlockIndex
*pindexFork
, bool fInitialDownload
) {
4704 const int nNewHeight
= pindexNew
->nHeight
;
4705 connman
->SetBestHeight(nNewHeight
);
4707 if (!fInitialDownload
) {
4708 // Find the hashes of all blocks that weren't previously in the best chain.
4709 std::vector
<uint256
> vHashes
;
4710 const CBlockIndex
*pindexToAnnounce
= pindexNew
;
4711 while (pindexToAnnounce
!= pindexFork
) {
4712 vHashes
.push_back(pindexToAnnounce
->GetBlockHash());
4713 pindexToAnnounce
= pindexToAnnounce
->pprev
;
4714 if (vHashes
.size() == MAX_BLOCKS_TO_ANNOUNCE
) {
4715 // Limit announcements in case of a huge reorganization.
4716 // Rely on the peer's synchronization mechanism in that case.
4720 // Relay inventory, but don't relay old inventory during initial block download.
4721 connman
->ForEachNode([nNewHeight
, &vHashes
](CNode
* pnode
) {
4722 if (nNewHeight
> (pnode
->nStartingHeight
!= -1 ? pnode
->nStartingHeight
- 2000 : 0)) {
4723 BOOST_REVERSE_FOREACH(const uint256
& hash
, vHashes
) {
4724 pnode
->PushBlockHash(hash
);
4731 void PeerLogicValidation::BlockChecked(const CBlock
& block
, const CValidationState
& state
) {
4734 const uint256
hash(block
.GetHash());
4735 std::map
<uint256
, NodeId
>::iterator it
= mapBlockSource
.find(hash
);
4738 if (state
.IsInvalid(nDoS
)) {
4739 if (it
!= mapBlockSource
.end() && State(it
->second
)) {
4740 assert (state
.GetRejectCode() < REJECT_INTERNAL
); // Blocks are never rejected with internal reject codes
4741 CBlockReject reject
= {(unsigned char)state
.GetRejectCode(), state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), hash
};
4742 State(it
->second
)->rejects
.push_back(reject
);
4744 Misbehaving(it
->second
, nDoS
);
4747 if (it
!= mapBlockSource
.end())
4748 mapBlockSource
.erase(it
);
4751 //////////////////////////////////////////////////////////////////////////////
4757 bool static AlreadyHave(const CInv
& inv
) EXCLUSIVE_LOCKS_REQUIRED(cs_main
)
4762 case MSG_WITNESS_TX
:
4764 assert(recentRejects
);
4765 if (chainActive
.Tip()->GetBlockHash() != hashRecentRejectsChainTip
)
4767 // If the chain tip has changed previously rejected transactions
4768 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4769 // or a double-spend. Reset the rejects filter and give those
4770 // txs a second chance.
4771 hashRecentRejectsChainTip
= chainActive
.Tip()->GetBlockHash();
4772 recentRejects
->reset();
4775 // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
4776 // requesting or processing some txs which have already been included in a block
4777 return recentRejects
->contains(inv
.hash
) ||
4778 mempool
.exists(inv
.hash
) ||
4779 mapOrphanTransactions
.count(inv
.hash
) ||
4780 pcoinsTip
->HaveCoinsInCache(inv
.hash
);
4783 case MSG_WITNESS_BLOCK
:
4784 return mapBlockIndex
.count(inv
.hash
);
4786 // Don't know what it is, just say we already got one
4790 static void RelayTransaction(const CTransaction
& tx
, CConnman
& connman
)
4792 CInv
inv(MSG_TX
, tx
.GetHash());
4793 connman
.ForEachNode([&inv
](CNode
* pnode
)
4795 pnode
->PushInventory(inv
);
4799 static void RelayAddress(const CAddress
& addr
, bool fReachable
, CConnman
& connman
)
4801 int nRelayNodes
= fReachable
? 2 : 1; // limited relaying of addresses outside our network(s)
4803 // Relay to a limited number of other nodes
4804 // Use deterministic randomness to send to the same nodes for 24 hours
4805 // at a time so the addrKnowns of the chosen nodes prevent repeats
4806 uint64_t hashAddr
= addr
.GetHash();
4807 std::multimap
<uint64_t, CNode
*> mapMix
;
4808 const CSipHasher hasher
= connman
.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY
).Write(hashAddr
<< 32).Write((GetTime() + hashAddr
) / (24*60*60));
4809 FastRandomContext insecure_rand
;
4811 auto sortfunc
= [&mapMix
, &hasher
](CNode
* pnode
) {
4812 if (pnode
->nVersion
>= CADDR_TIME_VERSION
) {
4813 uint64_t hashKey
= CSipHasher(hasher
).Write(pnode
->id
).Finalize();
4814 mapMix
.emplace(hashKey
, pnode
);
4818 auto pushfunc
= [&addr
, &mapMix
, &nRelayNodes
, &insecure_rand
] {
4819 for (auto mi
= mapMix
.begin(); mi
!= mapMix
.end() && nRelayNodes
-- > 0; ++mi
)
4820 mi
->second
->PushAddress(addr
, insecure_rand
);
4823 connman
.ForEachNodeThen(std::move(sortfunc
), std::move(pushfunc
));
4826 void static ProcessGetData(CNode
* pfrom
, const Consensus::Params
& consensusParams
, CConnman
& connman
)
4828 std::deque
<CInv
>::iterator it
= pfrom
->vRecvGetData
.begin();
4829 unsigned int nMaxSendBufferSize
= connman
.GetSendBufferSize();
4831 vector
<CInv
> vNotFound
;
4835 while (it
!= pfrom
->vRecvGetData
.end()) {
4836 // Don't bother if send buffer is too full to respond anyway
4837 if (pfrom
->nSendSize
>= nMaxSendBufferSize
)
4840 const CInv
&inv
= *it
;
4842 boost::this_thread::interruption_point();
4845 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
4848 BlockMap::iterator mi
= mapBlockIndex
.find(inv
.hash
);
4849 if (mi
!= mapBlockIndex
.end())
4851 if (chainActive
.Contains(mi
->second
)) {
4854 static const int nOneMonth
= 30 * 24 * 60 * 60;
4855 // To prevent fingerprinting attacks, only send blocks outside of the active
4856 // chain if they are valid, and no more than a month older (both in time, and in
4857 // best equivalent proof of work) than the best header chain we know about.
4858 send
= mi
->second
->IsValid(BLOCK_VALID_SCRIPTS
) && (pindexBestHeader
!= NULL
) &&
4859 (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() < nOneMonth
) &&
4860 (GetBlockProofEquivalentTime(*pindexBestHeader
, *mi
->second
, *pindexBestHeader
, consensusParams
) < nOneMonth
);
4862 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__
, pfrom
->GetId());
4866 // disconnect node in case we have reached the outbound limit for serving historical blocks
4867 // never disconnect whitelisted nodes
4868 static const int nOneWeek
= 7 * 24 * 60 * 60; // assume > 1 week = historical
4869 if (send
&& connman
.OutboundTargetReached(true) && ( ((pindexBestHeader
!= NULL
) && (pindexBestHeader
->GetBlockTime() - mi
->second
->GetBlockTime() > nOneWeek
)) || inv
.type
== MSG_FILTERED_BLOCK
) && !pfrom
->fWhitelisted
)
4871 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom
->GetId());
4874 pfrom
->fDisconnect
= true;
4877 // Pruned nodes may have deleted the block, so check whether
4878 // it's available before trying to send.
4879 if (send
&& (mi
->second
->nStatus
& BLOCK_HAVE_DATA
))
4881 // Send block from disk
4883 if (!ReadBlockFromDisk(block
, (*mi
).second
, consensusParams
))
4884 assert(!"cannot load block from disk");
4885 if (inv
.type
== MSG_BLOCK
)
4886 pfrom
->PushMessageWithFlag(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, block
);
4887 else if (inv
.type
== MSG_WITNESS_BLOCK
)
4888 pfrom
->PushMessage(NetMsgType::BLOCK
, block
);
4889 else if (inv
.type
== MSG_FILTERED_BLOCK
)
4891 bool sendMerkleBlock
= false;
4892 CMerkleBlock merkleBlock
;
4894 LOCK(pfrom
->cs_filter
);
4895 if (pfrom
->pfilter
) {
4896 sendMerkleBlock
= true;
4897 merkleBlock
= CMerkleBlock(block
, *pfrom
->pfilter
);
4900 if (sendMerkleBlock
) {
4901 pfrom
->PushMessage(NetMsgType::MERKLEBLOCK
, merkleBlock
);
4902 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4903 // This avoids hurting performance by pointlessly requiring a round-trip
4904 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4905 // they must either disconnect and retry or request the full block.
4906 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4907 // however we MUST always provide at least what the remote peer needs
4908 typedef std::pair
<unsigned int, uint256
> PairType
;
4909 BOOST_FOREACH(PairType
& pair
, merkleBlock
.vMatchedTxn
)
4910 pfrom
->PushMessageWithFlag(SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::TX
, block
.vtx
[pair
.first
]);
4915 else if (inv
.type
== MSG_CMPCT_BLOCK
)
4917 // If a peer is asking for old blocks, we're almost guaranteed
4918 // they wont have a useful mempool to match against a compact block,
4919 // and we don't feel like constructing the object for them, so
4920 // instead we respond with the full, non-compact block.
4921 bool fPeerWantsWitness
= State(pfrom
->GetId())->fWantsCmpctWitness
;
4922 if (CanDirectFetch(consensusParams
) && mi
->second
->nHeight
>= chainActive
.Height() - MAX_CMPCTBLOCK_DEPTH
) {
4923 CBlockHeaderAndShortTxIDs
cmpctblock(block
, fPeerWantsWitness
);
4924 pfrom
->PushMessageWithFlag(fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::CMPCTBLOCK
, cmpctblock
);
4926 pfrom
->PushMessageWithFlag(fPeerWantsWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCK
, block
);
4929 // Trigger the peer node to send a getblocks request for the next batch of inventory
4930 if (inv
.hash
== pfrom
->hashContinue
)
4932 // Bypass PushInventory, this must send even if redundant,
4933 // and we want it right after the last block so they don't
4934 // wait for other stuff first.
4936 vInv
.push_back(CInv(MSG_BLOCK
, chainActive
.Tip()->GetBlockHash()));
4937 pfrom
->PushMessage(NetMsgType::INV
, vInv
);
4938 pfrom
->hashContinue
.SetNull();
4942 else if (inv
.type
== MSG_TX
|| inv
.type
== MSG_WITNESS_TX
)
4944 // Send stream from relay memory
4946 auto mi
= mapRelay
.find(inv
.hash
);
4947 if (mi
!= mapRelay
.end()) {
4948 pfrom
->PushMessageWithFlag(inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0, NetMsgType::TX
, *mi
->second
);
4950 } else if (pfrom
->timeLastMempoolReq
) {
4951 auto txinfo
= mempool
.info(inv
.hash
);
4952 // To protect privacy, do not answer getdata using the mempool when
4953 // that TX couldn't have been INVed in reply to a MEMPOOL request.
4954 if (txinfo
.tx
&& txinfo
.nTime
<= pfrom
->timeLastMempoolReq
) {
4955 pfrom
->PushMessageWithFlag(inv
.type
== MSG_TX
? SERIALIZE_TRANSACTION_NO_WITNESS
: 0, NetMsgType::TX
, *txinfo
.tx
);
4960 vNotFound
.push_back(inv
);
4964 // Track requests for our stuff.
4965 GetMainSignals().Inventory(inv
.hash
);
4967 if (inv
.type
== MSG_BLOCK
|| inv
.type
== MSG_FILTERED_BLOCK
|| inv
.type
== MSG_CMPCT_BLOCK
|| inv
.type
== MSG_WITNESS_BLOCK
)
4972 pfrom
->vRecvGetData
.erase(pfrom
->vRecvGetData
.begin(), it
);
4974 if (!vNotFound
.empty()) {
4975 // Let the peer know that we didn't find what it asked for, so it doesn't
4976 // have to wait around forever. Currently only SPV clients actually care
4977 // about this message: it's needed when they are recursively walking the
4978 // dependencies of relevant unconfirmed transactions. SPV clients want to
4979 // do that because they want to know about (and store and rebroadcast and
4980 // risk analyze) the dependencies of transactions relevant to them, without
4981 // having to download the entire memory pool.
4982 pfrom
->PushMessage(NetMsgType::NOTFOUND
, vNotFound
);
4986 uint32_t GetFetchFlags(CNode
* pfrom
, CBlockIndex
* pprev
, const Consensus::Params
& chainparams
) {
4987 uint32_t nFetchFlags
= 0;
4988 if ((pfrom
->GetLocalServices() & NODE_WITNESS
) && State(pfrom
->GetId())->fHaveWitness
) {
4989 nFetchFlags
|= MSG_WITNESS_FLAG
;
4994 bool static ProcessMessage(CNode
* pfrom
, string strCommand
, CDataStream
& vRecv
, int64_t nTimeReceived
, const CChainParams
& chainparams
, CConnman
& connman
)
4996 unsigned int nMaxSendBufferSize
= connman
.GetSendBufferSize();
4998 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand
), vRecv
.size(), pfrom
->id
);
4999 if (mapArgs
.count("-dropmessagestest") && GetRand(atoi(mapArgs
["-dropmessagestest"])) == 0)
5001 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
5006 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) &&
5007 (strCommand
== NetMsgType::FILTERLOAD
||
5008 strCommand
== NetMsgType::FILTERADD
||
5009 strCommand
== NetMsgType::FILTERCLEAR
))
5011 if (pfrom
->nVersion
>= NO_BLOOM_VERSION
) {
5013 Misbehaving(pfrom
->GetId(), 100);
5016 pfrom
->fDisconnect
= true;
5022 if (strCommand
== NetMsgType::VERSION
)
5024 // Feeler connections exist only to verify if address is online.
5025 if (pfrom
->fFeeler
) {
5026 assert(pfrom
->fInbound
== false);
5027 pfrom
->fDisconnect
= true;
5030 // Each connection can only send one version message
5031 if (pfrom
->nVersion
!= 0)
5033 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, REJECT_DUPLICATE
, string("Duplicate version message"));
5035 Misbehaving(pfrom
->GetId(), 1);
5042 uint64_t nNonce
= 1;
5043 uint64_t nServiceInt
;
5044 vRecv
>> pfrom
->nVersion
>> nServiceInt
>> nTime
>> addrMe
;
5045 pfrom
->nServices
= ServiceFlags(nServiceInt
);
5046 if (!pfrom
->fInbound
)
5048 connman
.SetServices(pfrom
->addr
, pfrom
->nServices
);
5050 if (pfrom
->nServicesExpected
& ~pfrom
->nServices
)
5052 LogPrint("net", "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom
->id
, pfrom
->nServices
, pfrom
->nServicesExpected
);
5053 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, REJECT_NONSTANDARD
,
5054 strprintf("Expected to offer services %08x", pfrom
->nServicesExpected
));
5055 pfrom
->fDisconnect
= true;
5059 if (pfrom
->nVersion
< MIN_PEER_PROTO_VERSION
)
5061 // disconnect from peers older than this proto version
5062 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom
->id
, pfrom
->nVersion
);
5063 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, REJECT_OBSOLETE
,
5064 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION
));
5065 pfrom
->fDisconnect
= true;
5069 if (pfrom
->nVersion
== 10300)
5070 pfrom
->nVersion
= 300;
5072 vRecv
>> addrFrom
>> nNonce
;
5073 if (!vRecv
.empty()) {
5074 vRecv
>> LIMITED_STRING(pfrom
->strSubVer
, MAX_SUBVERSION_LENGTH
);
5075 pfrom
->cleanSubVer
= SanitizeString(pfrom
->strSubVer
);
5077 if (!vRecv
.empty()) {
5078 vRecv
>> pfrom
->nStartingHeight
;
5081 LOCK(pfrom
->cs_filter
);
5083 vRecv
>> pfrom
->fRelayTxes
; // set to true after we get the first filter* message
5085 pfrom
->fRelayTxes
= true;
5088 // Disconnect if we connected to ourself
5089 if (pfrom
->fInbound
&& !connman
.CheckIncomingNonce(nNonce
))
5091 LogPrintf("connected to self at %s, disconnecting\n", pfrom
->addr
.ToString());
5092 pfrom
->fDisconnect
= true;
5096 pfrom
->addrLocal
= addrMe
;
5097 if (pfrom
->fInbound
&& addrMe
.IsRoutable())
5102 // Be shy and don't send version until we hear
5103 if (pfrom
->fInbound
)
5104 pfrom
->PushVersion();
5106 pfrom
->fClient
= !(pfrom
->nServices
& NODE_NETWORK
);
5108 if((pfrom
->nServices
& NODE_WITNESS
))
5111 State(pfrom
->GetId())->fHaveWitness
= true;
5114 // Potentially mark this peer as a preferred download peer.
5117 UpdatePreferredDownload(pfrom
, State(pfrom
->GetId()));
5121 pfrom
->PushMessage(NetMsgType::VERACK
);
5122 pfrom
->ssSend
.SetVersion(min(pfrom
->nVersion
, PROTOCOL_VERSION
));
5124 if (!pfrom
->fInbound
)
5126 // Advertise our address
5127 if (fListen
&& !IsInitialBlockDownload())
5129 CAddress addr
= GetLocalAddress(&pfrom
->addr
, pfrom
->GetLocalServices());
5130 FastRandomContext insecure_rand
;
5131 if (addr
.IsRoutable())
5133 LogPrint("net", "ProcessMessages: advertising address %s\n", addr
.ToString());
5134 pfrom
->PushAddress(addr
, insecure_rand
);
5135 } else if (IsPeerAddrLocalGood(pfrom
)) {
5136 addr
.SetIP(pfrom
->addrLocal
);
5137 LogPrint("net", "ProcessMessages: advertising address %s\n", addr
.ToString());
5138 pfrom
->PushAddress(addr
, insecure_rand
);
5142 // Get recent addresses
5143 if (pfrom
->fOneShot
|| pfrom
->nVersion
>= CADDR_TIME_VERSION
|| connman
.GetAddressCount() < 1000)
5145 pfrom
->PushMessage(NetMsgType::GETADDR
);
5146 pfrom
->fGetAddr
= true;
5148 connman
.MarkAddressGood(pfrom
->addr
);
5151 pfrom
->fSuccessfullyConnected
= true;
5155 remoteAddr
= ", peeraddr=" + pfrom
->addr
.ToString();
5157 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
5158 pfrom
->cleanSubVer
, pfrom
->nVersion
,
5159 pfrom
->nStartingHeight
, addrMe
.ToString(), pfrom
->id
,
5162 int64_t nTimeOffset
= nTime
- GetTime();
5163 pfrom
->nTimeOffset
= nTimeOffset
;
5164 AddTimeData(pfrom
->addr
, nTimeOffset
);
5168 else if (pfrom
->nVersion
== 0)
5170 // Must have a version message before anything else
5172 Misbehaving(pfrom
->GetId(), 1);
5177 else if (strCommand
== NetMsgType::VERACK
)
5179 pfrom
->SetRecvVersion(min(pfrom
->nVersion
, PROTOCOL_VERSION
));
5181 // Mark this node as currently connected, so we update its timestamp later.
5182 if (pfrom
->fNetworkNode
) {
5184 State(pfrom
->GetId())->fCurrentlyConnected
= true;
5187 if (pfrom
->nVersion
>= SENDHEADERS_VERSION
) {
5188 // Tell our peer we prefer to receive headers rather than inv's
5189 // We send this to non-NODE NETWORK peers as well, because even
5190 // non-NODE NETWORK peers can announce blocks (such as pruning
5192 pfrom
->PushMessage(NetMsgType::SENDHEADERS
);
5194 if (pfrom
->nVersion
>= SHORT_IDS_BLOCKS_VERSION
) {
5195 // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
5196 // However, we do not request new block announcements using
5197 // cmpctblock messages.
5198 // We send this to non-NODE NETWORK peers as well, because
5199 // they may wish to request compact blocks from us
5200 bool fAnnounceUsingCMPCTBLOCK
= false;
5201 uint64_t nCMPCTBLOCKVersion
= 2;
5202 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
5203 pfrom
->PushMessage(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
);
5204 nCMPCTBLOCKVersion
= 1;
5205 pfrom
->PushMessage(NetMsgType::SENDCMPCT
, fAnnounceUsingCMPCTBLOCK
, nCMPCTBLOCKVersion
);
5210 else if (strCommand
== NetMsgType::ADDR
)
5212 vector
<CAddress
> vAddr
;
5215 // Don't want addr from older versions unless seeding
5216 if (pfrom
->nVersion
< CADDR_TIME_VERSION
&& connman
.GetAddressCount() > 1000)
5218 if (vAddr
.size() > 1000)
5221 Misbehaving(pfrom
->GetId(), 20);
5222 return error("message addr size() = %u", vAddr
.size());
5225 // Store the new addresses
5226 vector
<CAddress
> vAddrOk
;
5227 int64_t nNow
= GetAdjustedTime();
5228 int64_t nSince
= nNow
- 10 * 60;
5229 BOOST_FOREACH(CAddress
& addr
, vAddr
)
5231 boost::this_thread::interruption_point();
5233 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
5236 if (addr
.nTime
<= 100000000 || addr
.nTime
> nNow
+ 10 * 60)
5237 addr
.nTime
= nNow
- 5 * 24 * 60 * 60;
5238 pfrom
->AddAddressKnown(addr
);
5239 bool fReachable
= IsReachable(addr
);
5240 if (addr
.nTime
> nSince
&& !pfrom
->fGetAddr
&& vAddr
.size() <= 10 && addr
.IsRoutable())
5242 // Relay to a limited number of other nodes
5243 RelayAddress(addr
, fReachable
, connman
);
5245 // Do not store addresses outside our network
5247 vAddrOk
.push_back(addr
);
5249 connman
.AddNewAddresses(vAddrOk
, pfrom
->addr
, 2 * 60 * 60);
5250 if (vAddr
.size() < 1000)
5251 pfrom
->fGetAddr
= false;
5252 if (pfrom
->fOneShot
)
5253 pfrom
->fDisconnect
= true;
5256 else if (strCommand
== NetMsgType::SENDHEADERS
)
5259 State(pfrom
->GetId())->fPreferHeaders
= true;
5262 else if (strCommand
== NetMsgType::SENDCMPCT
)
5264 bool fAnnounceUsingCMPCTBLOCK
= false;
5265 uint64_t nCMPCTBLOCKVersion
= 0;
5266 vRecv
>> fAnnounceUsingCMPCTBLOCK
>> nCMPCTBLOCKVersion
;
5267 if (nCMPCTBLOCKVersion
== 1 || ((pfrom
->GetLocalServices() & NODE_WITNESS
) && nCMPCTBLOCKVersion
== 2)) {
5269 // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
5270 if (!State(pfrom
->GetId())->fProvidesHeaderAndIDs
) {
5271 State(pfrom
->GetId())->fProvidesHeaderAndIDs
= true;
5272 State(pfrom
->GetId())->fWantsCmpctWitness
= nCMPCTBLOCKVersion
== 2;
5274 if (State(pfrom
->GetId())->fWantsCmpctWitness
== (nCMPCTBLOCKVersion
== 2)) // ignore later version announces
5275 State(pfrom
->GetId())->fPreferHeaderAndIDs
= fAnnounceUsingCMPCTBLOCK
;
5276 if (!State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
) {
5277 if (pfrom
->GetLocalServices() & NODE_WITNESS
)
5278 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 2);
5280 State(pfrom
->GetId())->fSupportsDesiredCmpctVersion
= (nCMPCTBLOCKVersion
== 1);
5286 else if (strCommand
== NetMsgType::INV
)
5290 if (vInv
.size() > MAX_INV_SZ
)
5293 Misbehaving(pfrom
->GetId(), 20);
5294 return error("message inv size() = %u", vInv
.size());
5297 bool fBlocksOnly
= !fRelayTxes
;
5299 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
5300 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
))
5301 fBlocksOnly
= false;
5305 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus());
5307 std::vector
<CInv
> vToFetch
;
5309 for (unsigned int nInv
= 0; nInv
< vInv
.size(); nInv
++)
5311 CInv
&inv
= vInv
[nInv
];
5313 boost::this_thread::interruption_point();
5315 bool fAlreadyHave
= AlreadyHave(inv
);
5316 LogPrint("net", "got inv: %s %s peer=%d\n", inv
.ToString(), fAlreadyHave
? "have" : "new", pfrom
->id
);
5318 if (inv
.type
== MSG_TX
) {
5319 inv
.type
|= nFetchFlags
;
5322 if (inv
.type
== MSG_BLOCK
) {
5323 UpdateBlockAvailability(pfrom
->GetId(), inv
.hash
);
5324 if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !mapBlocksInFlight
.count(inv
.hash
)) {
5325 // First request the headers preceding the announced block. In the normal fully-synced
5326 // case where a new block is announced that succeeds the current tip (no reorganization),
5327 // there are no such headers.
5328 // Secondly, and only when we are close to being synced, we request the announced block directly,
5329 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
5330 // time the block arrives, the header chain leading up to it is already validated. Not
5331 // doing this will result in the received block being rejected as an orphan in case it is
5332 // not a direct successor.
5333 pfrom
->PushMessage(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), inv
.hash
);
5334 CNodeState
*nodestate
= State(pfrom
->GetId());
5335 if (CanDirectFetch(chainparams
.GetConsensus()) &&
5336 nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
&&
5337 (!IsWitnessEnabled(chainActive
.Tip(), chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
5338 inv
.type
|= nFetchFlags
;
5339 if (nodestate
->fSupportsDesiredCmpctVersion
)
5340 vToFetch
.push_back(CInv(MSG_CMPCT_BLOCK
, inv
.hash
));
5342 vToFetch
.push_back(inv
);
5343 // Mark block as in flight already, even though the actual "getdata" message only goes out
5344 // later (within the same cs_main lock, though).
5345 MarkBlockAsInFlight(pfrom
->GetId(), inv
.hash
, chainparams
.GetConsensus());
5347 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader
->nHeight
, inv
.hash
.ToString(), pfrom
->id
);
5352 pfrom
->AddInventoryKnown(inv
);
5354 LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv
.hash
.ToString(), pfrom
->id
);
5355 else if (!fAlreadyHave
&& !fImporting
&& !fReindex
&& !IsInitialBlockDownload())
5359 // Track requests for our stuff
5360 GetMainSignals().Inventory(inv
.hash
);
5362 if (pfrom
->nSendSize
> (nMaxSendBufferSize
* 2)) {
5363 Misbehaving(pfrom
->GetId(), 50);
5364 return error("send buffer size() = %u", pfrom
->nSendSize
);
5368 if (!vToFetch
.empty())
5369 pfrom
->PushMessage(NetMsgType::GETDATA
, vToFetch
);
5373 else if (strCommand
== NetMsgType::GETDATA
)
5377 if (vInv
.size() > MAX_INV_SZ
)
5380 Misbehaving(pfrom
->GetId(), 20);
5381 return error("message getdata size() = %u", vInv
.size());
5384 if (fDebug
|| (vInv
.size() != 1))
5385 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv
.size(), pfrom
->id
);
5387 if ((fDebug
&& vInv
.size() > 0) || (vInv
.size() == 1))
5388 LogPrint("net", "received getdata for: %s peer=%d\n", vInv
[0].ToString(), pfrom
->id
);
5390 pfrom
->vRecvGetData
.insert(pfrom
->vRecvGetData
.end(), vInv
.begin(), vInv
.end());
5391 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
);
5395 else if (strCommand
== NetMsgType::GETBLOCKS
)
5397 CBlockLocator locator
;
5399 vRecv
>> locator
>> hashStop
;
5403 // Find the last block the caller has in the main chain
5404 CBlockIndex
* pindex
= FindForkInGlobalIndex(chainActive
, locator
);
5406 // Send the rest of the chain
5408 pindex
= chainActive
.Next(pindex
);
5410 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), nLimit
, pfrom
->id
);
5411 for (; pindex
; pindex
= chainActive
.Next(pindex
))
5413 if (pindex
->GetBlockHash() == hashStop
)
5415 LogPrint("net", " getblocks stopping at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
5418 // If pruning, don't inv blocks unless we have on disk and are likely to still have
5419 // for some reasonable time window (1 hour) that block relay might require.
5420 const int nPrunedBlocksLikelyToHave
= MIN_BLOCKS_TO_KEEP
- 3600 / chainparams
.GetConsensus().nPowTargetSpacing
;
5421 if (fPruneMode
&& (!(pindex
->nStatus
& BLOCK_HAVE_DATA
) || pindex
->nHeight
<= chainActive
.Tip()->nHeight
- nPrunedBlocksLikelyToHave
))
5423 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
5426 pfrom
->PushInventory(CInv(MSG_BLOCK
, pindex
->GetBlockHash()));
5429 // When this block is requested, we'll send an inv that'll
5430 // trigger the peer to getblocks the next batch of inventory.
5431 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
5432 pfrom
->hashContinue
= pindex
->GetBlockHash();
5439 else if (strCommand
== NetMsgType::GETBLOCKTXN
)
5441 BlockTransactionsRequest req
;
5444 BlockMap::iterator it
= mapBlockIndex
.find(req
.blockhash
);
5445 if (it
== mapBlockIndex
.end() || !(it
->second
->nStatus
& BLOCK_HAVE_DATA
)) {
5446 LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom
->id
);
5450 if (it
->second
->nHeight
< chainActive
.Height() - MAX_BLOCKTXN_DEPTH
) {
5451 LogPrint("net", "Peer %d sent us a getblocktxn for a block > %i deep", pfrom
->id
, MAX_BLOCKTXN_DEPTH
);
5456 assert(ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus()));
5458 BlockTransactions
resp(req
);
5459 for (size_t i
= 0; i
< req
.indexes
.size(); i
++) {
5460 if (req
.indexes
[i
] >= block
.vtx
.size()) {
5461 Misbehaving(pfrom
->GetId(), 100);
5462 LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom
->id
);
5465 resp
.txn
[i
] = block
.vtx
[req
.indexes
[i
]];
5467 pfrom
->PushMessageWithFlag(State(pfrom
->GetId())->fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::BLOCKTXN
, resp
);
5471 else if (strCommand
== NetMsgType::GETHEADERS
)
5473 CBlockLocator locator
;
5475 vRecv
>> locator
>> hashStop
;
5478 if (IsInitialBlockDownload() && !pfrom
->fWhitelisted
) {
5479 LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom
->id
);
5483 CNodeState
*nodestate
= State(pfrom
->GetId());
5484 CBlockIndex
* pindex
= NULL
;
5485 if (locator
.IsNull())
5487 // If locator is null, return the hashStop block
5488 BlockMap::iterator mi
= mapBlockIndex
.find(hashStop
);
5489 if (mi
== mapBlockIndex
.end())
5491 pindex
= (*mi
).second
;
5495 // Find the last block the caller has in the main chain
5496 pindex
= FindForkInGlobalIndex(chainActive
, locator
);
5498 pindex
= chainActive
.Next(pindex
);
5501 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5502 vector
<CBlock
> vHeaders
;
5503 int nLimit
= MAX_HEADERS_RESULTS
;
5504 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex
? pindex
->nHeight
: -1), hashStop
.IsNull() ? "end" : hashStop
.ToString(), pfrom
->id
);
5505 for (; pindex
; pindex
= chainActive
.Next(pindex
))
5507 vHeaders
.push_back(pindex
->GetBlockHeader());
5508 if (--nLimit
<= 0 || pindex
->GetBlockHash() == hashStop
)
5511 // pindex can be NULL either if we sent chainActive.Tip() OR
5512 // if our peer has chainActive.Tip() (and thus we are sending an empty
5513 // headers message). In both cases it's safe to update
5514 // pindexBestHeaderSent to be our tip.
5515 nodestate
->pindexBestHeaderSent
= pindex
? pindex
: chainActive
.Tip();
5516 pfrom
->PushMessage(NetMsgType::HEADERS
, vHeaders
);
5520 else if (strCommand
== NetMsgType::TX
)
5522 // Stop processing the transaction early if
5523 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
5524 if (!fRelayTxes
&& (!pfrom
->fWhitelisted
|| !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY
)))
5526 LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom
->id
);
5530 deque
<COutPoint
> vWorkQueue
;
5531 vector
<uint256
> vEraseQueue
;
5535 CInv
inv(MSG_TX
, tx
.GetHash());
5536 pfrom
->AddInventoryKnown(inv
);
5540 bool fMissingInputs
= false;
5541 CValidationState state
;
5543 pfrom
->setAskFor
.erase(inv
.hash
);
5544 mapAlreadyAskedFor
.erase(inv
.hash
);
5546 if (!AlreadyHave(inv
) && AcceptToMemoryPool(mempool
, state
, tx
, true, &fMissingInputs
)) {
5547 mempool
.check(pcoinsTip
);
5548 RelayTransaction(tx
, connman
);
5549 for (unsigned int i
= 0; i
< tx
.vout
.size(); i
++) {
5550 vWorkQueue
.emplace_back(inv
.hash
, i
);
5553 pfrom
->nLastTXTime
= GetTime();
5555 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
5557 tx
.GetHash().ToString(),
5558 mempool
.size(), mempool
.DynamicMemoryUsage() / 1000);
5560 // Recursively process any orphan transactions that depended on this one
5561 set
<NodeId
> setMisbehaving
;
5562 while (!vWorkQueue
.empty()) {
5563 auto itByPrev
= mapOrphanTransactionsByPrev
.find(vWorkQueue
.front());
5564 vWorkQueue
.pop_front();
5565 if (itByPrev
== mapOrphanTransactionsByPrev
.end())
5567 for (auto mi
= itByPrev
->second
.begin();
5568 mi
!= itByPrev
->second
.end();
5571 const CTransaction
& orphanTx
= (*mi
)->second
.tx
;
5572 const uint256
& orphanHash
= orphanTx
.GetHash();
5573 NodeId fromPeer
= (*mi
)->second
.fromPeer
;
5574 bool fMissingInputs2
= false;
5575 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5576 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5577 // anyone relaying LegitTxX banned)
5578 CValidationState stateDummy
;
5581 if (setMisbehaving
.count(fromPeer
))
5583 if (AcceptToMemoryPool(mempool
, stateDummy
, orphanTx
, true, &fMissingInputs2
)) {
5584 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash
.ToString());
5585 RelayTransaction(orphanTx
, connman
);
5586 for (unsigned int i
= 0; i
< orphanTx
.vout
.size(); i
++) {
5587 vWorkQueue
.emplace_back(orphanHash
, i
);
5589 vEraseQueue
.push_back(orphanHash
);
5591 else if (!fMissingInputs2
)
5594 if (stateDummy
.IsInvalid(nDos
) && nDos
> 0)
5596 // Punish peer that gave us an invalid orphan tx
5597 Misbehaving(fromPeer
, nDos
);
5598 setMisbehaving
.insert(fromPeer
);
5599 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash
.ToString());
5601 // Has inputs but not accepted to mempool
5602 // Probably non-standard or insufficient fee/priority
5603 LogPrint("mempool", " removed orphan tx %s\n", orphanHash
.ToString());
5604 vEraseQueue
.push_back(orphanHash
);
5605 if (orphanTx
.wit
.IsNull() && !stateDummy
.CorruptionPossible()) {
5606 // Do not use rejection cache for witness transactions or
5607 // witness-stripped transactions, as they can have been malleated.
5608 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
5609 assert(recentRejects
);
5610 recentRejects
->insert(orphanHash
);
5613 mempool
.check(pcoinsTip
);
5617 BOOST_FOREACH(uint256 hash
, vEraseQueue
)
5618 EraseOrphanTx(hash
);
5620 else if (fMissingInputs
)
5622 bool fRejectedParents
= false; // It may be the case that the orphans parents have all been rejected
5623 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
5624 if (recentRejects
->contains(txin
.prevout
.hash
)) {
5625 fRejectedParents
= true;
5629 if (!fRejectedParents
) {
5630 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
5631 CInv
_inv(MSG_TX
, txin
.prevout
.hash
);
5632 pfrom
->AddInventoryKnown(_inv
);
5633 if (!AlreadyHave(_inv
)) pfrom
->AskFor(_inv
);
5635 AddOrphanTx(tx
, pfrom
->GetId());
5637 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5638 unsigned int nMaxOrphanTx
= (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS
));
5639 unsigned int nEvicted
= LimitOrphanTxSize(nMaxOrphanTx
);
5641 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted
);
5643 LogPrint("mempool", "not keeping orphan with rejected parents %s\n",tx
.GetHash().ToString());
5646 if (tx
.wit
.IsNull() && !state
.CorruptionPossible()) {
5647 // Do not use rejection cache for witness transactions or
5648 // witness-stripped transactions, as they can have been malleated.
5649 // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
5650 assert(recentRejects
);
5651 recentRejects
->insert(tx
.GetHash());
5654 if (pfrom
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
)) {
5655 // Always relay transactions received from whitelisted peers, even
5656 // if they were already in the mempool or rejected from it due
5657 // to policy, allowing the node to function as a gateway for
5658 // nodes hidden behind it.
5660 // Never relay transactions that we would assign a non-zero DoS
5661 // score for, as we expect peers to do the same with us in that
5664 if (!state
.IsInvalid(nDoS
) || nDoS
== 0) {
5665 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx
.GetHash().ToString(), pfrom
->id
);
5666 RelayTransaction(tx
, connman
);
5668 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx
.GetHash().ToString(), pfrom
->id
, FormatStateMessage(state
));
5673 if (state
.IsInvalid(nDoS
))
5675 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx
.GetHash().ToString(),
5677 FormatStateMessage(state
));
5678 if (state
.GetRejectCode() < REJECT_INTERNAL
) // Never send AcceptToMemoryPool's internal codes over P2P
5679 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
5680 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), inv
.hash
);
5682 Misbehaving(pfrom
->GetId(), nDoS
);
5685 FlushStateToDisk(state
, FLUSH_STATE_PERIODIC
);
5689 else if (strCommand
== NetMsgType::CMPCTBLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
5691 CBlockHeaderAndShortTxIDs cmpctblock
;
5692 vRecv
>> cmpctblock
;
5696 if (mapBlockIndex
.find(cmpctblock
.header
.hashPrevBlock
) == mapBlockIndex
.end()) {
5697 // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
5698 if (!IsInitialBlockDownload())
5699 pfrom
->PushMessage(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256());
5703 CBlockIndex
*pindex
= NULL
;
5704 CValidationState state
;
5705 if (!AcceptBlockHeader(cmpctblock
.header
, state
, chainparams
, &pindex
)) {
5707 if (state
.IsInvalid(nDoS
)) {
5709 Misbehaving(pfrom
->GetId(), nDoS
);
5710 LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom
->id
);
5715 // If AcceptBlockHeader returned true, it set pindex
5717 UpdateBlockAvailability(pfrom
->GetId(), pindex
->GetBlockHash());
5719 std::map
<uint256
, pair
<NodeId
, list
<QueuedBlock
>::iterator
> >::iterator blockInFlightIt
= mapBlocksInFlight
.find(pindex
->GetBlockHash());
5720 bool fAlreadyInFlight
= blockInFlightIt
!= mapBlocksInFlight
.end();
5722 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) // Nothing to do here
5725 if (pindex
->nChainWork
<= chainActive
.Tip()->nChainWork
|| // We know something better
5726 pindex
->nTx
!= 0) { // We had this block at some point, but pruned it
5727 if (fAlreadyInFlight
) {
5728 // We requested this block for some reason, but our mempool will probably be useless
5729 // so we just grab the block via normal getdata
5730 std::vector
<CInv
> vInv(1);
5731 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
5732 pfrom
->PushMessage(NetMsgType::GETDATA
, vInv
);
5737 // If we're not close to tip yet, give up and let parallel block fetch work its magic
5738 if (!fAlreadyInFlight
&& !CanDirectFetch(chainparams
.GetConsensus()))
5741 CNodeState
*nodestate
= State(pfrom
->GetId());
5743 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus()) && !nodestate
->fSupportsDesiredCmpctVersion
) {
5744 // Don't bother trying to process compact blocks from v1 peers
5745 // after segwit activates.
5749 // We want to be a bit conservative just to be extra careful about DoS
5750 // possibilities in compact block processing...
5751 if (pindex
->nHeight
<= chainActive
.Height() + 2) {
5752 if ((!fAlreadyInFlight
&& nodestate
->nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) ||
5753 (fAlreadyInFlight
&& blockInFlightIt
->second
.first
== pfrom
->GetId())) {
5754 list
<QueuedBlock
>::iterator
*queuedBlockIt
= NULL
;
5755 if (!MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
, &queuedBlockIt
)) {
5756 if (!(*queuedBlockIt
)->partialBlock
)
5757 (*queuedBlockIt
)->partialBlock
.reset(new PartiallyDownloadedBlock(&mempool
));
5759 // The block was already in flight using compact blocks from the same peer
5760 LogPrint("net", "Peer sent us compact block we were already syncing!\n");
5765 PartiallyDownloadedBlock
& partialBlock
= *(*queuedBlockIt
)->partialBlock
;
5766 ReadStatus status
= partialBlock
.InitData(cmpctblock
);
5767 if (status
== READ_STATUS_INVALID
) {
5768 MarkBlockAsReceived(pindex
->GetBlockHash()); // Reset in-flight state in case of whitelist
5769 Misbehaving(pfrom
->GetId(), 100);
5770 LogPrintf("Peer %d sent us invalid compact block\n", pfrom
->id
);
5772 } else if (status
== READ_STATUS_FAILED
) {
5773 // Duplicate txindexes, the block is now in-flight, so just request it
5774 std::vector
<CInv
> vInv(1);
5775 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
5776 pfrom
->PushMessage(NetMsgType::GETDATA
, vInv
);
5780 if (!fAlreadyInFlight
&& mapBlocksInFlight
.size() == 1 && pindex
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
5781 // We seem to be rather well-synced, so it appears pfrom was the first to provide us
5782 // with this block! Let's get them to announce using compact blocks in the future.
5783 MaybeSetPeerAsAnnouncingHeaderAndIDs(nodestate
, pfrom
, connman
);
5786 BlockTransactionsRequest req
;
5787 for (size_t i
= 0; i
< cmpctblock
.BlockTxCount(); i
++) {
5788 if (!partialBlock
.IsTxAvailable(i
))
5789 req
.indexes
.push_back(i
);
5791 if (req
.indexes
.empty()) {
5792 // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
5793 BlockTransactions txn
;
5794 txn
.blockhash
= cmpctblock
.header
.GetHash();
5795 CDataStream
blockTxnMsg(SER_NETWORK
, PROTOCOL_VERSION
);
5797 return ProcessMessage(pfrom
, NetMsgType::BLOCKTXN
, blockTxnMsg
, nTimeReceived
, chainparams
, connman
);
5799 req
.blockhash
= pindex
->GetBlockHash();
5800 pfrom
->PushMessage(NetMsgType::GETBLOCKTXN
, req
);
5804 if (fAlreadyInFlight
) {
5805 // We requested this block, but its far into the future, so our
5806 // mempool will probably be useless - request the block normally
5807 std::vector
<CInv
> vInv(1);
5808 vInv
[0] = CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus()), cmpctblock
.header
.GetHash());
5809 pfrom
->PushMessage(NetMsgType::GETDATA
, vInv
);
5812 // If this was an announce-cmpctblock, we want the same treatment as a header message
5813 // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
5814 std::vector
<CBlock
> headers
;
5815 headers
.push_back(cmpctblock
.header
);
5816 CDataStream
vHeadersMsg(SER_NETWORK
, PROTOCOL_VERSION
);
5817 vHeadersMsg
<< headers
;
5818 return ProcessMessage(pfrom
, NetMsgType::HEADERS
, vHeadersMsg
, nTimeReceived
, chainparams
, connman
);
5822 CheckBlockIndex(chainparams
.GetConsensus());
5825 else if (strCommand
== NetMsgType::BLOCKTXN
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
5827 BlockTransactions resp
;
5831 bool fBlockRead
= false;
5835 map
<uint256
, pair
<NodeId
, list
<QueuedBlock
>::iterator
> >::iterator it
= mapBlocksInFlight
.find(resp
.blockhash
);
5836 if (it
== mapBlocksInFlight
.end() || !it
->second
.second
->partialBlock
||
5837 it
->second
.first
!= pfrom
->GetId()) {
5838 LogPrint("net", "Peer %d sent us block transactions for block we weren't expecting\n", pfrom
->id
);
5842 PartiallyDownloadedBlock
& partialBlock
= *it
->second
.second
->partialBlock
;
5843 ReadStatus status
= partialBlock
.FillBlock(block
, resp
.txn
);
5844 if (status
== READ_STATUS_INVALID
) {
5845 MarkBlockAsReceived(resp
.blockhash
); // Reset in-flight state in case of whitelist
5846 Misbehaving(pfrom
->GetId(), 100);
5847 LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom
->id
);
5849 } else if (status
== READ_STATUS_FAILED
) {
5850 // Might have collided, fall back to getdata now :(
5851 std::vector
<CInv
> invs
;
5852 invs
.push_back(CInv(MSG_BLOCK
| GetFetchFlags(pfrom
, chainActive
.Tip(), chainparams
.GetConsensus()), resp
.blockhash
));
5853 pfrom
->PushMessage(NetMsgType::GETDATA
, invs
);
5856 } // Don't hold cs_main when we call into ProcessNewBlock
5858 CValidationState state
;
5859 ProcessNewBlock(state
, chainparams
, pfrom
, &block
, false, NULL
);
5861 if (state
.IsInvalid(nDoS
)) {
5862 assert (state
.GetRejectCode() < REJECT_INTERNAL
); // Blocks are never rejected with internal reject codes
5863 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
5864 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), block
.GetHash());
5867 Misbehaving(pfrom
->GetId(), nDoS
);
5874 else if (strCommand
== NetMsgType::HEADERS
&& !fImporting
&& !fReindex
) // Ignore headers received while importing
5876 std::vector
<CBlockHeader
> headers
;
5878 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5879 unsigned int nCount
= ReadCompactSize(vRecv
);
5880 if (nCount
> MAX_HEADERS_RESULTS
) {
5882 Misbehaving(pfrom
->GetId(), 20);
5883 return error("headers message size = %u", nCount
);
5885 headers
.resize(nCount
);
5886 for (unsigned int n
= 0; n
< nCount
; n
++) {
5887 vRecv
>> headers
[n
];
5888 ReadCompactSize(vRecv
); // ignore tx count; assume it is 0.
5895 // Nothing interesting. Stop asking this peers for more headers.
5899 CNodeState
*nodestate
= State(pfrom
->GetId());
5901 // If this looks like it could be a block announcement (nCount <
5902 // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
5904 // - Send a getheaders message in response to try to connect the chain.
5905 // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
5906 // don't connect before giving DoS points
5907 // - Once a headers message is received that is valid and does connect,
5908 // nUnconnectingHeaders gets reset back to 0.
5909 if (mapBlockIndex
.find(headers
[0].hashPrevBlock
) == mapBlockIndex
.end() && nCount
< MAX_BLOCKS_TO_ANNOUNCE
) {
5910 nodestate
->nUnconnectingHeaders
++;
5911 pfrom
->PushMessage(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexBestHeader
), uint256());
5912 LogPrint("net", "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
5913 headers
[0].GetHash().ToString(),
5914 headers
[0].hashPrevBlock
.ToString(),
5915 pindexBestHeader
->nHeight
,
5916 pfrom
->id
, nodestate
->nUnconnectingHeaders
);
5917 // Set hashLastUnknownBlock for this peer, so that if we
5918 // eventually get the headers - even from a different peer -
5919 // we can use this peer to download.
5920 UpdateBlockAvailability(pfrom
->GetId(), headers
.back().GetHash());
5922 if (nodestate
->nUnconnectingHeaders
% MAX_UNCONNECTING_HEADERS
== 0) {
5923 Misbehaving(pfrom
->GetId(), 20);
5928 CBlockIndex
*pindexLast
= NULL
;
5929 BOOST_FOREACH(const CBlockHeader
& header
, headers
) {
5930 CValidationState state
;
5931 if (pindexLast
!= NULL
&& header
.hashPrevBlock
!= pindexLast
->GetBlockHash()) {
5932 Misbehaving(pfrom
->GetId(), 20);
5933 return error("non-continuous headers sequence");
5935 if (!AcceptBlockHeader(header
, state
, chainparams
, &pindexLast
)) {
5937 if (state
.IsInvalid(nDoS
)) {
5939 Misbehaving(pfrom
->GetId(), nDoS
);
5940 return error("invalid header received");
5945 if (nodestate
->nUnconnectingHeaders
> 0) {
5946 LogPrint("net", "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom
->id
, nodestate
->nUnconnectingHeaders
);
5948 nodestate
->nUnconnectingHeaders
= 0;
5951 UpdateBlockAvailability(pfrom
->GetId(), pindexLast
->GetBlockHash());
5953 if (nCount
== MAX_HEADERS_RESULTS
) {
5954 // Headers message had its maximum size; the peer may have more headers.
5955 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5956 // from there instead.
5957 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast
->nHeight
, pfrom
->id
, pfrom
->nStartingHeight
);
5958 pfrom
->PushMessage(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexLast
), uint256());
5961 bool fCanDirectFetch
= CanDirectFetch(chainparams
.GetConsensus());
5962 // If this set of headers is valid and ends in a block with at least as
5963 // much work as our tip, download as much as possible.
5964 if (fCanDirectFetch
&& pindexLast
->IsValid(BLOCK_VALID_TREE
) && chainActive
.Tip()->nChainWork
<= pindexLast
->nChainWork
) {
5965 vector
<CBlockIndex
*> vToFetch
;
5966 CBlockIndex
*pindexWalk
= pindexLast
;
5967 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
5968 while (pindexWalk
&& !chainActive
.Contains(pindexWalk
) && vToFetch
.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
5969 if (!(pindexWalk
->nStatus
& BLOCK_HAVE_DATA
) &&
5970 !mapBlocksInFlight
.count(pindexWalk
->GetBlockHash()) &&
5971 (!IsWitnessEnabled(pindexWalk
->pprev
, chainparams
.GetConsensus()) || State(pfrom
->GetId())->fHaveWitness
)) {
5972 // We don't have this block, and it's not yet in flight.
5973 vToFetch
.push_back(pindexWalk
);
5975 pindexWalk
= pindexWalk
->pprev
;
5977 // If pindexWalk still isn't on our main chain, we're looking at a
5978 // very large reorg at a time we think we're close to caught up to
5979 // the main chain -- this shouldn't really happen. Bail out on the
5980 // direct fetch and rely on parallel download instead.
5981 if (!chainActive
.Contains(pindexWalk
)) {
5982 LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
5983 pindexLast
->GetBlockHash().ToString(),
5984 pindexLast
->nHeight
);
5986 vector
<CInv
> vGetData
;
5987 // Download as much as possible, from earliest to latest.
5988 BOOST_REVERSE_FOREACH(CBlockIndex
*pindex
, vToFetch
) {
5989 if (nodestate
->nBlocksInFlight
>= MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
5990 // Can't download any more from this peer
5993 uint32_t nFetchFlags
= GetFetchFlags(pfrom
, pindex
->pprev
, chainparams
.GetConsensus());
5994 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
5995 MarkBlockAsInFlight(pfrom
->GetId(), pindex
->GetBlockHash(), chainparams
.GetConsensus(), pindex
);
5996 LogPrint("net", "Requesting block %s from peer=%d\n",
5997 pindex
->GetBlockHash().ToString(), pfrom
->id
);
5999 if (vGetData
.size() > 1) {
6000 LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
6001 pindexLast
->GetBlockHash().ToString(), pindexLast
->nHeight
);
6003 if (vGetData
.size() > 0) {
6004 if (nodestate
->fSupportsDesiredCmpctVersion
&& vGetData
.size() == 1 && mapBlocksInFlight
.size() == 1 && pindexLast
->pprev
->IsValid(BLOCK_VALID_CHAIN
)) {
6005 // We seem to be rather well-synced, so it appears pfrom was the first to provide us
6006 // with this block! Let's get them to announce using compact blocks in the future.
6007 MaybeSetPeerAsAnnouncingHeaderAndIDs(nodestate
, pfrom
, connman
);
6008 // In any case, we want to download using a compact block, not a regular one
6009 vGetData
[0] = CInv(MSG_CMPCT_BLOCK
, vGetData
[0].hash
);
6011 pfrom
->PushMessage(NetMsgType::GETDATA
, vGetData
);
6016 CheckBlockIndex(chainparams
.GetConsensus());
6022 else if (strCommand
== NetMsgType::BLOCK
&& !fImporting
&& !fReindex
) // Ignore blocks received while importing
6027 LogPrint("net", "received block %s peer=%d\n", block
.GetHash().ToString(), pfrom
->id
);
6029 CValidationState state
;
6030 // Process all blocks from whitelisted peers, even if not requested,
6031 // unless we're still syncing with the network.
6032 // Such an unrequested block may still be processed, subject to the
6033 // conditions in AcceptBlock().
6034 bool forceProcessing
= pfrom
->fWhitelisted
&& !IsInitialBlockDownload();
6035 ProcessNewBlock(state
, chainparams
, pfrom
, &block
, forceProcessing
, NULL
);
6037 if (state
.IsInvalid(nDoS
)) {
6038 assert (state
.GetRejectCode() < REJECT_INTERNAL
); // Blocks are never rejected with internal reject codes
6039 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, (unsigned char)state
.GetRejectCode(),
6040 state
.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH
), block
.GetHash());
6043 Misbehaving(pfrom
->GetId(), nDoS
);
6050 else if (strCommand
== NetMsgType::GETADDR
)
6052 // This asymmetric behavior for inbound and outbound connections was introduced
6053 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
6054 // to users' AddrMan and later request them by sending getaddr messages.
6055 // Making nodes which are behind NAT and can only make outgoing connections ignore
6056 // the getaddr message mitigates the attack.
6057 if (!pfrom
->fInbound
) {
6058 LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom
->id
);
6062 // Only send one GetAddr response per connection to reduce resource waste
6063 // and discourage addr stamping of INV announcements.
6064 if (pfrom
->fSentAddr
) {
6065 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom
->id
);
6068 pfrom
->fSentAddr
= true;
6070 pfrom
->vAddrToSend
.clear();
6071 vector
<CAddress
> vAddr
= connman
.GetAddresses();
6072 FastRandomContext insecure_rand
;
6073 BOOST_FOREACH(const CAddress
&addr
, vAddr
)
6074 pfrom
->PushAddress(addr
, insecure_rand
);
6078 else if (strCommand
== NetMsgType::MEMPOOL
)
6080 if (!(pfrom
->GetLocalServices() & NODE_BLOOM
) && !pfrom
->fWhitelisted
)
6082 LogPrint("net", "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom
->GetId());
6083 pfrom
->fDisconnect
= true;
6087 if (connman
.OutboundTargetReached(false) && !pfrom
->fWhitelisted
)
6089 LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom
->GetId());
6090 pfrom
->fDisconnect
= true;
6094 LOCK(pfrom
->cs_inventory
);
6095 pfrom
->fSendMempool
= true;
6099 else if (strCommand
== NetMsgType::PING
)
6101 if (pfrom
->nVersion
> BIP0031_VERSION
)
6105 // Echo the message back with the nonce. This allows for two useful features:
6107 // 1) A remote node can quickly check if the connection is operational
6108 // 2) Remote nodes can measure the latency of the network thread. If this node
6109 // is overloaded it won't respond to pings quickly and the remote node can
6110 // avoid sending us more work, like chain download requests.
6112 // The nonce stops the remote getting confused between different pings: without
6113 // it, if the remote node sends a ping once per second and this node takes 5
6114 // seconds to respond to each, the 5th ping the remote sends would appear to
6115 // return very quickly.
6116 pfrom
->PushMessage(NetMsgType::PONG
, nonce
);
6121 else if (strCommand
== NetMsgType::PONG
)
6123 int64_t pingUsecEnd
= nTimeReceived
;
6125 size_t nAvail
= vRecv
.in_avail();
6126 bool bPingFinished
= false;
6127 std::string sProblem
;
6129 if (nAvail
>= sizeof(nonce
)) {
6132 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
6133 if (pfrom
->nPingNonceSent
!= 0) {
6134 if (nonce
== pfrom
->nPingNonceSent
) {
6135 // Matching pong received, this ping is no longer outstanding
6136 bPingFinished
= true;
6137 int64_t pingUsecTime
= pingUsecEnd
- pfrom
->nPingUsecStart
;
6138 if (pingUsecTime
> 0) {
6139 // Successful ping time measurement, replace previous
6140 pfrom
->nPingUsecTime
= pingUsecTime
;
6141 pfrom
->nMinPingUsecTime
= std::min(pfrom
->nMinPingUsecTime
, pingUsecTime
);
6143 // This should never happen
6144 sProblem
= "Timing mishap";
6147 // Nonce mismatches are normal when pings are overlapping
6148 sProblem
= "Nonce mismatch";
6150 // This is most likely a bug in another implementation somewhere; cancel this ping
6151 bPingFinished
= true;
6152 sProblem
= "Nonce zero";
6156 sProblem
= "Unsolicited pong without ping";
6159 // This is most likely a bug in another implementation somewhere; cancel this ping
6160 bPingFinished
= true;
6161 sProblem
= "Short payload";
6164 if (!(sProblem
.empty())) {
6165 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
6168 pfrom
->nPingNonceSent
,
6172 if (bPingFinished
) {
6173 pfrom
->nPingNonceSent
= 0;
6178 else if (strCommand
== NetMsgType::FILTERLOAD
)
6180 CBloomFilter filter
;
6183 if (!filter
.IsWithinSizeConstraints())
6185 // There is no excuse for sending a too-large filter
6187 Misbehaving(pfrom
->GetId(), 100);
6191 LOCK(pfrom
->cs_filter
);
6192 delete pfrom
->pfilter
;
6193 pfrom
->pfilter
= new CBloomFilter(filter
);
6194 pfrom
->pfilter
->UpdateEmptyFull();
6195 pfrom
->fRelayTxes
= true;
6200 else if (strCommand
== NetMsgType::FILTERADD
)
6202 vector
<unsigned char> vData
;
6205 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
6206 // and thus, the maximum size any matched object can have) in a filteradd message
6208 if (vData
.size() > MAX_SCRIPT_ELEMENT_SIZE
) {
6211 LOCK(pfrom
->cs_filter
);
6212 if (pfrom
->pfilter
) {
6213 pfrom
->pfilter
->insert(vData
);
6220 Misbehaving(pfrom
->GetId(), 100);
6225 else if (strCommand
== NetMsgType::FILTERCLEAR
)
6227 LOCK(pfrom
->cs_filter
);
6228 delete pfrom
->pfilter
;
6229 pfrom
->pfilter
= new CBloomFilter();
6230 pfrom
->fRelayTxes
= true;
6234 else if (strCommand
== NetMsgType::REJECT
)
6238 string strMsg
; unsigned char ccode
; string strReason
;
6239 vRecv
>> LIMITED_STRING(strMsg
, CMessageHeader::COMMAND_SIZE
) >> ccode
>> LIMITED_STRING(strReason
, MAX_REJECT_MESSAGE_LENGTH
);
6242 ss
<< strMsg
<< " code " << itostr(ccode
) << ": " << strReason
;
6244 if (strMsg
== NetMsgType::BLOCK
|| strMsg
== NetMsgType::TX
)
6248 ss
<< ": hash " << hash
.ToString();
6250 LogPrint("net", "Reject %s\n", SanitizeString(ss
.str()));
6251 } catch (const std::ios_base::failure
&) {
6252 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
6253 LogPrint("net", "Unparseable reject message received\n");
6258 else if (strCommand
== NetMsgType::FEEFILTER
) {
6259 CAmount newFeeFilter
= 0;
6260 vRecv
>> newFeeFilter
;
6261 if (MoneyRange(newFeeFilter
)) {
6263 LOCK(pfrom
->cs_feeFilter
);
6264 pfrom
->minFeeFilter
= newFeeFilter
;
6266 LogPrint("net", "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter
).ToString(), pfrom
->id
);
6270 else if (strCommand
== NetMsgType::NOTFOUND
) {
6271 // We do not care about the NOTFOUND message, but logging an Unknown Command
6272 // message would be undesirable as we transmit it ourselves.
6276 // Ignore unknown commands for extensibility
6277 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand
), pfrom
->id
);
6285 // requires LOCK(cs_vRecvMsg)
6286 bool ProcessMessages(CNode
* pfrom
, CConnman
& connman
)
6288 const CChainParams
& chainparams
= Params();
6289 unsigned int nMaxSendBufferSize
= connman
.GetSendBufferSize();
6291 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
6295 // (4) message start
6303 if (!pfrom
->vRecvGetData
.empty())
6304 ProcessGetData(pfrom
, chainparams
.GetConsensus(), connman
);
6306 // this maintains the order of responses
6307 if (!pfrom
->vRecvGetData
.empty()) return fOk
;
6309 std::deque
<CNetMessage
>::iterator it
= pfrom
->vRecvMsg
.begin();
6310 while (!pfrom
->fDisconnect
&& it
!= pfrom
->vRecvMsg
.end()) {
6311 // Don't bother if send buffer is too full to respond anyway
6312 if (pfrom
->nSendSize
>= nMaxSendBufferSize
)
6316 CNetMessage
& msg
= *it
;
6319 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
6320 // msg.hdr.nMessageSize, msg.vRecv.size(),
6321 // msg.complete() ? "Y" : "N");
6323 // end, if an incomplete message is found
6324 if (!msg
.complete())
6327 // at this point, any failure means we can delete the current message
6330 // Scan for message start
6331 if (memcmp(msg
.hdr
.pchMessageStart
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
) != 0) {
6332 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg
.hdr
.GetCommand()), pfrom
->id
);
6338 CMessageHeader
& hdr
= msg
.hdr
;
6339 if (!hdr
.IsValid(chainparams
.MessageStart()))
6341 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr
.GetCommand()), pfrom
->id
);
6344 string strCommand
= hdr
.GetCommand();
6347 unsigned int nMessageSize
= hdr
.nMessageSize
;
6350 CDataStream
& vRecv
= msg
.vRecv
;
6351 uint256 hash
= Hash(vRecv
.begin(), vRecv
.begin() + nMessageSize
);
6352 if (memcmp(hash
.begin(), hdr
.pchChecksum
, CMessageHeader::CHECKSUM_SIZE
) != 0)
6354 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__
,
6355 SanitizeString(strCommand
), nMessageSize
,
6356 HexStr(hash
.begin(), hash
.begin()+CMessageHeader::CHECKSUM_SIZE
),
6357 HexStr(hdr
.pchChecksum
, hdr
.pchChecksum
+CMessageHeader::CHECKSUM_SIZE
));
6365 fRet
= ProcessMessage(pfrom
, strCommand
, vRecv
, msg
.nTime
, chainparams
, connman
);
6366 boost::this_thread::interruption_point();
6368 catch (const std::ios_base::failure
& e
)
6370 pfrom
->PushMessage(NetMsgType::REJECT
, strCommand
, REJECT_MALFORMED
, string("error parsing message"));
6371 if (strstr(e
.what(), "end of data"))
6373 // Allow exceptions from under-length message on vRecv
6374 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());
6376 else if (strstr(e
.what(), "size too large"))
6378 // Allow exceptions from over-long size
6379 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
6381 else if (strstr(e
.what(), "non-canonical ReadCompactSize()"))
6383 // Allow exceptions from non-canonical encoding
6384 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__
, SanitizeString(strCommand
), nMessageSize
, e
.what());
6388 PrintExceptionContinue(&e
, "ProcessMessages()");
6391 catch (const boost::thread_interrupted
&) {
6394 catch (const std::exception
& e
) {
6395 PrintExceptionContinue(&e
, "ProcessMessages()");
6397 PrintExceptionContinue(NULL
, "ProcessMessages()");
6401 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__
, SanitizeString(strCommand
), nMessageSize
, pfrom
->id
);
6406 // In case the connection got shut down, its receive buffer was wiped
6407 if (!pfrom
->fDisconnect
)
6408 pfrom
->vRecvMsg
.erase(pfrom
->vRecvMsg
.begin(), it
);
6413 class CompareInvMempoolOrder
6417 CompareInvMempoolOrder(CTxMemPool
*_mempool
)
6422 bool operator()(std::set
<uint256
>::iterator a
, std::set
<uint256
>::iterator b
)
6424 /* As std::make_heap produces a max-heap, we want the entries with the
6425 * fewest ancestors/highest fee to sort later. */
6426 return mp
->CompareDepthAndScore(*b
, *a
);
6430 bool SendMessages(CNode
* pto
, CConnman
& connman
)
6432 const Consensus::Params
& consensusParams
= Params().GetConsensus();
6434 // Don't send anything until we get its version message
6435 if (pto
->nVersion
== 0)
6441 bool pingSend
= false;
6442 if (pto
->fPingQueued
) {
6443 // RPC ping request by user
6446 if (pto
->nPingNonceSent
== 0 && pto
->nPingUsecStart
+ PING_INTERVAL
* 1000000 < GetTimeMicros()) {
6447 // Ping automatically sent as a latency probe & keepalive.
6450 if (pingSend
&& !pto
->fDisconnect
) {
6452 while (nonce
== 0) {
6453 GetRandBytes((unsigned char*)&nonce
, sizeof(nonce
));
6455 pto
->fPingQueued
= false;
6456 pto
->nPingUsecStart
= GetTimeMicros();
6457 if (pto
->nVersion
> BIP0031_VERSION
) {
6458 pto
->nPingNonceSent
= nonce
;
6459 pto
->PushMessage(NetMsgType::PING
, nonce
);
6461 // Peer is too old to support ping command with nonce, pong will never arrive.
6462 pto
->nPingNonceSent
= 0;
6463 pto
->PushMessage(NetMsgType::PING
);
6467 TRY_LOCK(cs_main
, lockMain
); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
6471 // Address refresh broadcast
6472 int64_t nNow
= GetTimeMicros();
6473 if (!IsInitialBlockDownload() && pto
->nNextLocalAddrSend
< nNow
) {
6474 AdvertiseLocal(pto
);
6475 pto
->nNextLocalAddrSend
= PoissonNextSend(nNow
, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL
);
6481 if (pto
->nNextAddrSend
< nNow
) {
6482 pto
->nNextAddrSend
= PoissonNextSend(nNow
, AVG_ADDRESS_BROADCAST_INTERVAL
);
6483 vector
<CAddress
> vAddr
;
6484 vAddr
.reserve(pto
->vAddrToSend
.size());
6485 BOOST_FOREACH(const CAddress
& addr
, pto
->vAddrToSend
)
6487 if (!pto
->addrKnown
.contains(addr
.GetKey()))
6489 pto
->addrKnown
.insert(addr
.GetKey());
6490 vAddr
.push_back(addr
);
6491 // receiver rejects addr messages larger than 1000
6492 if (vAddr
.size() >= 1000)
6494 pto
->PushMessage(NetMsgType::ADDR
, vAddr
);
6499 pto
->vAddrToSend
.clear();
6501 pto
->PushMessage(NetMsgType::ADDR
, vAddr
);
6502 // we only send the big addr message once
6503 if (pto
->vAddrToSend
.capacity() > 40)
6504 pto
->vAddrToSend
.shrink_to_fit();
6507 CNodeState
&state
= *State(pto
->GetId());
6508 if (state
.fShouldBan
) {
6509 if (pto
->fWhitelisted
)
6510 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto
->addr
.ToString());
6512 pto
->fDisconnect
= true;
6513 if (pto
->addr
.IsLocal())
6514 LogPrintf("Warning: not banning local peer %s!\n", pto
->addr
.ToString());
6517 connman
.Ban(pto
->addr
, BanReasonNodeMisbehaving
);
6520 state
.fShouldBan
= false;
6523 BOOST_FOREACH(const CBlockReject
& reject
, state
.rejects
)
6524 pto
->PushMessage(NetMsgType::REJECT
, (string
)NetMsgType::BLOCK
, reject
.chRejectCode
, reject
.strRejectReason
, reject
.hashBlock
);
6525 state
.rejects
.clear();
6528 if (pindexBestHeader
== NULL
)
6529 pindexBestHeader
= chainActive
.Tip();
6530 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.
6531 if (!state
.fSyncStarted
&& !pto
->fClient
&& !pto
->fDisconnect
&& !fImporting
&& !fReindex
) {
6532 // Only actively request headers from a single peer, unless we're close to today.
6533 if ((nSyncStarted
== 0 && fFetch
) || pindexBestHeader
->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
6534 state
.fSyncStarted
= true;
6536 const CBlockIndex
*pindexStart
= pindexBestHeader
;
6537 /* If possible, start at the block preceding the currently
6538 best known header. This ensures that we always get a
6539 non-empty list of headers back as long as the peer
6540 is up-to-date. With a non-empty response, we can initialise
6541 the peer's known best block. This wouldn't be possible
6542 if we requested starting at pindexBestHeader and
6543 got back an empty response. */
6544 if (pindexStart
->pprev
)
6545 pindexStart
= pindexStart
->pprev
;
6546 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart
->nHeight
, pto
->id
, pto
->nStartingHeight
);
6547 pto
->PushMessage(NetMsgType::GETHEADERS
, chainActive
.GetLocator(pindexStart
), uint256());
6551 // Resend wallet transactions that haven't gotten in a block yet
6552 // Except during reindex, importing and IBD, when old wallet
6553 // transactions become unconfirmed and spams other nodes.
6554 if (!fReindex
&& !fImporting
&& !IsInitialBlockDownload())
6556 GetMainSignals().Broadcast(nTimeBestReceived
, &connman
);
6560 // Try sending block announcements via headers
6563 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
6564 // list of block hashes we're relaying, and our peer wants
6565 // headers announcements, then find the first header
6566 // not yet known to our peer but would connect, and send.
6567 // If no header would connect, or if we have too many
6568 // blocks, or if the peer doesn't want headers, just
6569 // add all to the inv queue.
6570 LOCK(pto
->cs_inventory
);
6571 vector
<CBlock
> vHeaders
;
6572 bool fRevertToInv
= ((!state
.fPreferHeaders
&&
6573 (!state
.fPreferHeaderAndIDs
|| pto
->vBlockHashesToAnnounce
.size() > 1)) ||
6574 pto
->vBlockHashesToAnnounce
.size() > MAX_BLOCKS_TO_ANNOUNCE
);
6575 CBlockIndex
*pBestIndex
= NULL
; // last header queued for delivery
6576 ProcessBlockAvailability(pto
->id
); // ensure pindexBestKnownBlock is up-to-date
6578 if (!fRevertToInv
) {
6579 bool fFoundStartingHeader
= false;
6580 // Try to find first header that our peer doesn't have, and
6581 // then send all headers past that one. If we come across any
6582 // headers that aren't on chainActive, give up.
6583 BOOST_FOREACH(const uint256
&hash
, pto
->vBlockHashesToAnnounce
) {
6584 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
6585 assert(mi
!= mapBlockIndex
.end());
6586 CBlockIndex
*pindex
= mi
->second
;
6587 if (chainActive
[pindex
->nHeight
] != pindex
) {
6588 // Bail out if we reorged away from this block
6589 fRevertToInv
= true;
6592 if (pBestIndex
!= NULL
&& pindex
->pprev
!= pBestIndex
) {
6593 // This means that the list of blocks to announce don't
6594 // connect to each other.
6595 // This shouldn't really be possible to hit during
6596 // regular operation (because reorgs should take us to
6597 // a chain that has some block not on the prior chain,
6598 // which should be caught by the prior check), but one
6599 // way this could happen is by using invalidateblock /
6600 // reconsiderblock repeatedly on the tip, causing it to
6601 // be added multiple times to vBlockHashesToAnnounce.
6602 // Robustly deal with this rare situation by reverting
6604 fRevertToInv
= true;
6607 pBestIndex
= pindex
;
6608 if (fFoundStartingHeader
) {
6609 // add this to the headers message
6610 vHeaders
.push_back(pindex
->GetBlockHeader());
6611 } else if (PeerHasHeader(&state
, pindex
)) {
6612 continue; // keep looking for the first new block
6613 } else if (pindex
->pprev
== NULL
|| PeerHasHeader(&state
, pindex
->pprev
)) {
6614 // Peer doesn't have this header but they do have the prior one.
6615 // Start sending headers.
6616 fFoundStartingHeader
= true;
6617 vHeaders
.push_back(pindex
->GetBlockHeader());
6619 // Peer doesn't have this header or the prior one -- nothing will
6620 // connect, so bail out.
6621 fRevertToInv
= true;
6626 if (!fRevertToInv
&& !vHeaders
.empty()) {
6627 if (vHeaders
.size() == 1 && state
.fPreferHeaderAndIDs
) {
6628 // We only send up to 1 block as header-and-ids, as otherwise
6629 // probably means we're doing an initial-ish-sync or they're slow
6630 LogPrint("net", "%s sending header-and-ids %s to peer %d\n", __func__
,
6631 vHeaders
.front().GetHash().ToString(), pto
->id
);
6632 //TODO: Shouldn't need to reload block from disk, but requires refactor
6634 assert(ReadBlockFromDisk(block
, pBestIndex
, consensusParams
));
6635 CBlockHeaderAndShortTxIDs
cmpctblock(block
, state
.fWantsCmpctWitness
);
6636 pto
->PushMessageWithFlag(state
.fWantsCmpctWitness
? 0 : SERIALIZE_TRANSACTION_NO_WITNESS
, NetMsgType::CMPCTBLOCK
, cmpctblock
);
6637 state
.pindexBestHeaderSent
= pBestIndex
;
6638 } else if (state
.fPreferHeaders
) {
6639 if (vHeaders
.size() > 1) {
6640 LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__
,
6642 vHeaders
.front().GetHash().ToString(),
6643 vHeaders
.back().GetHash().ToString(), pto
->id
);
6645 LogPrint("net", "%s: sending header %s to peer=%d\n", __func__
,
6646 vHeaders
.front().GetHash().ToString(), pto
->id
);
6648 pto
->PushMessage(NetMsgType::HEADERS
, vHeaders
);
6649 state
.pindexBestHeaderSent
= pBestIndex
;
6651 fRevertToInv
= true;
6654 // If falling back to using an inv, just try to inv the tip.
6655 // The last entry in vBlockHashesToAnnounce was our tip at some point
6657 if (!pto
->vBlockHashesToAnnounce
.empty()) {
6658 const uint256
&hashToAnnounce
= pto
->vBlockHashesToAnnounce
.back();
6659 BlockMap::iterator mi
= mapBlockIndex
.find(hashToAnnounce
);
6660 assert(mi
!= mapBlockIndex
.end());
6661 CBlockIndex
*pindex
= mi
->second
;
6663 // Warn if we're announcing a block that is not on the main chain.
6664 // This should be very rare and could be optimized out.
6665 // Just log for now.
6666 if (chainActive
[pindex
->nHeight
] != pindex
) {
6667 LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
6668 hashToAnnounce
.ToString(), chainActive
.Tip()->GetBlockHash().ToString());
6671 // If the peer's chain has this block, don't inv it back.
6672 if (!PeerHasHeader(&state
, pindex
)) {
6673 pto
->PushInventory(CInv(MSG_BLOCK
, hashToAnnounce
));
6674 LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__
,
6675 pto
->id
, hashToAnnounce
.ToString());
6679 pto
->vBlockHashesToAnnounce
.clear();
6683 // Message: inventory
6687 LOCK(pto
->cs_inventory
);
6688 vInv
.reserve(std::max
<size_t>(pto
->vInventoryBlockToSend
.size(), INVENTORY_BROADCAST_MAX
));
6691 BOOST_FOREACH(const uint256
& hash
, pto
->vInventoryBlockToSend
) {
6692 vInv
.push_back(CInv(MSG_BLOCK
, hash
));
6693 if (vInv
.size() == MAX_INV_SZ
) {
6694 pto
->PushMessage(NetMsgType::INV
, vInv
);
6698 pto
->vInventoryBlockToSend
.clear();
6700 // Check whether periodic sends should happen
6701 bool fSendTrickle
= pto
->fWhitelisted
;
6702 if (pto
->nNextInvSend
< nNow
) {
6703 fSendTrickle
= true;
6704 // Use half the delay for outbound peers, as there is less privacy concern for them.
6705 pto
->nNextInvSend
= PoissonNextSend(nNow
, INVENTORY_BROADCAST_INTERVAL
>> !pto
->fInbound
);
6708 // Time to send but the peer has requested we not relay transactions.
6710 LOCK(pto
->cs_filter
);
6711 if (!pto
->fRelayTxes
) pto
->setInventoryTxToSend
.clear();
6714 // Respond to BIP35 mempool requests
6715 if (fSendTrickle
&& pto
->fSendMempool
) {
6716 auto vtxinfo
= mempool
.infoAll();
6717 pto
->fSendMempool
= false;
6718 CAmount filterrate
= 0;
6720 LOCK(pto
->cs_feeFilter
);
6721 filterrate
= pto
->minFeeFilter
;
6724 LOCK(pto
->cs_filter
);
6726 for (const auto& txinfo
: vtxinfo
) {
6727 const uint256
& hash
= txinfo
.tx
->GetHash();
6728 CInv
inv(MSG_TX
, hash
);
6729 pto
->setInventoryTxToSend
.erase(hash
);
6731 if (txinfo
.feeRate
.GetFeePerK() < filterrate
)
6735 if (!pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
6737 pto
->filterInventoryKnown
.insert(hash
);
6738 vInv
.push_back(inv
);
6739 if (vInv
.size() == MAX_INV_SZ
) {
6740 pto
->PushMessage(NetMsgType::INV
, vInv
);
6744 pto
->timeLastMempoolReq
= GetTime();
6747 // Determine transactions to relay
6749 // Produce a vector with all candidates for sending
6750 vector
<std::set
<uint256
>::iterator
> vInvTx
;
6751 vInvTx
.reserve(pto
->setInventoryTxToSend
.size());
6752 for (std::set
<uint256
>::iterator it
= pto
->setInventoryTxToSend
.begin(); it
!= pto
->setInventoryTxToSend
.end(); it
++) {
6753 vInvTx
.push_back(it
);
6755 CAmount filterrate
= 0;
6757 LOCK(pto
->cs_feeFilter
);
6758 filterrate
= pto
->minFeeFilter
;
6760 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
6761 // A heap is used so that not all items need sorting if only a few are being sent.
6762 CompareInvMempoolOrder
compareInvMempoolOrder(&mempool
);
6763 std::make_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
6764 // No reason to drain out at many times the network's capacity,
6765 // especially since we have many peers and some will draw much shorter delays.
6766 unsigned int nRelayedTransactions
= 0;
6767 LOCK(pto
->cs_filter
);
6768 while (!vInvTx
.empty() && nRelayedTransactions
< INVENTORY_BROADCAST_MAX
) {
6769 // Fetch the top element from the heap
6770 std::pop_heap(vInvTx
.begin(), vInvTx
.end(), compareInvMempoolOrder
);
6771 std::set
<uint256
>::iterator it
= vInvTx
.back();
6774 // Remove it from the to-be-sent set
6775 pto
->setInventoryTxToSend
.erase(it
);
6776 // Check if not in the filter already
6777 if (pto
->filterInventoryKnown
.contains(hash
)) {
6780 // Not in the mempool anymore? don't bother sending it.
6781 auto txinfo
= mempool
.info(hash
);
6785 if (filterrate
&& txinfo
.feeRate
.GetFeePerK() < filterrate
) {
6788 if (pto
->pfilter
&& !pto
->pfilter
->IsRelevantAndUpdate(*txinfo
.tx
)) continue;
6790 vInv
.push_back(CInv(MSG_TX
, hash
));
6791 nRelayedTransactions
++;
6793 // Expire old relay messages
6794 while (!vRelayExpiration
.empty() && vRelayExpiration
.front().first
< nNow
)
6796 mapRelay
.erase(vRelayExpiration
.front().second
);
6797 vRelayExpiration
.pop_front();
6800 auto ret
= mapRelay
.insert(std::make_pair(hash
, std::move(txinfo
.tx
)));
6802 vRelayExpiration
.push_back(std::make_pair(nNow
+ 15 * 60 * 1000000, ret
.first
));
6805 if (vInv
.size() == MAX_INV_SZ
) {
6806 pto
->PushMessage(NetMsgType::INV
, vInv
);
6809 pto
->filterInventoryKnown
.insert(hash
);
6814 pto
->PushMessage(NetMsgType::INV
, vInv
);
6816 // Detect whether we're stalling
6817 nNow
= GetTimeMicros();
6818 if (!pto
->fDisconnect
&& state
.nStallingSince
&& state
.nStallingSince
< nNow
- 1000000 * BLOCK_STALLING_TIMEOUT
) {
6819 // Stalling only triggers when the block download window cannot move. During normal steady state,
6820 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6821 // should only happen during initial block download.
6822 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto
->id
);
6823 pto
->fDisconnect
= true;
6825 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
6826 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
6827 // We compensate for other peers to prevent killing off peers due to our own downstream link
6828 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6829 // to unreasonably increase our timeout.
6830 if (!pto
->fDisconnect
&& state
.vBlocksInFlight
.size() > 0) {
6831 QueuedBlock
&queuedBlock
= state
.vBlocksInFlight
.front();
6832 int nOtherPeersWithValidatedDownloads
= nPeersWithValidatedDownloads
- (state
.nBlocksInFlightValidHeaders
> 0);
6833 if (nNow
> state
.nDownloadingSince
+ consensusParams
.nPowTargetSpacing
* (BLOCK_DOWNLOAD_TIMEOUT_BASE
+ BLOCK_DOWNLOAD_TIMEOUT_PER_PEER
* nOtherPeersWithValidatedDownloads
)) {
6834 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock
.hash
.ToString(), pto
->id
);
6835 pto
->fDisconnect
= true;
6840 // Message: getdata (blocks)
6842 vector
<CInv
> vGetData
;
6843 if (!pto
->fDisconnect
&& !pto
->fClient
&& (fFetch
|| !IsInitialBlockDownload()) && state
.nBlocksInFlight
< MAX_BLOCKS_IN_TRANSIT_PER_PEER
) {
6844 vector
<CBlockIndex
*> vToDownload
;
6845 NodeId staller
= -1;
6846 FindNextBlocksToDownload(pto
->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER
- state
.nBlocksInFlight
, vToDownload
, staller
, consensusParams
);
6847 BOOST_FOREACH(CBlockIndex
*pindex
, vToDownload
) {
6848 uint32_t nFetchFlags
= GetFetchFlags(pto
, pindex
->pprev
, consensusParams
);
6849 vGetData
.push_back(CInv(MSG_BLOCK
| nFetchFlags
, pindex
->GetBlockHash()));
6850 MarkBlockAsInFlight(pto
->GetId(), pindex
->GetBlockHash(), consensusParams
, pindex
);
6851 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex
->GetBlockHash().ToString(),
6852 pindex
->nHeight
, pto
->id
);
6854 if (state
.nBlocksInFlight
== 0 && staller
!= -1) {
6855 if (State(staller
)->nStallingSince
== 0) {
6856 State(staller
)->nStallingSince
= nNow
;
6857 LogPrint("net", "Stall started peer=%d\n", staller
);
6863 // Message: getdata (non-blocks)
6865 while (!pto
->fDisconnect
&& !pto
->mapAskFor
.empty() && (*pto
->mapAskFor
.begin()).first
<= nNow
)
6867 const CInv
& inv
= (*pto
->mapAskFor
.begin()).second
;
6868 if (!AlreadyHave(inv
))
6871 LogPrint("net", "Requesting %s peer=%d\n", inv
.ToString(), pto
->id
);
6872 vGetData
.push_back(inv
);
6873 if (vGetData
.size() >= 1000)
6875 pto
->PushMessage(NetMsgType::GETDATA
, vGetData
);
6879 //If we're not going to ask, don't expect a response.
6880 pto
->setAskFor
.erase(inv
.hash
);
6882 pto
->mapAskFor
.erase(pto
->mapAskFor
.begin());
6884 if (!vGetData
.empty())
6885 pto
->PushMessage(NetMsgType::GETDATA
, vGetData
);
6888 // Message: feefilter
6890 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
6891 if (pto
->nVersion
>= FEEFILTER_VERSION
&& GetBoolArg("-feefilter", DEFAULT_FEEFILTER
) &&
6892 !(pto
->fWhitelisted
&& GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY
))) {
6893 CAmount currentFilter
= mempool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFeePerK();
6894 int64_t timeNow
= GetTimeMicros();
6895 if (timeNow
> pto
->nextSendTimeFeeFilter
) {
6896 CAmount filterToSend
= filterRounder
.round(currentFilter
);
6897 if (filterToSend
!= pto
->lastSentFeeFilter
) {
6898 pto
->PushMessage(NetMsgType::FEEFILTER
, filterToSend
);
6899 pto
->lastSentFeeFilter
= filterToSend
;
6901 pto
->nextSendTimeFeeFilter
= PoissonNextSend(timeNow
, AVG_FEEFILTER_BROADCAST_INTERVAL
);
6903 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
6904 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
6905 else if (timeNow
+ MAX_FEEFILTER_CHANGE_DELAY
* 1000000 < pto
->nextSendTimeFeeFilter
&&
6906 (currentFilter
< 3 * pto
->lastSentFeeFilter
/ 4 || currentFilter
> 4 * pto
->lastSentFeeFilter
/ 3)) {
6907 pto
->nextSendTimeFeeFilter
= timeNow
+ GetRandInt(MAX_FEEFILTER_CHANGE_DELAY
) * 1000000;
6914 std::string
CBlockFileInfo::ToString() const {
6915 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks
, nSize
, nHeightFirst
, nHeightLast
, DateTimeStrFormat("%Y-%m-%d", nTimeFirst
), DateTimeStrFormat("%Y-%m-%d", nTimeLast
));
6918 ThresholdState
VersionBitsTipState(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
6921 return VersionBitsState(chainActive
.Tip(), params
, pos
, versionbitscache
);
6924 int VersionBitsTipStateSinceHeight(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
6927 return VersionBitsStateSinceHeight(chainActive
.Tip(), params
, pos
, versionbitscache
);
6936 BlockMap::iterator it1
= mapBlockIndex
.begin();
6937 for (; it1
!= mapBlockIndex
.end(); it1
++)
6938 delete (*it1
).second
;
6939 mapBlockIndex
.clear();
6941 // orphan transactions
6942 mapOrphanTransactions
.clear();
6943 mapOrphanTransactionsByPrev
.clear();
6945 } instance_of_cmaincleanup
;