1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
12 #include "arith_uint256.h"
13 #include "chainparams.h"
14 #include "checkpoints.h"
15 #include "checkqueue.h"
16 #include "consensus/validation.h"
18 #include "merkleblock.h"
23 #include "txmempool.h"
24 #include "ui_interface.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
32 #include <boost/algorithm/string/replace.hpp>
33 #include <boost/filesystem.hpp>
34 #include <boost/filesystem/fstream.hpp>
35 #include <boost/math/distributions/poisson.hpp>
36 #include <boost/thread.hpp>
37 #include <boost/static_assert.hpp>
42 # error "Zcash cannot be compiled without assertions."
50 CCriticalSection cs_main;
52 BlockMap mapBlockIndex;
54 CBlockIndex *pindexBestHeader = NULL;
55 int64_t nTimeBestReceived = 0;
56 CWaitableCriticalSection csBestBlock;
57 CConditionVariable cvBlockChange;
58 int nScriptCheckThreads = 0;
59 bool fImporting = false;
60 bool fReindex = false;
61 bool fTxIndex = false;
62 bool fHavePruned = false;
63 bool fPruneMode = false;
64 bool fIsBareMultisigStd = true;
65 bool fCheckBlockIndex = false;
66 bool fCheckpointsEnabled = true;
67 bool fCoinbaseEnforcedProtectionEnabled = true;
68 size_t nCoinCacheUsage = 5000 * 300;
69 uint64_t nPruneTarget = 0;
70 bool fAlerts = DEFAULT_ALERTS;
72 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
73 CFeeRate minRelayTxFee = CFeeRate(5000);
75 CTxMemPool mempool(::minRelayTxFee);
81 map<uint256, COrphanTx> mapOrphanTransactions;
82 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
83 void EraseOrphansFor(NodeId peer);
86 * Returns true if there are nRequired or more blocks of minVersion or above
87 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
89 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
90 static void CheckBlockIndex();
92 /** Constant stuff for coinbase transactions we create: */
93 CScript COINBASE_FLAGS;
95 const string strMessageMagic = "Komodo Signed Message:\n";
100 struct CBlockIndexWorkComparator
102 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
103 // First sort by most total work, ...
104 if (pa->nChainWork > pb->nChainWork) return false;
105 if (pa->nChainWork < pb->nChainWork) return true;
107 // ... then by earliest time received, ...
108 if (pa->nSequenceId < pb->nSequenceId) return false;
109 if (pa->nSequenceId > pb->nSequenceId) return true;
111 // Use pointer address as tie breaker (should only happen with blocks
112 // loaded from disk, as those all have id 0).
113 if (pa < pb) return false;
114 if (pa > pb) return true;
121 CBlockIndex *pindexBestInvalid;
124 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
125 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
126 * missing the data for the block.
128 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
129 /** Number of nodes with fSyncStarted. */
130 int nSyncStarted = 0;
131 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
132 * Pruned nodes may have entries where B is missing data.
134 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
136 CCriticalSection cs_LastBlockFile;
137 std::vector<CBlockFileInfo> vinfoBlockFile;
138 int nLastBlockFile = 0;
139 /** Global flag to indicate we should check to see if there are
140 * block/undo files that should be deleted. Set on startup
141 * or if we allocate more file space when we're in prune mode
143 bool fCheckForPruning = false;
146 * Every received block is assigned a unique and increasing identifier, so we
147 * know which one to give priority in case of a fork.
149 CCriticalSection cs_nBlockSequenceId;
150 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
151 uint32_t nBlockSequenceId = 1;
154 * Sources of received blocks, saved to be able to send them reject
155 * messages or ban them when processing happens afterwards. Protected by
158 map<uint256, NodeId> mapBlockSource;
161 * Filter for transactions that were recently rejected by
162 * AcceptToMemoryPool. These are not rerequested until the chain tip
163 * changes, at which point the entire filter is reset. Protected by
166 * Without this filter we'd be re-requesting txs from each of our peers,
167 * increasing bandwidth consumption considerably. For instance, with 100
168 * peers, half of which relay a tx we don't accept, that might be a 50x
169 * bandwidth increase. A flooding attacker attempting to roll-over the
170 * filter using minimum-sized, 60byte, transactions might manage to send
171 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
172 * two minute window to send invs to us.
174 * Decreasing the false positive rate is fairly cheap, so we pick one in a
175 * million to make it highly unlikely for users to have issues with this
180 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
181 uint256 hashRecentRejectsChainTip;
183 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
186 CBlockIndex *pindex; //! Optional.
187 int64_t nTime; //! Time of "getdata" request in microseconds.
188 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
189 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
191 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
193 /** Number of blocks in flight with validated headers. */
194 int nQueuedValidatedHeaders = 0;
196 /** Number of preferable block download peers. */
197 int nPreferredDownload = 0;
199 /** Dirty block index entries. */
200 set<CBlockIndex*> setDirtyBlockIndex;
202 /** Dirty block file entries. */
203 set<int> setDirtyFileInfo;
206 //////////////////////////////////////////////////////////////////////////////
208 // Registration of network node signals.
213 struct CBlockReject {
214 unsigned char chRejectCode;
215 string strRejectReason;
220 * Maintain validation-specific state about nodes, protected by cs_main, instead
221 * by CNode's own locks. This simplifies asynchronous operation, where
222 * processing of incoming data is done after the ProcessMessage call returns,
223 * and we're no longer holding the node's locks.
226 //! The peer's address
228 //! Whether we have a fully established connection.
229 bool fCurrentlyConnected;
230 //! Accumulated misbehaviour score for this peer.
232 //! Whether this peer should be disconnected and banned (unless whitelisted).
234 //! String name of this peer (debugging/logging purposes).
236 //! List of asynchronously-determined block rejections to notify this peer about.
237 std::vector<CBlockReject> rejects;
238 //! The best known block we know this peer has announced.
239 CBlockIndex *pindexBestKnownBlock;
240 //! The hash of the last unknown block this peer has announced.
241 uint256 hashLastUnknownBlock;
242 //! The last full block we both have.
243 CBlockIndex *pindexLastCommonBlock;
244 //! Whether we've started headers synchronization with this peer.
246 //! Since when we're stalling block download progress (in microseconds), or 0.
247 int64_t nStallingSince;
248 list<QueuedBlock> vBlocksInFlight;
250 int nBlocksInFlightValidHeaders;
251 //! Whether we consider this a preferred download peer.
252 bool fPreferredDownload;
255 fCurrentlyConnected = false;
258 pindexBestKnownBlock = NULL;
259 hashLastUnknownBlock.SetNull();
260 pindexLastCommonBlock = NULL;
261 fSyncStarted = false;
264 nBlocksInFlightValidHeaders = 0;
265 fPreferredDownload = false;
269 /** Map maintaining per-node state. Requires cs_main. */
270 map<NodeId, CNodeState> mapNodeState;
273 CNodeState *State(NodeId pnode) {
274 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
275 if (it == mapNodeState.end())
283 return chainActive.Height();
286 void UpdatePreferredDownload(CNode* node, CNodeState* state)
288 nPreferredDownload -= state->fPreferredDownload;
290 // Whether this node should be marked as a preferred download node.
291 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
293 nPreferredDownload += state->fPreferredDownload;
296 // Returns time at which to timeout block request (nTime in microseconds)
297 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
299 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
302 void InitializeNode(NodeId nodeid, const CNode *pnode) {
304 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
305 state.name = pnode->addrName;
306 state.address = pnode->addr;
309 void FinalizeNode(NodeId nodeid) {
311 CNodeState *state = State(nodeid);
313 if (state->fSyncStarted)
316 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
317 AddressCurrentlyConnected(state->address);
320 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
321 mapBlocksInFlight.erase(entry.hash);
322 EraseOrphansFor(nodeid);
323 nPreferredDownload -= state->fPreferredDownload;
325 mapNodeState.erase(nodeid);
329 // Returns a bool indicating whether we requested this block.
330 bool MarkBlockAsReceived(const uint256& hash) {
331 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
332 if (itInFlight != mapBlocksInFlight.end()) {
333 CNodeState *state = State(itInFlight->second.first);
334 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
335 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
336 state->vBlocksInFlight.erase(itInFlight->second.second);
337 state->nBlocksInFlight--;
338 state->nStallingSince = 0;
339 mapBlocksInFlight.erase(itInFlight);
346 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
347 CNodeState *state = State(nodeid);
348 assert(state != NULL);
350 // Make sure it's not listed somewhere already.
351 MarkBlockAsReceived(hash);
353 int64_t nNow = GetTimeMicros();
354 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
355 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
356 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
357 state->nBlocksInFlight++;
358 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
359 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
362 /** Check whether the last unknown block a peer advertized is not yet known. */
363 void ProcessBlockAvailability(NodeId nodeid) {
364 CNodeState *state = State(nodeid);
365 assert(state != NULL);
367 if (!state->hashLastUnknownBlock.IsNull()) {
368 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
369 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
370 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
371 state->pindexBestKnownBlock = itOld->second;
372 state->hashLastUnknownBlock.SetNull();
377 /** Update tracking information about which blocks a peer is assumed to have. */
378 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
379 CNodeState *state = State(nodeid);
380 assert(state != NULL);
382 ProcessBlockAvailability(nodeid);
384 BlockMap::iterator it = mapBlockIndex.find(hash);
385 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
386 // An actually better block was announced.
387 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
388 state->pindexBestKnownBlock = it->second;
390 // An unknown block was announced; just assume that the latest one is the best one.
391 state->hashLastUnknownBlock = hash;
395 /** Find the last common ancestor two blocks have.
396 * Both pa and pb must be non-NULL. */
397 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
398 if (pa->nHeight > pb->nHeight) {
399 pa = pa->GetAncestor(pb->nHeight);
400 } else if (pb->nHeight > pa->nHeight) {
401 pb = pb->GetAncestor(pa->nHeight);
404 while (pa != pb && pa && pb) {
409 // Eventually all chain branches meet at the genesis block.
414 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
415 * at most count entries. */
416 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
420 vBlocks.reserve(vBlocks.size() + count);
421 CNodeState *state = State(nodeid);
422 assert(state != NULL);
424 // Make sure pindexBestKnownBlock is up to date, we'll need it.
425 ProcessBlockAvailability(nodeid);
427 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
428 // This peer has nothing interesting.
432 if (state->pindexLastCommonBlock == NULL) {
433 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
434 // Guessing wrong in either direction is not a problem.
435 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
438 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
439 // of its current tip anymore. Go back enough to fix that.
440 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
441 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
444 std::vector<CBlockIndex*> vToFetch;
445 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
446 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
447 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
448 // download that next block if the window were 1 larger.
449 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
450 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
451 NodeId waitingfor = -1;
452 while (pindexWalk->nHeight < nMaxHeight) {
453 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
454 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
455 // as iterating over ~100 CBlockIndex* entries anyway.
456 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
457 vToFetch.resize(nToFetch);
458 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
459 vToFetch[nToFetch - 1] = pindexWalk;
460 for (unsigned int i = nToFetch - 1; i > 0; i--) {
461 vToFetch[i - 1] = vToFetch[i]->pprev;
464 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
465 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
466 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
467 // already part of our chain (and therefore don't need it even if pruned).
468 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
469 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
470 // We consider the chain that this peer is on invalid.
473 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
474 if (pindex->nChainTx)
475 state->pindexLastCommonBlock = pindex;
476 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
477 // The block is not already downloaded, and not yet in flight.
478 if (pindex->nHeight > nWindowEnd) {
479 // We reached the end of the window.
480 if (vBlocks.size() == 0 && waitingfor != nodeid) {
481 // We aren't able to fetch anything, but we would be if the download window was one larger.
482 nodeStaller = waitingfor;
486 vBlocks.push_back(pindex);
487 if (vBlocks.size() == count) {
490 } else if (waitingfor == -1) {
491 // This is the first already-in-flight block.
492 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
500 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
502 CNodeState *state = State(nodeid);
505 stats.nMisbehavior = state->nMisbehavior;
506 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
507 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
508 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
510 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
515 void RegisterNodeSignals(CNodeSignals& nodeSignals)
517 nodeSignals.GetHeight.connect(&GetHeight);
518 nodeSignals.ProcessMessages.connect(&ProcessMessages);
519 nodeSignals.SendMessages.connect(&SendMessages);
520 nodeSignals.InitializeNode.connect(&InitializeNode);
521 nodeSignals.FinalizeNode.connect(&FinalizeNode);
524 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
526 nodeSignals.GetHeight.disconnect(&GetHeight);
527 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
528 nodeSignals.SendMessages.disconnect(&SendMessages);
529 nodeSignals.InitializeNode.disconnect(&InitializeNode);
530 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
533 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
535 // Find the first block the caller has in the main chain
536 BOOST_FOREACH(const uint256& hash, locator.vHave) {
537 BlockMap::iterator mi = mapBlockIndex.find(hash);
538 if (mi != mapBlockIndex.end())
540 CBlockIndex* pindex = (*mi).second;
541 if (chain.Contains(pindex))
545 return chain.Genesis();
548 CCoinsViewCache *pcoinsTip = NULL;
549 CBlockTreeDB *pblocktree = NULL;
552 int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY;
553 std::string NOTARY_PUBKEY;
554 uint8_t NOTARY_PUBKEY33[33];
556 #define KOMODO_TESTNET_EXPIRATION 60000
557 //#define KOMODO_ENABLE_INTEREST enabling this is a hardfork
558 #define KOMODO_SOURCE "KMD"
563 //////////////////////////////////////////////////////////////////////////////
565 // mapOrphanTransactions
568 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
570 uint256 hash = tx.GetHash();
571 if (mapOrphanTransactions.count(hash))
574 // Ignore big transactions, to avoid a
575 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
576 // large transaction with a missing parent then we assume
577 // it will rebroadcast it later, after the parent transaction(s)
578 // have been mined or received.
579 // 10,000 orphans, each of which is at most 5,000 bytes big is
580 // at most 500 megabytes of orphans:
581 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
584 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
588 mapOrphanTransactions[hash].tx = tx;
589 mapOrphanTransactions[hash].fromPeer = peer;
590 BOOST_FOREACH(const CTxIn& txin, tx.vin)
591 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
593 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
594 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
598 void static EraseOrphanTx(uint256 hash)
600 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
601 if (it == mapOrphanTransactions.end())
603 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
605 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
606 if (itPrev == mapOrphanTransactionsByPrev.end())
608 itPrev->second.erase(hash);
609 if (itPrev->second.empty())
610 mapOrphanTransactionsByPrev.erase(itPrev);
612 mapOrphanTransactions.erase(it);
615 void EraseOrphansFor(NodeId peer)
618 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
619 while (iter != mapOrphanTransactions.end())
621 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
622 if (maybeErase->second.fromPeer == peer)
624 EraseOrphanTx(maybeErase->second.tx.GetHash());
628 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
632 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
634 unsigned int nEvicted = 0;
635 while (mapOrphanTransactions.size() > nMaxOrphans)
637 // Evict a random orphan:
638 uint256 randomhash = GetRandHash();
639 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
640 if (it == mapOrphanTransactions.end())
641 it = mapOrphanTransactions.begin();
642 EraseOrphanTx(it->first);
654 bool IsStandardTx(const CTransaction& tx, string& reason)
656 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
661 BOOST_FOREACH(const CTxIn& txin, tx.vin)
663 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
664 // keys. (remember the 520 byte limit on redeemScript size) That works
665 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
666 // bytes of scriptSig, which we round off to 1650 bytes for some minor
667 // future-proofing. That's also enough to spend a 20-of-20
668 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
669 // considered standard)
670 if (txin.scriptSig.size() > 1650) {
671 reason = "scriptsig-size";
674 if (!txin.scriptSig.IsPushOnly()) {
675 reason = "scriptsig-not-pushonly";
680 unsigned int v=0,nDataOut = 0;
681 txnouttype whichType;
682 BOOST_FOREACH(const CTxOut& txout, tx.vout)
684 if (!::IsStandard(txout.scriptPubKey, whichType)) {
685 reason = "scriptpubkey";
686 fprintf(stderr,"vout.%d nDataout.%d\n",v,nDataOut);
690 if (whichType == TX_NULL_DATA)
692 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
693 reason = "bare-multisig";
695 } else if (txout.IsDust(::minRelayTxFee)) {
702 // only one OP_RETURN txout is permitted
704 reason = "multi-op-return";
711 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
713 if (tx.nLockTime == 0)
715 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
717 if ( (int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime < nBlockTime-3600 )
719 fprintf(stderr,"IsFinalTx reject locktime %u vs nBlockTime %u\n",tx.nLockTime,(uint32_t)nBlockTime);
720 return(false); // need to prevent pastdating tx
722 BOOST_FOREACH(const CTxIn& txin, tx.vin)
724 if ( txin.nSequence == 0xfffffffe && (((int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime > nBlockTime) || ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime > nBlockHeight)) )
728 else if (!txin.IsFinal())
730 printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime);
737 bool CheckFinalTx(const CTransaction &tx, int flags)
739 AssertLockHeld(cs_main);
741 // By convention a negative value for flags indicates that the
742 // current network-enforced consensus rules should be used. In
743 // a future soft-fork scenario that would mean checking which
744 // rules would be enforced for the next block and setting the
745 // appropriate flags. At the present time no soft-forks are
746 // scheduled, so no flags are set.
747 flags = std::max(flags, 0);
749 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
750 // nLockTime because when IsFinalTx() is called within
751 // CBlock::AcceptBlock(), the height of the block *being*
752 // evaluated is what is used. Thus if we want to know if a
753 // transaction can be part of the *next* block, we need to call
754 // IsFinalTx() with one more than chainActive.Height().
755 const int nBlockHeight = chainActive.Height() + 1;
757 // Timestamps on the other hand don't get any special treatment,
758 // because we can't know what timestamp the next block will have,
759 // and there aren't timestamp applications where it matters.
760 // However this changes once median past time-locks are enforced:
761 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
762 ? chainActive.Tip()->GetMedianTimePast()
765 return IsFinalTx(tx, nBlockHeight, nBlockTime);
769 * Check transaction inputs to mitigate two
770 * potential denial-of-service attacks:
772 * 1. scriptSigs with extra data stuffed into them,
773 * not consumed by scriptPubKey (or P2SH script)
774 * 2. P2SH scripts with a crazy number of expensive
775 * CHECKSIG/CHECKMULTISIG operations
777 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
780 return true; // Coinbases don't use vin normally
782 for (unsigned int i = 0; i < tx.vin.size(); i++)
784 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
786 vector<vector<unsigned char> > vSolutions;
787 txnouttype whichType;
788 // get the scriptPubKey corresponding to this input:
789 const CScript& prevScript = prev.scriptPubKey;
790 if (!Solver(prevScript, whichType, vSolutions))
792 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
793 if (nArgsExpected < 0)
796 // Transactions with extra stuff in their scriptSigs are
797 // non-standard. Note that this EvalScript() call will
798 // be quick, because if there are any operations
799 // beside "push data" in the scriptSig
800 // IsStandardTx() will have already returned false
801 // and this method isn't called.
802 vector<vector<unsigned char> > stack;
803 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
806 if (whichType == TX_SCRIPTHASH)
810 CScript subscript(stack.back().begin(), stack.back().end());
811 vector<vector<unsigned char> > vSolutions2;
812 txnouttype whichType2;
813 if (Solver(subscript, whichType2, vSolutions2))
815 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
818 nArgsExpected += tmpExpected;
822 // Any other Script with less than 15 sigops OK:
823 unsigned int sigops = subscript.GetSigOpCount(true);
824 // ... extra data left on the stack after execution is OK, too:
825 return (sigops <= MAX_P2SH_SIGOPS);
829 if (stack.size() != (unsigned int)nArgsExpected)
836 unsigned int GetLegacySigOpCount(const CTransaction& tx)
838 unsigned int nSigOps = 0;
839 BOOST_FOREACH(const CTxIn& txin, tx.vin)
841 nSigOps += txin.scriptSig.GetSigOpCount(false);
843 BOOST_FOREACH(const CTxOut& txout, tx.vout)
845 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
850 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
855 unsigned int nSigOps = 0;
856 for (unsigned int i = 0; i < tx.vin.size(); i++)
858 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
859 if (prevout.scriptPubKey.IsPayToScriptHash())
860 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
865 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
867 // Don't count coinbase transactions because mining skews the count
868 if (!tx.IsCoinBase()) {
869 transactionsValidated.increment();
872 if (!CheckTransactionWithoutProofVerification(tx, state)) {
875 // Ensure that zk-SNARKs verify
876 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
877 if (!joinsplit.Verify(*pzcashParams, tx.joinSplitPubKey)) {
878 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
879 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
886 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
888 // Basic checks that don't depend on any context
890 // Check transaction version
891 if (tx.nVersion < MIN_TX_VERSION) {
892 return state.DoS(100, error("CheckTransaction(): version too low"),
893 REJECT_INVALID, "bad-txns-version-too-low");
896 // Transactions can contain empty `vin` and `vout` so long as
897 // `vjoinsplit` is non-empty.
898 if (tx.vin.empty() && tx.vjoinsplit.empty())
899 return state.DoS(10, error("CheckTransaction(): vin empty"),
900 REJECT_INVALID, "bad-txns-vin-empty");
901 if (tx.vout.empty() && tx.vjoinsplit.empty())
902 return state.DoS(10, error("CheckTransaction(): vout empty"),
903 REJECT_INVALID, "bad-txns-vout-empty");
906 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
907 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
908 return state.DoS(100, error("CheckTransaction(): size limits failed"),
909 REJECT_INVALID, "bad-txns-oversize");
911 // Check for negative or overflow output values
912 CAmount nValueOut = 0;
913 BOOST_FOREACH(const CTxOut& txout, tx.vout)
915 if (txout.nValue < 0)
916 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
917 REJECT_INVALID, "bad-txns-vout-negative");
918 if (txout.nValue > MAX_MONEY)
919 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
920 REJECT_INVALID, "bad-txns-vout-toolarge");
921 nValueOut += txout.nValue;
922 if (!MoneyRange(nValueOut))
923 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
924 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
927 // Ensure that joinsplit values are well-formed
928 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
930 if (joinsplit.vpub_old < 0) {
931 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
932 REJECT_INVALID, "bad-txns-vpub_old-negative");
935 if (joinsplit.vpub_new < 0) {
936 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
937 REJECT_INVALID, "bad-txns-vpub_new-negative");
940 if (joinsplit.vpub_old > MAX_MONEY) {
941 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
942 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
945 if (joinsplit.vpub_new > MAX_MONEY) {
946 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
947 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
950 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
951 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
952 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
955 nValueOut += joinsplit.vpub_old;
956 if (!MoneyRange(nValueOut)) {
957 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
958 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
962 // Ensure input values do not exceed MAX_MONEY
963 // We have not resolved the txin values at this stage,
964 // but we do know what the joinsplits claim to add
965 // to the value pool.
967 CAmount nValueIn = 0;
968 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
970 nValueIn += it->vpub_new;
972 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
973 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
974 REJECT_INVALID, "bad-txns-txintotal-toolarge");
980 // Check for duplicate inputs
981 set<COutPoint> vInOutPoints;
982 BOOST_FOREACH(const CTxIn& txin, tx.vin)
984 if (vInOutPoints.count(txin.prevout))
985 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
986 REJECT_INVALID, "bad-txns-inputs-duplicate");
987 vInOutPoints.insert(txin.prevout);
990 // Check for duplicate joinsplit nullifiers in this transaction
991 set<uint256> vJoinSplitNullifiers;
992 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
994 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
996 if (vJoinSplitNullifiers.count(nf))
997 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
998 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1000 vJoinSplitNullifiers.insert(nf);
1004 if (tx.IsCoinBase())
1006 // There should be no joinsplits in a coinbase transaction
1007 if (tx.vjoinsplit.size() > 0)
1008 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1009 REJECT_INVALID, "bad-cb-has-joinsplits");
1011 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1012 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1013 REJECT_INVALID, "bad-cb-length");
1017 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1018 if (txin.prevout.IsNull())
1019 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1020 REJECT_INVALID, "bad-txns-prevout-null");
1022 if (tx.vjoinsplit.size() > 0) {
1023 // Empty output script.
1025 uint256 dataToBeSigned;
1027 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1028 } catch (std::logic_error ex) {
1029 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1030 REJECT_INVALID, "error-computing-signature-hash");
1033 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1035 // We rely on libsodium to check that the signature is canonical.
1036 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1037 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1038 dataToBeSigned.begin(), 32,
1039 tx.joinSplitPubKey.begin()
1041 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1042 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1050 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1054 uint256 hash = tx.GetHash();
1055 double dPriorityDelta = 0;
1056 CAmount nFeeDelta = 0;
1057 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1058 if (dPriorityDelta > 0 || nFeeDelta > 0)
1062 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1066 // There is a free transaction area in blocks created by most miners,
1067 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1068 // to be considered to fall into this category. We don't want to encourage sending
1069 // multiple transactions instead of one big transaction to avoid fees.
1070 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1074 if (!MoneyRange(nMinFee))
1075 nMinFee = MAX_MONEY;
1080 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
1082 AssertLockHeld(cs_main);
1083 if (pfMissingInputs)
1084 *pfMissingInputs = false;
1085 if (!CheckTransaction(tx, state))
1087 fprintf(stderr,"AcceptToMemoryPool CheckTransaction failed\n");
1088 return error("AcceptToMemoryPool: CheckTransaction failed");
1090 // Coinbase is only valid in a block, not as a loose transaction
1091 if (tx.IsCoinBase())
1093 fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
1094 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
1096 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1098 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1100 fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str());
1101 return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
1103 // Only accept nLockTime-using transactions that can be mined in the next
1104 // block; we don't want our mempool filled up with transactions that can't
1106 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1108 fprintf(stderr,"AcceptToMemoryPool non-final\n");
1109 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1111 // is it already in the memory pool?
1112 uint256 hash = tx.GetHash();
1113 if (pool.exists(hash))
1115 fprintf(stderr,"already in mempool\n");
1119 // Check for conflicts with in-memory transactions
1121 LOCK(pool.cs); // protect pool.mapNextTx
1122 for (unsigned int i = 0; i < tx.vin.size(); i++)
1124 COutPoint outpoint = tx.vin[i].prevout;
1125 if (pool.mapNextTx.count(outpoint))
1127 // Disable replacement feature for now
1128 fprintf(stderr,"Disable replacement feature for now\n");
1132 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1133 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1134 if (pool.mapNullifiers.count(nf))
1136 fprintf(stderr,"pool.mapNullifiers.count\n");
1145 CCoinsViewCache view(&dummy);
1147 CAmount nValueIn = 0;
1150 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1151 view.SetBackend(viewMemPool);
1153 // do we already have it?
1154 if (view.HaveCoins(hash))
1156 fprintf(stderr,"view.HaveCoins(hash) error\n");
1160 // do all inputs exist?
1161 // Note that this does not check for the presence of actual outputs (see the next check for that),
1162 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1163 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1164 if (!view.HaveCoins(txin.prevout.hash)) {
1165 if (pfMissingInputs)
1166 *pfMissingInputs = true;
1167 //fprintf(stderr,"missing inputs\n");
1172 // are the actual inputs available?
1173 if (!view.HaveInputs(tx))
1174 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1175 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1177 // are the joinsplit's requirements met?
1178 if (!view.HaveJoinSplitRequirements(tx))
1179 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1180 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1182 // Bring the best block into scope
1183 view.GetBestBlock();
1185 nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
1187 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1188 view.SetBackend(dummy);
1191 // Check for non-standard pay-to-script-hash in inputs
1192 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1193 return error("AcceptToMemoryPool: nonstandard transaction input");
1195 // Check that the transaction doesn't have an excessive number of
1196 // sigops, making it impossible to mine. Since the coinbase transaction
1197 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1198 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1199 // merely non-standard transaction.
1200 unsigned int nSigOps = GetLegacySigOpCount(tx);
1201 nSigOps += GetP2SHSigOpCount(tx, view);
1202 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1203 return state.DoS(0, error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1204 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1205 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1207 CAmount nValueOut = tx.GetValueOut();
1208 CAmount nFees = nValueIn-nValueOut;
1209 double dPriority = view.GetPriority(tx, chainActive.Height());
1211 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1212 unsigned int nSize = entry.GetTxSize();
1214 // Don't accept it if it can't get into a block
1215 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1216 if (fLimitFree && nFees < txMinFee)
1217 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1218 hash.ToString(), nFees, txMinFee),
1219 REJECT_INSUFFICIENTFEE, "insufficient fee");
1221 // Require that free transactions have sufficient priority to be mined in the next block.
1222 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1223 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1226 // Continuously rate-limit free (really, very-low-fee) transactions
1227 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1228 // be annoying or make others' transactions take longer to confirm.
1229 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1231 static CCriticalSection csFreeLimiter;
1232 static double dFreeCount;
1233 static int64_t nLastTime;
1234 int64_t nNow = GetTime();
1236 LOCK(csFreeLimiter);
1238 // Use an exponentially decaying ~10-minute window:
1239 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1241 // -limitfreerelay unit is thousand-bytes-per-minute
1242 // At default rate it would take over a month to fill 1GB
1243 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1244 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1245 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1246 dFreeCount += nSize;
1249 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1250 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1251 hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1253 // Check against previous transactions
1254 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1255 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1257 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1260 // Check again against just the consensus-critical mandatory script
1261 // verification flags, in case of bugs in the standard flags that cause
1262 // transactions to pass as valid when they're actually invalid. For
1263 // instance the STRICTENC flag was incorrectly allowing certain
1264 // CHECKSIG NOT scripts to pass, even though they were invalid.
1266 // There is a similar check in CreateNewBlock() to prevent creating
1267 // invalid blocks, however allowing such transactions into the mempool
1268 // can be exploited as a DoS attack.
1269 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1271 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1274 // Store transaction in memory
1275 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1278 SyncWithWallets(tx, NULL);
1283 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1284 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1286 CBlockIndex *pindexSlow = NULL;
1290 if (mempool.lookup(hash, txOut))
1297 if (pblocktree->ReadTxIndex(hash, postx)) {
1298 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1300 return error("%s: OpenBlockFile failed", __func__);
1301 CBlockHeader header;
1304 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1306 } catch (const std::exception& e) {
1307 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1309 hashBlock = header.GetHash();
1310 if (txOut.GetHash() != hash)
1311 return error("%s: txid mismatch", __func__);
1316 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1319 CCoinsViewCache &view = *pcoinsTip;
1320 const CCoins* coins = view.AccessCoins(hash);
1322 nHeight = coins->nHeight;
1325 pindexSlow = chainActive[nHeight];
1330 if (ReadBlockFromDisk(block, pindexSlow)) {
1331 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1332 if (tx.GetHash() == hash) {
1334 hashBlock = pindexSlow->GetBlockHash();
1344 /*char *komodo_getspendscript(uint256 hash,int32_t n)
1346 CTransaction tx; uint256 hashBlock;
1347 if ( !GetTransaction(hash,tx,hashBlock,true) )
1349 printf("null GetTransaction\n");
1352 if ( n >= 0 && n < tx.vout.size() )
1353 return((char *)tx.vout[n].scriptPubKey.ToString().c_str());
1354 else printf("getspendscript illegal n.%d\n",n);
1359 //////////////////////////////////////////////////////////////////////////////
1361 // CBlock and CBlockIndex
1364 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1366 // Open history file to append
1367 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1368 if (fileout.IsNull())
1369 return error("WriteBlockToDisk: OpenBlockFile failed");
1371 // Write index header
1372 unsigned int nSize = fileout.GetSerializeSize(block);
1373 fileout << FLATDATA(messageStart) << nSize;
1376 long fileOutPos = ftell(fileout.Get());
1378 return error("WriteBlockToDisk: ftell failed");
1379 pos.nPos = (unsigned int)fileOutPos;
1385 bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos)
1387 uint8_t pubkey33[33];
1390 // Open history file to read
1391 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1392 if (filein.IsNull())
1394 //fprintf(stderr,"readblockfromdisk err A\n");
1395 return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1402 catch (const std::exception& e) {
1403 fprintf(stderr,"readblockfromdisk err B\n");
1404 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1407 komodo_block2pubkey33(pubkey33,block);
1408 if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus())))
1409 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1413 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1415 if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos()))
1417 if (block.GetHash() != pindex->GetBlockHash())
1418 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1419 pindex->ToString(), pindex->GetBlockPos().ToString());
1423 uint64_t komodo_moneysupply(int32_t height);
1425 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1427 CAmount nSubsidy = 3 * COIN;
1429 return(100000000 * COIN); // ICO allocation
1430 else if ( komodo_moneysupply(nHeight) < MAX_MONEY )
1434 // Mining slow start
1435 // The subsidy is ramped up linearly, skipping the middle payout of
1436 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1437 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1438 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1439 nSubsidy *= nHeight;
1441 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1442 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1443 nSubsidy *= (nHeight+1);
1447 assert(nHeight > consensusParams.SubsidySlowStartShift());
1448 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/
1449 // Force block reward to zero when right shift is undefined.
1450 //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1451 //if (halvings >= 64)
1454 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1455 //nSubsidy >>= halvings;
1459 bool IsInitialBlockDownload()
1461 const CChainParams& chainParams = Params();
1463 if (fImporting || fReindex)
1465 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1467 static bool lockIBDState = false;
1470 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1471 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1473 lockIBDState = true;
1477 bool fLargeWorkForkFound = false;
1478 bool fLargeWorkInvalidChainFound = false;
1479 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1481 void CheckForkWarningConditions()
1483 AssertLockHeld(cs_main);
1484 // Before we get past initial download, we cannot reliably alert about forks
1485 // (we assume we don't get stuck on a fork before the last checkpoint)
1486 if (IsInitialBlockDownload())
1489 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1490 // of our head, drop it
1491 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1492 pindexBestForkTip = NULL;
1494 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1496 if (!fLargeWorkForkFound && pindexBestForkBase)
1498 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1499 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1500 CAlert::Notify(warning, true);
1502 if (pindexBestForkTip && pindexBestForkBase)
1504 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__,
1505 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1506 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1507 fLargeWorkForkFound = true;
1511 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1512 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1513 CAlert::Notify(warning, true);
1514 fLargeWorkInvalidChainFound = true;
1519 fLargeWorkForkFound = false;
1520 fLargeWorkInvalidChainFound = false;
1524 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1526 AssertLockHeld(cs_main);
1527 // If we are on a fork that is sufficiently large, set a warning flag
1528 CBlockIndex* pfork = pindexNewForkTip;
1529 CBlockIndex* plonger = chainActive.Tip();
1530 while (pfork && pfork != plonger)
1532 while (plonger && plonger->nHeight > pfork->nHeight)
1533 plonger = plonger->pprev;
1534 if (pfork == plonger)
1536 pfork = pfork->pprev;
1539 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1540 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1541 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1542 // hash rate operating on the fork.
1543 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1544 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1545 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1546 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1547 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1548 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1550 pindexBestForkTip = pindexNewForkTip;
1551 pindexBestForkBase = pfork;
1554 CheckForkWarningConditions();
1557 // Requires cs_main.
1558 void Misbehaving(NodeId pnode, int howmuch)
1563 CNodeState *state = State(pnode);
1567 state->nMisbehavior += howmuch;
1568 int banscore = GetArg("-banscore", 100);
1569 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1571 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1572 state->fShouldBan = true;
1574 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1577 void static InvalidChainFound(CBlockIndex* pindexNew)
1579 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1580 pindexBestInvalid = pindexNew;
1582 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1583 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1584 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1585 pindexNew->GetBlockTime()));
1586 CBlockIndex *tip = chainActive.Tip();
1588 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1589 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1590 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1591 CheckForkWarningConditions();
1594 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1596 if (state.IsInvalid(nDoS)) {
1597 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1598 if (it != mapBlockSource.end() && State(it->second)) {
1599 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1600 State(it->second)->rejects.push_back(reject);
1602 Misbehaving(it->second, nDoS);
1605 if (!state.CorruptionPossible()) {
1606 pindex->nStatus |= BLOCK_FAILED_VALID;
1607 setDirtyBlockIndex.insert(pindex);
1608 setBlockIndexCandidates.erase(pindex);
1609 InvalidChainFound(pindex);
1613 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1615 // mark inputs spent
1616 if (!tx.IsCoinBase()) {
1617 txundo.vprevout.reserve(tx.vin.size());
1618 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1619 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1620 unsigned nPos = txin.prevout.n;
1622 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1624 // mark an outpoint spent, and construct undo information
1625 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1627 if (coins->vout.size() == 0) {
1628 CTxInUndo& undo = txundo.vprevout.back();
1629 undo.nHeight = coins->nHeight;
1630 undo.fCoinBase = coins->fCoinBase;
1631 undo.nVersion = coins->nVersion;
1637 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1638 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1639 inputs.SetNullifier(nf, true);
1644 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1647 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1650 UpdateCoins(tx, state, inputs, txundo, nHeight);
1653 bool CScriptCheck::operator()() {
1654 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1655 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1656 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1661 bool NonContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1663 if (!tx.IsCoinBase())
1666 pvChecks->reserve(tx.vin.size());
1668 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1669 // for an attacker to attempt to split the network.
1670 if (!inputs.HaveInputs(tx))
1671 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1673 // are the JoinSplit's requirements met?
1674 if (!inputs.HaveJoinSplitRequirements(tx))
1675 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1677 CAmount nValueIn = 0;
1679 for (unsigned int i = 0; i < tx.vin.size(); i++)
1681 const COutPoint &prevout = tx.vin[i].prevout;
1682 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1685 if (coins->IsCoinBase()) {
1686 // Ensure that coinbases cannot be spent to transparent outputs
1687 // Disabled on regtest
1688 if (fCoinbaseEnforcedProtectionEnabled &&
1689 consensusParams.fCoinbaseMustBeProtected &&
1691 return state.Invalid(
1692 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1693 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1697 // Check for negative or overflow input values
1698 nValueIn += coins->vout[prevout.n].nValue;
1699 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1700 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1701 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1705 nValueIn += tx.GetJoinSplitValueIn();
1706 if (!MoneyRange(nValueIn))
1707 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1708 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1710 if (nValueIn < tx.GetValueOut())
1711 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1712 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1713 REJECT_INVALID, "bad-txns-in-belowout");
1715 // Tally transaction fees
1716 CAmount nTxFee = nValueIn - tx.GetValueOut();
1718 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1719 REJECT_INVALID, "bad-txns-fee-negative");
1721 if (!MoneyRange(nFees))
1722 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1723 REJECT_INVALID, "bad-txns-fee-outofrange");
1725 // The first loop above does all the inexpensive checks.
1726 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1727 // Helps prevent CPU exhaustion attacks.
1729 // Skip ECDSA signature verification when connecting blocks
1730 // before the last block chain checkpoint. This is safe because block merkle hashes are
1731 // still computed and checked, and any change will be caught at the next checkpoint.
1732 if (fScriptChecks) {
1733 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1734 const COutPoint &prevout = tx.vin[i].prevout;
1735 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1739 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1741 pvChecks->push_back(CScriptCheck());
1742 check.swap(pvChecks->back());
1743 } else if (!check()) {
1744 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1745 // Check whether the failure was caused by a
1746 // non-mandatory script verification check, such as
1747 // non-standard DER encodings or non-null dummy
1748 // arguments; if so, don't trigger DoS protection to
1749 // avoid splitting the network between upgraded and
1750 // non-upgraded nodes.
1751 CScriptCheck check(*coins, tx, i,
1752 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1754 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1756 // Failures of other flags indicate a transaction that is
1757 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1758 // such nodes as they are not following the protocol. That
1759 // said during an upgrade careful thought should be taken
1760 // as to the correct behavior - we may want to continue
1761 // peering with non-upgraded nodes even after a soft-fork
1762 // super-majority vote has passed.
1763 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1772 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1774 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1778 if (!tx.IsCoinBase())
1780 // While checking, GetBestBlock() refers to the parent block.
1781 // This is also true for mempool checks.
1782 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1783 int nSpendHeight = pindexPrev->nHeight + 1;
1784 for (unsigned int i = 0; i < tx.vin.size(); i++)
1786 const COutPoint &prevout = tx.vin[i].prevout;
1787 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1788 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1792 // If prev is coinbase, check that it's matured
1793 if (coins->IsCoinBase()) {
1794 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1795 return state.Invalid(
1796 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1797 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1808 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1810 // Open history file to append
1811 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1812 if (fileout.IsNull())
1813 return error("%s: OpenUndoFile failed", __func__);
1815 // Write index header
1816 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1817 fileout << FLATDATA(messageStart) << nSize;
1820 long fileOutPos = ftell(fileout.Get());
1822 return error("%s: ftell failed", __func__);
1823 pos.nPos = (unsigned int)fileOutPos;
1824 fileout << blockundo;
1826 // calculate & write checksum
1827 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1828 hasher << hashBlock;
1829 hasher << blockundo;
1830 fileout << hasher.GetHash();
1835 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1837 // Open history file to read
1838 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1839 if (filein.IsNull())
1840 return error("%s: OpenBlockFile failed", __func__);
1843 uint256 hashChecksum;
1845 filein >> blockundo;
1846 filein >> hashChecksum;
1848 catch (const std::exception& e) {
1849 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1853 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1854 hasher << hashBlock;
1855 hasher << blockundo;
1856 if (hashChecksum != hasher.GetHash())
1857 return error("%s: Checksum mismatch", __func__);
1862 /** Abort with a message */
1863 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1865 strMiscWarning = strMessage;
1866 LogPrintf("*** %s\n", strMessage);
1867 uiInterface.ThreadSafeMessageBox(
1868 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1869 "", CClientUIInterface::MSG_ERROR);
1874 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1876 AbortNode(strMessage, userMessage);
1877 return state.Error(strMessage);
1883 * Apply the undo operation of a CTxInUndo to the given chain state.
1884 * @param undo The undo object.
1885 * @param view The coins view to which to apply the changes.
1886 * @param out The out point that corresponds to the tx input.
1887 * @return True on success.
1889 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1893 CCoinsModifier coins = view.ModifyCoins(out.hash);
1894 if (undo.nHeight != 0) {
1895 // undo data contains height: this is the last output of the prevout tx being spent
1896 if (!coins->IsPruned())
1897 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1899 coins->fCoinBase = undo.fCoinBase;
1900 coins->nHeight = undo.nHeight;
1901 coins->nVersion = undo.nVersion;
1903 if (coins->IsPruned())
1904 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1906 if (coins->IsAvailable(out.n))
1907 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1908 if (coins->vout.size() < out.n+1)
1909 coins->vout.resize(out.n+1);
1910 coins->vout[out.n] = undo.txout;
1915 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1917 assert(pindex->GetBlockHash() == view.GetBestBlock());
1923 komodo_disconnect(pindex,block);
1924 CBlockUndo blockUndo;
1925 CDiskBlockPos pos = pindex->GetUndoPos();
1927 return error("DisconnectBlock(): no undo data available");
1928 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1929 return error("DisconnectBlock(): failure reading undo data");
1931 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1932 return error("DisconnectBlock(): block and undo data inconsistent");
1934 // undo transactions in reverse order
1935 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1936 const CTransaction &tx = block.vtx[i];
1937 uint256 hash = tx.GetHash();
1939 // Check that all outputs are available and match the outputs in the block itself
1942 CCoinsModifier outs = view.ModifyCoins(hash);
1943 outs->ClearUnspendable();
1945 CCoins outsBlock(tx, pindex->nHeight);
1946 // The CCoins serialization does not serialize negative numbers.
1947 // No network rules currently depend on the version here, so an inconsistency is harmless
1948 // but it must be corrected before txout nversion ever influences a network rule.
1949 if (outsBlock.nVersion < 0)
1950 outs->nVersion = outsBlock.nVersion;
1951 if (*outs != outsBlock)
1952 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1958 // unspend nullifiers
1959 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1960 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1961 view.SetNullifier(nf, false);
1966 if (i > 0) { // not coinbases
1967 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1968 if (txundo.vprevout.size() != tx.vin.size())
1969 return error("DisconnectBlock(): transaction and undo data inconsistent");
1970 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1971 const COutPoint &out = tx.vin[j].prevout;
1972 const CTxInUndo &undo = txundo.vprevout[j];
1973 if (!ApplyTxInUndo(undo, view, out))
1979 // set the old best anchor back
1980 view.PopAnchor(blockUndo.old_tree_root);
1982 // move best block pointer to prevout block
1983 view.SetBestBlock(pindex->pprev->GetBlockHash());
1993 void static FlushBlockFile(bool fFinalize = false)
1995 LOCK(cs_LastBlockFile);
1997 CDiskBlockPos posOld(nLastBlockFile, 0);
1999 FILE *fileOld = OpenBlockFile(posOld);
2002 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2003 FileCommit(fileOld);
2007 fileOld = OpenUndoFile(posOld);
2010 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2011 FileCommit(fileOld);
2016 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2018 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2020 void ThreadScriptCheck() {
2021 RenameThread("zcash-scriptch");
2022 scriptcheckqueue.Thread();
2026 // Called periodically asynchronously; alerts if it smells like
2027 // we're being fed a bad chain (blocks being generated much
2028 // too slowly or too quickly).
2030 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2031 int64_t nPowTargetSpacing)
2033 if (bestHeader == NULL || initialDownloadCheck()) return;
2035 static int64_t lastAlertTime = 0;
2036 int64_t now = GetAdjustedTime();
2037 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2039 const int SPAN_HOURS=4;
2040 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2041 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2043 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2045 std::string strWarning;
2046 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2049 const CBlockIndex* i = bestHeader;
2051 while (i->GetBlockTime() >= startTime) {
2054 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2057 // How likely is it to find that many by chance?
2058 double p = boost::math::pdf(poisson, nBlocks);
2060 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2061 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2063 // Aim for one false-positive about every fifty years of normal running:
2064 const int FIFTY_YEARS = 50*365*24*60*60;
2065 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2067 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2069 // Many fewer blocks than expected: alert!
2070 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2071 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2073 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2075 // Many more blocks than expected: alert!
2076 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2077 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2079 if (!strWarning.empty())
2081 strMiscWarning = strWarning;
2082 CAlert::Notify(strWarning, true);
2083 lastAlertTime = now;
2087 static int64_t nTimeVerify = 0;
2088 static int64_t nTimeConnect = 0;
2089 static int64_t nTimeIndex = 0;
2090 static int64_t nTimeCallbacks = 0;
2091 static int64_t nTimeTotal = 0;
2093 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2095 const CChainParams& chainparams = Params();
2096 AssertLockHeld(cs_main);
2097 // Check it again in case a previous version let a bad block in
2098 if (!CheckBlock(pindex->nHeight,pindex,block, state, !fJustCheck, !fJustCheck))
2101 // verify that the view's current state corresponds to the previous block
2102 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2103 assert(hashPrevBlock == view.GetBestBlock());
2105 // Special case for the genesis block, skipping connection of its transactions
2106 // (its coinbase is unspendable)
2107 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2109 view.SetBestBlock(pindex->GetBlockHash());
2110 // Before the genesis block, there was an empty tree
2111 ZCIncrementalMerkleTree tree;
2112 pindex->hashAnchor = tree.root();
2117 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2118 if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet"
2120 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2121 // unless those are already completely spent.
2122 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2123 const CCoins* coins = view.AccessCoins(tx.GetHash());
2124 if (coins && !coins->IsPruned())
2125 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2126 REJECT_INVALID, "bad-txns-BIP30");
2129 unsigned int flags = SCRIPT_VERIFY_P2SH;
2131 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2132 // when 75% of the network has upgraded:
2133 if (block.nVersion >= 3) {
2134 flags |= SCRIPT_VERIFY_DERSIG;
2137 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2138 // blocks, when 75% of the network has upgraded:
2139 if (block.nVersion >= 4) {
2140 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2143 CBlockUndo blockundo;
2145 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2147 int64_t nTimeStart = GetTimeMicros();
2150 int64_t interest,sum = 0;
2151 unsigned int nSigOps = 0;
2152 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2153 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2154 vPos.reserve(block.vtx.size());
2155 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2157 // Construct the incremental merkle tree at the current
2159 auto old_tree_root = view.GetBestAnchor();
2160 // saving the top anchor in the block index as we go.
2162 pindex->hashAnchor = old_tree_root;
2164 ZCIncrementalMerkleTree tree;
2165 // This should never fail: we should always be able to get the root
2166 // that is on the tip of our chain
2167 assert(view.GetAnchorAt(old_tree_root, tree));
2170 // Consistency check: the root of the tree we're given should
2171 // match what we asked for.
2172 assert(tree.root() == old_tree_root);
2175 for (unsigned int i = 0; i < block.vtx.size(); i++)
2177 const CTransaction &tx = block.vtx[i];
2179 nInputs += tx.vin.size();
2180 nSigOps += GetLegacySigOpCount(tx);
2181 if (nSigOps > MAX_BLOCK_SIGOPS)
2182 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2183 REJECT_INVALID, "bad-blk-sigops");
2184 //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
2185 if (!tx.IsCoinBase())
2187 if (!view.HaveInputs(tx))
2188 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2189 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2191 // are the JoinSplit's requirements met?
2192 if (!view.HaveJoinSplitRequirements(tx))
2193 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2194 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2196 // Add in sigops done by pay-to-script-hash inputs;
2197 // this is to prevent a "rogue miner" from creating
2198 // an incredibly-expensive-to-validate block.
2199 nSigOps += GetP2SHSigOpCount(tx, view);
2200 if (nSigOps > MAX_BLOCK_SIGOPS)
2201 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2202 REJECT_INVALID, "bad-blk-sigops");
2204 nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
2206 std::vector<CScriptCheck> vChecks;
2207 if (!ContextualCheckInputs(tx, state, view, fScriptChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2209 control.Add(vChecks);
2211 komodo_accrued_interest(pindex->nHeight,sum);
2214 blockundo.vtxundo.push_back(CTxUndo());
2216 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2218 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2219 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2220 // Insert the note commitments into our temporary tree.
2222 tree.append(note_commitment);
2226 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2227 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2230 view.PushAnchor(tree);
2231 blockundo.old_tree_root = old_tree_root;
2233 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2234 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
2236 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2237 if (block.vtx[0].GetValueOut() > blockReward)
2238 return state.DoS(100,
2239 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2240 block.vtx[0].GetValueOut(), blockReward),
2241 REJECT_INVALID, "bad-cb-amount");
2243 if (!control.Wait())
2244 return state.DoS(100, false);
2245 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2246 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
2251 // Write undo information to disk
2252 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2254 if (pindex->GetUndoPos().IsNull()) {
2256 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2257 return error("ConnectBlock(): FindUndoPos failed");
2258 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2259 return AbortNode(state, "Failed to write undo data");
2261 // update nUndoPos in block index
2262 pindex->nUndoPos = pos.nPos;
2263 pindex->nStatus |= BLOCK_HAVE_UNDO;
2266 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2267 setDirtyBlockIndex.insert(pindex);
2271 if (!pblocktree->WriteTxIndex(vPos))
2272 return AbortNode(state, "Failed to write transaction index");
2274 // add this block to the view's block chain
2275 view.SetBestBlock(pindex->GetBlockHash());
2277 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2278 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2280 // Watch for changes to the previous coinbase transaction.
2281 static uint256 hashPrevBestCoinBase;
2282 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2283 hashPrevBestCoinBase = block.vtx[0].GetHash();
2285 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2286 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2288 //FlushStateToDisk();
2289 komodo_connectblock(pindex,*(CBlock *)&block);
2294 enum FlushStateMode {
2296 FLUSH_STATE_IF_NEEDED,
2297 FLUSH_STATE_PERIODIC,
2302 * Update the on-disk chain state.
2303 * The caches and indexes are flushed depending on the mode we're called with
2304 * if they're too large, if it's been a while since the last write,
2305 * or always and in all cases if we're in prune mode and are deleting files.
2307 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2308 LOCK2(cs_main, cs_LastBlockFile);
2309 static int64_t nLastWrite = 0;
2310 static int64_t nLastFlush = 0;
2311 static int64_t nLastSetChain = 0;
2312 std::set<int> setFilesToPrune;
2313 bool fFlushForPrune = false;
2315 if (fPruneMode && fCheckForPruning && !fReindex) {
2316 FindFilesToPrune(setFilesToPrune);
2317 fCheckForPruning = false;
2318 if (!setFilesToPrune.empty()) {
2319 fFlushForPrune = true;
2321 pblocktree->WriteFlag("prunedblockfiles", true);
2326 int64_t nNow = GetTimeMicros();
2327 // Avoid writing/flushing immediately after startup.
2328 if (nLastWrite == 0) {
2331 if (nLastFlush == 0) {
2334 if (nLastSetChain == 0) {
2335 nLastSetChain = nNow;
2337 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2338 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2339 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2340 // The cache is over the limit, we have to write now.
2341 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2342 // 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.
2343 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2344 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2345 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2346 // Combine all conditions that result in a full cache flush.
2347 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2348 // Write blocks and block index to disk.
2349 if (fDoFullFlush || fPeriodicWrite) {
2350 // Depend on nMinDiskSpace to ensure we can write block index
2351 if (!CheckDiskSpace(0))
2352 return state.Error("out of disk space");
2353 // First make sure all block and undo data is flushed to disk.
2355 // Then update all block file information (which may refer to block and undo files).
2357 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2358 vFiles.reserve(setDirtyFileInfo.size());
2359 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2360 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2361 setDirtyFileInfo.erase(it++);
2363 std::vector<const CBlockIndex*> vBlocks;
2364 vBlocks.reserve(setDirtyBlockIndex.size());
2365 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2366 vBlocks.push_back(*it);
2367 setDirtyBlockIndex.erase(it++);
2369 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2370 return AbortNode(state, "Files to write to block index database");
2373 // Finally remove any pruned files
2375 UnlinkPrunedFiles(setFilesToPrune);
2378 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2380 // Typical CCoins structures on disk are around 128 bytes in size.
2381 // Pushing a new one to the database can cause it to be written
2382 // twice (once in the log, and once in the tables). This is already
2383 // an overestimation, as most will delete an existing entry or
2384 // overwrite one. Still, use a conservative safety factor of 2.
2385 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2386 return state.Error("out of disk space");
2387 // Flush the chainstate (which may refer to block index entries).
2388 if (!pcoinsTip->Flush())
2389 return AbortNode(state, "Failed to write to coin database");
2392 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2393 // Update best block in wallet (so we can detect restored wallets).
2394 GetMainSignals().SetBestChain(chainActive.GetLocator());
2395 nLastSetChain = nNow;
2397 } catch (const std::runtime_error& e) {
2398 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2403 void FlushStateToDisk() {
2404 CValidationState state;
2405 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2408 void PruneAndFlush() {
2409 CValidationState state;
2410 fCheckForPruning = true;
2411 FlushStateToDisk(state, FLUSH_STATE_NONE);
2414 /** Update chainActive and related internal data structures. */
2415 void static UpdateTip(CBlockIndex *pindexNew) {
2416 const CChainParams& chainParams = Params();
2417 chainActive.SetTip(pindexNew);
2420 nTimeBestReceived = GetTime();
2421 mempool.AddTransactionsUpdated(1);
2423 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2424 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2425 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2426 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2428 cvBlockChange.notify_all();
2430 // Check the version of the last 100 blocks to see if we need to upgrade:
2431 static bool fWarned = false;
2432 if (!IsInitialBlockDownload() && !fWarned)
2435 const CBlockIndex* pindex = chainActive.Tip();
2436 for (int i = 0; i < 100 && pindex != NULL; i++)
2438 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2440 pindex = pindex->pprev;
2443 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2444 if (nUpgraded > 100/2)
2446 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2447 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2448 CAlert::Notify(strMiscWarning, true);
2454 /** Disconnect chainActive's tip. */
2455 bool static DisconnectTip(CValidationState &state) {
2456 CBlockIndex *pindexDelete = chainActive.Tip();
2457 assert(pindexDelete);
2458 mempool.check(pcoinsTip);
2459 // Read block from disk.
2461 if (!ReadBlockFromDisk(block, pindexDelete))
2462 return AbortNode(state, "Failed to read block");
2463 // Apply the block atomically to the chain state.
2464 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2465 int64_t nStart = GetTimeMicros();
2467 CCoinsViewCache view(pcoinsTip);
2468 if (!DisconnectBlock(block, state, pindexDelete, view))
2469 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2470 assert(view.Flush());
2472 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2473 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2474 // Write the chain state to disk, if necessary.
2475 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2477 // Resurrect mempool transactions from the disconnected block.
2478 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2479 // ignore validation errors in resurrected transactions
2480 list<CTransaction> removed;
2481 CValidationState stateDummy;
2482 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2483 mempool.remove(tx, removed, true);
2485 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2486 // The anchor may not change between block disconnects,
2487 // in which case we don't want to evict from the mempool yet!
2488 mempool.removeWithAnchor(anchorBeforeDisconnect);
2490 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2491 mempool.check(pcoinsTip);
2492 // Update chainActive and related variables.
2493 UpdateTip(pindexDelete->pprev);
2494 // Get the current commitment tree
2495 ZCIncrementalMerkleTree newTree;
2496 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2497 // Let wallets know transactions went from 1-confirmed to
2498 // 0-confirmed or conflicted:
2499 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2500 SyncWithWallets(tx, NULL);
2502 // Update cached incremental witnesses
2503 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2507 static int64_t nTimeReadFromDisk = 0;
2508 static int64_t nTimeConnectTotal = 0;
2509 static int64_t nTimeFlush = 0;
2510 static int64_t nTimeChainState = 0;
2511 static int64_t nTimePostConnect = 0;
2514 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2515 * corresponding to pindexNew, to bypass loading it again from disk.
2517 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2518 assert(pindexNew->pprev == chainActive.Tip());
2519 mempool.check(pcoinsTip);
2520 // Read block from disk.
2521 int64_t nTime1 = GetTimeMicros();
2524 if (!ReadBlockFromDisk(block, pindexNew))
2525 return AbortNode(state, "Failed to read block");
2528 // Get the current commitment tree
2529 ZCIncrementalMerkleTree oldTree;
2530 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2531 // Apply the block atomically to the chain state.
2532 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2534 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2536 CCoinsViewCache view(pcoinsTip);
2537 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2538 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2539 GetMainSignals().BlockChecked(*pblock, state);
2541 if (state.IsInvalid())
2542 InvalidBlockFound(pindexNew, state);
2543 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2545 mapBlockSource.erase(inv.hash);
2546 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2547 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2548 assert(view.Flush());
2550 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2551 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2552 // Write the chain state to disk, if necessary.
2553 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2555 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2556 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2557 // Remove conflicting transactions from the mempool.
2558 list<CTransaction> txConflicted;
2559 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2560 mempool.check(pcoinsTip);
2561 // Update chainActive & related variables.
2562 UpdateTip(pindexNew);
2563 // Tell wallet about transactions that went from mempool
2565 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2566 SyncWithWallets(tx, NULL);
2568 // ... and about transactions that got confirmed:
2569 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2570 SyncWithWallets(tx, pblock);
2572 // Update cached incremental witnesses
2573 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2575 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2576 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2577 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2582 * Return the tip of the chain with the most work in it, that isn't
2583 * known to be invalid (it's however far from certain to be valid).
2585 static CBlockIndex* FindMostWorkChain() {
2587 CBlockIndex *pindexNew = NULL;
2589 // Find the best candidate header.
2591 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2592 if (it == setBlockIndexCandidates.rend())
2597 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2598 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2599 CBlockIndex *pindexTest = pindexNew;
2600 bool fInvalidAncestor = false;
2601 while (pindexTest && !chainActive.Contains(pindexTest)) {
2602 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2604 // Pruned nodes may have entries in setBlockIndexCandidates for
2605 // which block files have been deleted. Remove those as candidates
2606 // for the most work chain if we come across them; we can't switch
2607 // to a chain unless we have all the non-active-chain parent blocks.
2608 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2609 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2610 if (fFailedChain || fMissingData) {
2611 // Candidate chain is not usable (either invalid or missing data)
2612 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2613 pindexBestInvalid = pindexNew;
2614 CBlockIndex *pindexFailed = pindexNew;
2615 // Remove the entire chain from the set.
2616 while (pindexTest != pindexFailed) {
2618 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2619 } else if (fMissingData) {
2620 // If we're missing data, then add back to mapBlocksUnlinked,
2621 // so that if the block arrives in the future we can try adding
2622 // to setBlockIndexCandidates again.
2623 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2625 setBlockIndexCandidates.erase(pindexFailed);
2626 pindexFailed = pindexFailed->pprev;
2628 setBlockIndexCandidates.erase(pindexTest);
2629 fInvalidAncestor = true;
2632 pindexTest = pindexTest->pprev;
2634 if (!fInvalidAncestor)
2639 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2640 static void PruneBlockIndexCandidates() {
2641 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2642 // reorganization to a better block fails.
2643 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2644 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2645 setBlockIndexCandidates.erase(it++);
2647 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2648 assert(!setBlockIndexCandidates.empty());
2652 * Try to make some progress towards making pindexMostWork the active block.
2653 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2655 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2656 AssertLockHeld(cs_main);
2657 bool fInvalidFound = false;
2658 const CBlockIndex *pindexOldTip = chainActive.Tip();
2659 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2661 // Disconnect active blocks which are no longer in the best chain.
2662 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2663 if (!DisconnectTip(state))
2667 // Build list of new blocks to connect.
2668 std::vector<CBlockIndex*> vpindexToConnect;
2669 bool fContinue = true;
2670 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2671 while (fContinue && nHeight != pindexMostWork->nHeight) {
2672 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2673 // a few blocks along the way.
2674 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2675 vpindexToConnect.clear();
2676 vpindexToConnect.reserve(nTargetHeight - nHeight);
2677 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2678 while (pindexIter && pindexIter->nHeight != nHeight) {
2679 vpindexToConnect.push_back(pindexIter);
2680 pindexIter = pindexIter->pprev;
2682 nHeight = nTargetHeight;
2684 // Connect new blocks.
2685 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2686 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2687 if (state.IsInvalid()) {
2688 // The block violates a consensus rule.
2689 if (!state.CorruptionPossible())
2690 InvalidChainFound(vpindexToConnect.back());
2691 state = CValidationState();
2692 fInvalidFound = true;
2696 // A system error occurred (disk space, database error, ...).
2700 PruneBlockIndexCandidates();
2701 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2702 // We're in a better position than we were. Return temporarily to release the lock.
2710 // Callbacks/notifications for a new best chain.
2712 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2714 CheckForkWarningConditions();
2720 * Make the best chain active, in multiple steps. The result is either failure
2721 * or an activated best chain. pblock is either NULL or a pointer to a block
2722 * that is already loaded (to avoid loading it again from disk).
2724 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2725 CBlockIndex *pindexNewTip = NULL;
2726 CBlockIndex *pindexMostWork = NULL;
2727 const CChainParams& chainParams = Params();
2729 boost::this_thread::interruption_point();
2731 bool fInitialDownload;
2734 pindexMostWork = FindMostWorkChain();
2736 // Whether we have anything to do at all.
2737 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2740 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2743 pindexNewTip = chainActive.Tip();
2744 fInitialDownload = IsInitialBlockDownload();
2746 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2748 // Notifications/callbacks that can run without cs_main
2749 if (!fInitialDownload) {
2750 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2751 // Relay inventory, but don't relay old inventory during initial block download.
2752 int nBlockEstimate = 0;
2753 if (fCheckpointsEnabled)
2754 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2755 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2756 // in a stalled download if the block file is pruned before the request.
2757 if (nLocalServices & NODE_NETWORK) {
2759 BOOST_FOREACH(CNode* pnode, vNodes)
2760 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2761 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2763 // Notify external listeners about the new tip.
2764 uiInterface.NotifyBlockTip(hashNewTip);
2766 } while(pindexMostWork != chainActive.Tip());
2769 // Write changes periodically to disk, after relay.
2770 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2777 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2778 AssertLockHeld(cs_main);
2780 // Mark the block itself as invalid.
2781 pindex->nStatus |= BLOCK_FAILED_VALID;
2782 setDirtyBlockIndex.insert(pindex);
2783 setBlockIndexCandidates.erase(pindex);
2785 while (chainActive.Contains(pindex)) {
2786 CBlockIndex *pindexWalk = chainActive.Tip();
2787 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2788 setDirtyBlockIndex.insert(pindexWalk);
2789 setBlockIndexCandidates.erase(pindexWalk);
2790 // ActivateBestChain considers blocks already in chainActive
2791 // unconditionally valid already, so force disconnect away from it.
2792 if (!DisconnectTip(state)) {
2797 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2799 BlockMap::iterator it = mapBlockIndex.begin();
2800 while (it != mapBlockIndex.end()) {
2801 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2802 setBlockIndexCandidates.insert(it->second);
2807 InvalidChainFound(pindex);
2811 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2812 AssertLockHeld(cs_main);
2814 int nHeight = pindex->nHeight;
2816 // Remove the invalidity flag from this block and all its descendants.
2817 BlockMap::iterator it = mapBlockIndex.begin();
2818 while (it != mapBlockIndex.end()) {
2819 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2820 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2821 setDirtyBlockIndex.insert(it->second);
2822 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2823 setBlockIndexCandidates.insert(it->second);
2825 if (it->second == pindexBestInvalid) {
2826 // Reset invalid block marker if it was pointing to one of those.
2827 pindexBestInvalid = NULL;
2833 // Remove the invalidity flag from all ancestors too.
2834 while (pindex != NULL) {
2835 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2836 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2837 setDirtyBlockIndex.insert(pindex);
2839 pindex = pindex->pprev;
2844 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2846 // Check for duplicate
2847 uint256 hash = block.GetHash();
2848 BlockMap::iterator it = mapBlockIndex.find(hash);
2849 if (it != mapBlockIndex.end())
2852 // Construct new block index object
2853 CBlockIndex* pindexNew = new CBlockIndex(block);
2855 // We assign the sequence id to blocks only when the full data is available,
2856 // to avoid miners withholding blocks but broadcasting headers, to get a
2857 // competitive advantage.
2858 pindexNew->nSequenceId = 0;
2859 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2860 pindexNew->phashBlock = &((*mi).first);
2861 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2862 if (miPrev != mapBlockIndex.end())
2864 pindexNew->pprev = (*miPrev).second;
2865 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2866 pindexNew->BuildSkip();
2868 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2869 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2870 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2871 pindexBestHeader = pindexNew;
2873 setDirtyBlockIndex.insert(pindexNew);
2878 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2879 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2881 pindexNew->nTx = block.vtx.size();
2882 pindexNew->nChainTx = 0;
2883 pindexNew->nFile = pos.nFile;
2884 pindexNew->nDataPos = pos.nPos;
2885 pindexNew->nUndoPos = 0;
2886 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2887 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2888 setDirtyBlockIndex.insert(pindexNew);
2890 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2891 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2892 deque<CBlockIndex*> queue;
2893 queue.push_back(pindexNew);
2895 // Recursively process any descendant blocks that now may be eligible to be connected.
2896 while (!queue.empty()) {
2897 CBlockIndex *pindex = queue.front();
2899 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2901 LOCK(cs_nBlockSequenceId);
2902 pindex->nSequenceId = nBlockSequenceId++;
2904 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2905 setBlockIndexCandidates.insert(pindex);
2907 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2908 while (range.first != range.second) {
2909 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2910 queue.push_back(it->second);
2912 mapBlocksUnlinked.erase(it);
2916 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2917 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2924 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2926 LOCK(cs_LastBlockFile);
2928 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2929 if (vinfoBlockFile.size() <= nFile) {
2930 vinfoBlockFile.resize(nFile + 1);
2934 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2936 if (vinfoBlockFile.size() <= nFile) {
2937 vinfoBlockFile.resize(nFile + 1);
2941 pos.nPos = vinfoBlockFile[nFile].nSize;
2944 if (nFile != nLastBlockFile) {
2946 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2948 FlushBlockFile(!fKnown);
2949 nLastBlockFile = nFile;
2952 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2954 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2956 vinfoBlockFile[nFile].nSize += nAddSize;
2959 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2960 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2961 if (nNewChunks > nOldChunks) {
2963 fCheckForPruning = true;
2964 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2965 FILE *file = OpenBlockFile(pos);
2967 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2968 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2973 return state.Error("out of disk space");
2977 setDirtyFileInfo.insert(nFile);
2981 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2985 LOCK(cs_LastBlockFile);
2987 unsigned int nNewSize;
2988 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2989 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2990 setDirtyFileInfo.insert(nFile);
2992 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2993 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2994 if (nNewChunks > nOldChunks) {
2996 fCheckForPruning = true;
2997 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2998 FILE *file = OpenUndoFile(pos);
3000 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3001 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3006 return state.Error("out of disk space");
3012 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3014 uint8_t pubkey33[33];
3016 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3017 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3018 // Check block version
3019 //if (block.nVersion < MIN_BLOCK_VERSION)
3020 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3022 // Check Equihash solution is valid
3023 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3024 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3026 // Check proof of work matches claimed amount
3027 komodo_index2pubkey33(pubkey33,pindex,height);
3028 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3029 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3033 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
3035 // These are checks that are independent of context.
3037 // Check that the header is valid (particularly PoW). This is mostly
3038 // redundant with the call in AcceptBlockHeader.
3039 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3042 // Check the merkle root.
3043 if (fCheckMerkleRoot) {
3045 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3046 if (block.hashMerkleRoot != hashMerkleRoot2)
3047 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3048 REJECT_INVALID, "bad-txnmrklroot", true);
3050 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3051 // of transactions in a block without affecting the merkle root of a block,
3052 // while still invalidating it.
3054 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3055 REJECT_INVALID, "bad-txns-duplicate", true);
3058 // All potential-corruption validation must be done before we do any
3059 // transaction validation, as otherwise we may mark the header as invalid
3060 // because we receive the wrong transactions for it.
3063 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3064 return state.DoS(100, error("CheckBlock(): size limits failed"),
3065 REJECT_INVALID, "bad-blk-length");
3067 // First transaction must be coinbase, the rest must not be
3068 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3069 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3070 REJECT_INVALID, "bad-cb-missing");
3071 for (unsigned int i = 1; i < block.vtx.size(); i++)
3072 if (block.vtx[i].IsCoinBase())
3073 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3074 REJECT_INVALID, "bad-cb-multiple");
3076 // Check transactions
3077 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3078 if (!CheckTransaction(tx, state))
3079 return error("CheckBlock(): CheckTransaction failed");
3081 unsigned int nSigOps = 0;
3082 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3084 nSigOps += GetLegacySigOpCount(tx);
3086 if (nSigOps > MAX_BLOCK_SIGOPS)
3087 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3088 REJECT_INVALID, "bad-blk-sigops", true);
3093 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3095 const CChainParams& chainParams = Params();
3096 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3097 uint256 hash = block.GetHash();
3098 if (hash == consensusParams.hashGenesisBlock)
3103 int nHeight = pindexPrev->nHeight+1;
3105 // Check proof of work
3106 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3108 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3109 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3110 REJECT_INVALID, "bad-diffbits");
3113 // Check timestamp against prev
3114 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3115 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3116 REJECT_INVALID, "time-too-old");
3118 if(fCheckpointsEnabled)
3120 // Check that the block chain matches the known block chain up to a checkpoint
3121 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3122 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3124 // Don't accept any forks from the main chain prior to last checkpoint
3125 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3126 int32_t notarized_height;
3127 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3128 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3129 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3130 return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3133 // Reject block.nVersion < 4 blocks
3134 if (block.nVersion < 4)
3135 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3136 REJECT_OBSOLETE, "bad-version");
3141 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3143 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3144 const Consensus::Params& consensusParams = Params().GetConsensus();
3146 // Check that all transactions are finalized
3147 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3148 int nLockTimeFlags = 0;
3149 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3150 ? pindexPrev->GetMedianTimePast()
3151 : block.GetBlockTime();
3152 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3153 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3157 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3158 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3159 if (block.nVersion >= 2)
3161 CScript expect = CScript() << nHeight;
3162 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3163 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3164 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3171 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3173 const CChainParams& chainparams = Params();
3174 AssertLockHeld(cs_main);
3175 // Check for duplicate
3176 uint256 hash = block.GetHash();
3177 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3178 CBlockIndex *pindex = NULL;
3179 if (miSelf != mapBlockIndex.end()) {
3180 // Block header is already known.
3181 pindex = miSelf->second;
3184 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3185 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3189 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3192 // Get prev block index
3193 CBlockIndex* pindexPrev = NULL;
3194 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3195 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3196 if (mi == mapBlockIndex.end())
3197 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3198 pindexPrev = (*mi).second;
3199 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3200 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3202 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3205 pindex = AddToBlockIndex(block);
3206 //if (!CheckBlockHeader(pindex!=0?pindex->nHeight:0,pindex, block, state))
3213 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3215 const CChainParams& chainparams = Params();
3216 AssertLockHeld(cs_main);
3218 CBlockIndex *&pindex = *ppindex;
3219 if (!AcceptBlockHeader(block, state, &pindex))
3223 fprintf(stderr,"AcceptBlock error null pindex\n");
3226 // Try to process all requested blocks that we don't have, but only
3227 // process an unrequested block if it's new and has enough work to
3228 // advance our tip, and isn't too many blocks ahead.
3229 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3230 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3231 // Blocks that are too out-of-order needlessly limit the effectiveness of
3232 // pruning, because pruning will not delete block files that contain any
3233 // blocks which are too close in height to the tip. Apply this test
3234 // regardless of whether pruning is enabled; it should generally be safe to
3235 // not process unrequested blocks.
3236 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3238 // TODO: deal better with return value and error conditions for duplicate
3239 // and unrequested blocks.
3240 if (fAlreadyHave) return true;
3241 if (!fRequested) { // If we didn't ask for it:
3242 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3243 if (!fHasMoreWork) return true; // Don't process less-work chains
3244 if (fTooFarAhead) return true; // Block height is too high
3247 if ((!CheckBlock(pindex->nHeight,pindex,block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3248 if (state.IsInvalid() && !state.CorruptionPossible()) {
3249 pindex->nStatus |= BLOCK_FAILED_VALID;
3250 setDirtyBlockIndex.insert(pindex);
3255 int nHeight = pindex->nHeight;
3257 // Write block to history file
3259 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3260 CDiskBlockPos blockPos;
3263 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3264 return error("AcceptBlock(): FindBlockPos failed");
3266 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3267 AbortNode(state, "Failed to write block");
3268 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3269 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3270 } catch (const std::runtime_error& e) {
3271 return AbortNode(state, std::string("System error: ") + e.what());
3274 if (fCheckForPruning)
3275 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3280 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3282 unsigned int nFound = 0;
3283 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3285 if (pstart->nVersion >= minVersion)
3287 pstart = pstart->pprev;
3289 return (nFound >= nRequired);
3293 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3295 // Preliminary checks
3296 bool checked = CheckBlock(komodo_block2height(pblock),0,*pblock, state);
3300 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3301 fRequested |= fForceProcessing;
3303 return error("%s: CheckBlock FAILED", __func__);
3307 CBlockIndex *pindex = NULL;
3308 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3309 if (pindex && pfrom) {
3310 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3314 return error("%s: AcceptBlock FAILED", __func__);
3317 if (!ActivateBestChain(state, pblock))
3318 return error("%s: ActivateBestChain failed", __func__);
3323 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3325 AssertLockHeld(cs_main);
3326 assert(pindexPrev == chainActive.Tip());
3328 CCoinsViewCache viewNew(pcoinsTip);
3329 CBlockIndex indexDummy(block);
3330 indexDummy.pprev = pindexPrev;
3331 indexDummy.nHeight = pindexPrev->nHeight + 1;
3333 // NOTE: CheckBlockHeader is called by CheckBlock
3334 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3336 if (!CheckBlock(indexDummy.nHeight,0,block, state, fCheckPOW, fCheckMerkleRoot))
3338 if (!ContextualCheckBlock(block, state, pindexPrev))
3340 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3342 assert(state.IsValid());
3348 * BLOCK PRUNING CODE
3351 /* Calculate the amount of disk space the block & undo files currently use */
3352 uint64_t CalculateCurrentUsage()
3354 uint64_t retval = 0;
3355 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3356 retval += file.nSize + file.nUndoSize;
3361 /* Prune a block file (modify associated database entries)*/
3362 void PruneOneBlockFile(const int fileNumber)
3364 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3365 CBlockIndex* pindex = it->second;
3366 if (pindex->nFile == fileNumber) {
3367 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3368 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3370 pindex->nDataPos = 0;
3371 pindex->nUndoPos = 0;
3372 setDirtyBlockIndex.insert(pindex);
3374 // Prune from mapBlocksUnlinked -- any block we prune would have
3375 // to be downloaded again in order to consider its chain, at which
3376 // point it would be considered as a candidate for
3377 // mapBlocksUnlinked or setBlockIndexCandidates.
3378 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3379 while (range.first != range.second) {
3380 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3382 if (it->second == pindex) {
3383 mapBlocksUnlinked.erase(it);
3389 vinfoBlockFile[fileNumber].SetNull();
3390 setDirtyFileInfo.insert(fileNumber);
3394 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3396 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3397 CDiskBlockPos pos(*it, 0);
3398 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3399 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3400 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3404 /* Calculate the block/rev files that should be deleted to remain under target*/
3405 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3407 LOCK2(cs_main, cs_LastBlockFile);
3408 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3411 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3415 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3416 uint64_t nCurrentUsage = CalculateCurrentUsage();
3417 // We don't check to prune until after we've allocated new space for files
3418 // So we should leave a buffer under our target to account for another allocation
3419 // before the next pruning.
3420 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3421 uint64_t nBytesToPrune;
3424 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3425 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3426 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3428 if (vinfoBlockFile[fileNumber].nSize == 0)
3431 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3434 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3435 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3438 PruneOneBlockFile(fileNumber);
3439 // Queue up the files for removal
3440 setFilesToPrune.insert(fileNumber);
3441 nCurrentUsage -= nBytesToPrune;
3446 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3447 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3448 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3449 nLastBlockWeCanPrune, count);
3452 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3454 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3456 // Check for nMinDiskSpace bytes (currently 50MB)
3457 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3458 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3463 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3467 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3468 boost::filesystem::create_directories(path.parent_path());
3469 FILE* file = fopen(path.string().c_str(), "rb+");
3470 if (!file && !fReadOnly)
3471 file = fopen(path.string().c_str(), "wb+");
3473 LogPrintf("Unable to open file %s\n", path.string());
3477 if (fseek(file, pos.nPos, SEEK_SET)) {
3478 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3486 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3487 return OpenDiskFile(pos, "blk", fReadOnly);
3490 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3491 return OpenDiskFile(pos, "rev", fReadOnly);
3494 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3496 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3499 CBlockIndex * InsertBlockIndex(uint256 hash)
3505 BlockMap::iterator mi = mapBlockIndex.find(hash);
3506 if (mi != mapBlockIndex.end())
3507 return (*mi).second;
3510 CBlockIndex* pindexNew = new CBlockIndex();
3512 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3513 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3514 pindexNew->phashBlock = &((*mi).first);
3519 bool static LoadBlockIndexDB()
3521 const CChainParams& chainparams = Params();
3522 if (!pblocktree->LoadBlockIndexGuts())
3525 boost::this_thread::interruption_point();
3527 // Calculate nChainWork
3528 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3529 vSortedByHeight.reserve(mapBlockIndex.size());
3530 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3532 CBlockIndex* pindex = item.second;
3533 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3535 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3536 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3538 CBlockIndex* pindex = item.second;
3539 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3540 // We can link the chain of blocks for which we've received transactions at some point.
3541 // Pruned nodes may have deleted the block.
3542 if (pindex->nTx > 0) {
3543 if (pindex->pprev) {
3544 if (pindex->pprev->nChainTx) {
3545 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3547 pindex->nChainTx = 0;
3548 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3551 pindex->nChainTx = pindex->nTx;
3554 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3555 setBlockIndexCandidates.insert(pindex);
3556 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3557 pindexBestInvalid = pindex;
3559 pindex->BuildSkip();
3560 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3561 pindexBestHeader = pindex;
3564 // Load block file info
3565 pblocktree->ReadLastBlockFile(nLastBlockFile);
3566 vinfoBlockFile.resize(nLastBlockFile + 1);
3567 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3568 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3569 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3571 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3572 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3573 CBlockFileInfo info;
3574 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3575 vinfoBlockFile.push_back(info);
3581 // Check presence of blk files
3582 LogPrintf("Checking all blk files are present...\n");
3583 set<int> setBlkDataFiles;
3584 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3586 CBlockIndex* pindex = item.second;
3587 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3588 setBlkDataFiles.insert(pindex->nFile);
3591 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3593 CDiskBlockPos pos(*it, 0);
3594 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3599 // Check whether we have ever pruned block & undo files
3600 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3602 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3604 // Check whether we need to continue reindexing
3605 bool fReindexing = false;
3606 pblocktree->ReadReindexing(fReindexing);
3607 fReindex |= fReindexing;
3609 // Check whether we have a transaction index
3610 pblocktree->ReadFlag("txindex", fTxIndex);
3611 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3613 // Load pointer to end of best chain
3614 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3615 if (it == mapBlockIndex.end())
3617 chainActive.SetTip(it->second);
3619 PruneBlockIndexCandidates();
3621 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3622 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3623 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3624 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3629 CVerifyDB::CVerifyDB()
3631 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3634 CVerifyDB::~CVerifyDB()
3636 uiInterface.ShowProgress("", 100);
3639 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3642 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3645 // Verify blocks in the best chain
3646 if (nCheckDepth <= 0)
3647 nCheckDepth = 1000000000; // suffices until the year 19000
3648 if (nCheckDepth > chainActive.Height())
3649 nCheckDepth = chainActive.Height();
3650 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3651 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3652 CCoinsViewCache coins(coinsview);
3653 CBlockIndex* pindexState = chainActive.Tip();
3654 CBlockIndex* pindexFailure = NULL;
3655 int nGoodTransactions = 0;
3656 CValidationState state;
3657 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3659 boost::this_thread::interruption_point();
3660 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3661 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3664 // check level 0: read from disk
3665 if (!ReadBlockFromDisk(block, pindex))
3666 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3667 // check level 1: verify block validity
3668 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state))
3669 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3670 // check level 2: verify undo validity
3671 if (nCheckLevel >= 2 && pindex) {
3673 CDiskBlockPos pos = pindex->GetUndoPos();
3674 if (!pos.IsNull()) {
3675 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3676 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3679 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3680 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3682 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3683 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3684 pindexState = pindex->pprev;
3686 nGoodTransactions = 0;
3687 pindexFailure = pindex;
3689 nGoodTransactions += block.vtx.size();
3691 if (ShutdownRequested())
3695 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3697 // check level 4: try reconnecting blocks
3698 if (nCheckLevel >= 4) {
3699 CBlockIndex *pindex = pindexState;
3700 while (pindex != chainActive.Tip()) {
3701 boost::this_thread::interruption_point();
3702 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3703 pindex = chainActive.Next(pindex);
3705 if (!ReadBlockFromDisk(block, pindex))
3706 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3707 if (!ConnectBlock(block, state, pindex, coins))
3708 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3712 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3717 void UnloadBlockIndex()
3720 setBlockIndexCandidates.clear();
3721 chainActive.SetTip(NULL);
3722 pindexBestInvalid = NULL;
3723 pindexBestHeader = NULL;
3725 mapOrphanTransactions.clear();
3726 mapOrphanTransactionsByPrev.clear();
3728 mapBlocksUnlinked.clear();
3729 vinfoBlockFile.clear();
3731 nBlockSequenceId = 1;
3732 mapBlockSource.clear();
3733 mapBlocksInFlight.clear();
3734 nQueuedValidatedHeaders = 0;
3735 nPreferredDownload = 0;
3736 setDirtyBlockIndex.clear();
3737 setDirtyFileInfo.clear();
3738 mapNodeState.clear();
3739 recentRejects.reset(NULL);
3741 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3742 delete entry.second;
3744 mapBlockIndex.clear();
3745 fHavePruned = false;
3748 bool LoadBlockIndex()
3750 // Load block index from databases
3751 if (!fReindex && !LoadBlockIndexDB())
3757 bool InitBlockIndex() {
3758 const CChainParams& chainparams = Params();
3761 // Initialize global variables that cannot be constructed at startup.
3762 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3764 // Check whether we're already initialized
3765 if (chainActive.Genesis() != NULL)
3768 // Use the provided setting for -txindex in the new database
3769 fTxIndex = GetBoolArg("-txindex", false);
3770 pblocktree->WriteFlag("txindex", fTxIndex);
3771 LogPrintf("Initializing databases...\n");
3773 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3776 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3777 // Start new block file
3778 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3779 CDiskBlockPos blockPos;
3780 CValidationState state;
3781 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3782 return error("LoadBlockIndex(): FindBlockPos failed");
3783 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3784 return error("LoadBlockIndex(): writing genesis block to disk failed");
3785 CBlockIndex *pindex = AddToBlockIndex(block);
3786 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3787 return error("LoadBlockIndex(): genesis block not accepted");
3788 if (!ActivateBestChain(state, &block))
3789 return error("LoadBlockIndex(): genesis block cannot be activated");
3790 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3791 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3792 } catch (const std::runtime_error& e) {
3793 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3802 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3804 const CChainParams& chainparams = Params();
3805 // Map of disk positions for blocks with unknown parent (only used for reindex)
3806 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3807 int64_t nStart = GetTimeMillis();
3811 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3812 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3813 uint64_t nRewind = blkdat.GetPos();
3814 while (!blkdat.eof()) {
3815 boost::this_thread::interruption_point();
3817 blkdat.SetPos(nRewind);
3818 nRewind++; // start one byte further next time, in case of failure
3819 blkdat.SetLimit(); // remove former limit
3820 unsigned int nSize = 0;
3823 unsigned char buf[MESSAGE_START_SIZE];
3824 blkdat.FindByte(Params().MessageStart()[0]);
3825 nRewind = blkdat.GetPos()+1;
3826 blkdat >> FLATDATA(buf);
3827 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3831 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3833 } catch (const std::exception&) {
3834 // no valid block header found; don't complain
3839 uint64_t nBlockPos = blkdat.GetPos();
3841 dbp->nPos = nBlockPos;
3842 blkdat.SetLimit(nBlockPos + nSize);
3843 blkdat.SetPos(nBlockPos);
3846 nRewind = blkdat.GetPos();
3848 // detect out of order blocks, and store them for later
3849 uint256 hash = block.GetHash();
3850 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3851 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3852 block.hashPrevBlock.ToString());
3854 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3858 // process in case the block isn't known yet
3859 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3860 CValidationState state;
3861 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3863 if (state.IsError())
3865 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3866 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3869 // Recursively process earlier encountered successors of this block
3870 deque<uint256> queue;
3871 queue.push_back(hash);
3872 while (!queue.empty()) {
3873 uint256 head = queue.front();
3875 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3876 while (range.first != range.second) {
3877 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3878 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
3880 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3882 CValidationState dummy;
3883 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3886 queue.push_back(block.GetHash());
3890 mapBlocksUnknownParent.erase(it);
3893 } catch (const std::exception& e) {
3894 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3897 } catch (const std::runtime_error& e) {
3898 AbortNode(std::string("System error: ") + e.what());
3901 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3905 void static CheckBlockIndex()
3907 const Consensus::Params& consensusParams = Params().GetConsensus();
3908 if (!fCheckBlockIndex) {
3914 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3915 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3916 // iterating the block tree require that chainActive has been initialized.)
3917 if (chainActive.Height() < 0) {
3918 assert(mapBlockIndex.size() <= 1);
3922 // Build forward-pointing map of the entire block tree.
3923 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3924 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3925 forward.insert(std::make_pair(it->second->pprev, it->second));
3928 assert(forward.size() == mapBlockIndex.size());
3930 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3931 CBlockIndex *pindex = rangeGenesis.first->second;
3932 rangeGenesis.first++;
3933 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3935 // Iterate over the entire block tree, using depth-first search.
3936 // Along the way, remember whether there are blocks on the path from genesis
3937 // block being explored which are the first to have certain properties.
3940 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3941 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3942 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3943 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3944 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3945 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3946 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3947 while (pindex != NULL) {
3949 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3950 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3951 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3952 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3953 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3954 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3955 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3957 // Begin: actual consistency checks.
3958 if (pindex->pprev == NULL) {
3959 // Genesis block checks.
3960 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3961 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3963 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3964 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3965 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3967 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3968 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3969 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3971 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3972 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3974 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3975 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3976 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3977 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3978 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3979 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3980 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.
3981 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3982 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3983 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3984 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3985 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3986 if (pindexFirstInvalid == NULL) {
3987 // Checks for not-invalid blocks.
3988 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3990 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3991 if (pindexFirstInvalid == NULL) {
3992 // If this block sorts at least as good as the current tip and
3993 // is valid and we have all data for its parents, it must be in
3994 // setBlockIndexCandidates. chainActive.Tip() must also be there
3995 // even if some data has been pruned.
3996 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3997 assert(setBlockIndexCandidates.count(pindex));
3999 // If some parent is missing, then it could be that this block was in
4000 // setBlockIndexCandidates but had to be removed because of the missing data.
4001 // In this case it must be in mapBlocksUnlinked -- see test below.
4003 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4004 assert(setBlockIndexCandidates.count(pindex) == 0);
4006 // Check whether this block is in mapBlocksUnlinked.
4007 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4008 bool foundInUnlinked = false;
4009 while (rangeUnlinked.first != rangeUnlinked.second) {
4010 assert(rangeUnlinked.first->first == pindex->pprev);
4011 if (rangeUnlinked.first->second == pindex) {
4012 foundInUnlinked = true;
4015 rangeUnlinked.first++;
4017 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4018 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4019 assert(foundInUnlinked);
4021 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4022 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4023 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4024 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4025 assert(fHavePruned); // We must have pruned.
4026 // This block may have entered mapBlocksUnlinked if:
4027 // - it has a descendant that at some point had more work than the
4029 // - we tried switching to that descendant but were missing
4030 // data for some intermediate block between chainActive and the
4032 // So if this block is itself better than chainActive.Tip() and it wasn't in
4033 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4034 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4035 if (pindexFirstInvalid == NULL) {
4036 assert(foundInUnlinked);
4040 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4041 // End: actual consistency checks.
4043 // Try descending into the first subnode.
4044 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4045 if (range.first != range.second) {
4046 // A subnode was found.
4047 pindex = range.first->second;
4051 // This is a leaf node.
4052 // Move upwards until we reach a node of which we have not yet visited the last child.
4054 // We are going to either move to a parent or a sibling of pindex.
4055 // If pindex was the first with a certain property, unset the corresponding variable.
4056 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4057 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4058 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4059 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4060 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4061 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4062 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4064 CBlockIndex* pindexPar = pindex->pprev;
4065 // Find which child we just visited.
4066 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4067 while (rangePar.first->second != pindex) {
4068 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4071 // Proceed to the next one.
4073 if (rangePar.first != rangePar.second) {
4074 // Move to the sibling.
4075 pindex = rangePar.first->second;
4086 // Check that we actually traversed the entire map.
4087 assert(nNodes == forward.size());
4090 //////////////////////////////////////////////////////////////////////////////
4095 string GetWarnings(string strFor)
4098 string strStatusBar;
4101 if (!CLIENT_VERSION_IS_RELEASE)
4102 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4104 if (GetBoolArg("-testsafemode", false))
4105 strStatusBar = strRPC = "testsafemode enabled";
4107 // Misc warnings like out of disk space and clock is wrong
4108 if (strMiscWarning != "")
4111 strStatusBar = strMiscWarning;
4114 if (fLargeWorkForkFound)
4117 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4119 else if (fLargeWorkInvalidChainFound)
4122 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.");
4128 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4130 const CAlert& alert = item.second;
4131 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4133 nPriority = alert.nPriority;
4134 strStatusBar = alert.strStatusBar;
4135 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4136 strRPC = alert.strRPCError;
4142 if (strFor == "statusbar")
4143 return strStatusBar;
4144 else if (strFor == "rpc")
4146 assert(!"GetWarnings(): invalid parameter");
4157 //////////////////////////////////////////////////////////////////////////////
4163 bool static AlreadyHave(const CInv& inv)
4169 assert(recentRejects);
4170 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4172 // If the chain tip has changed previously rejected transactions
4173 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4174 // or a double-spend. Reset the rejects filter and give those
4175 // txs a second chance.
4176 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4177 recentRejects->reset();
4180 return recentRejects->contains(inv.hash) ||
4181 mempool.exists(inv.hash) ||
4182 mapOrphanTransactions.count(inv.hash) ||
4183 pcoinsTip->HaveCoins(inv.hash);
4186 return mapBlockIndex.count(inv.hash);
4188 // Don't know what it is, just say we already got one
4192 void static ProcessGetData(CNode* pfrom)
4194 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4196 vector<CInv> vNotFound;
4200 while (it != pfrom->vRecvGetData.end()) {
4201 // Don't bother if send buffer is too full to respond anyway
4202 if (pfrom->nSendSize >= SendBufferSize())
4205 const CInv &inv = *it;
4207 boost::this_thread::interruption_point();
4210 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4213 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4214 if (mi != mapBlockIndex.end())
4216 if (chainActive.Contains(mi->second)) {
4219 static const int nOneMonth = 30 * 24 * 60 * 60;
4220 // To prevent fingerprinting attacks, only send blocks outside of the active
4221 // chain if they are valid, and no more than a month older (both in time, and in
4222 // best equivalent proof of work) than the best header chain we know about.
4223 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4224 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4225 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4227 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4231 // Pruned nodes may have deleted the block, so check whether
4232 // it's available before trying to send.
4233 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4235 // Send block from disk
4237 if (!ReadBlockFromDisk(block, (*mi).second))
4238 assert(!"cannot load block from disk");
4239 if (inv.type == MSG_BLOCK)
4240 pfrom->PushMessage("block", block);
4241 else // MSG_FILTERED_BLOCK)
4243 LOCK(pfrom->cs_filter);
4246 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4247 pfrom->PushMessage("merkleblock", merkleBlock);
4248 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4249 // This avoids hurting performance by pointlessly requiring a round-trip
4250 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4251 // they must either disconnect and retry or request the full block.
4252 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4253 // however we MUST always provide at least what the remote peer needs
4254 typedef std::pair<unsigned int, uint256> PairType;
4255 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4256 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4257 pfrom->PushMessage("tx", block.vtx[pair.first]);
4263 // Trigger the peer node to send a getblocks request for the next batch of inventory
4264 if (inv.hash == pfrom->hashContinue)
4266 // Bypass PushInventory, this must send even if redundant,
4267 // and we want it right after the last block so they don't
4268 // wait for other stuff first.
4270 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4271 pfrom->PushMessage("inv", vInv);
4272 pfrom->hashContinue.SetNull();
4276 else if (inv.IsKnownType())
4278 // Send stream from relay memory
4279 bool pushed = false;
4282 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4283 if (mi != mapRelay.end()) {
4284 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4288 if (!pushed && inv.type == MSG_TX) {
4290 if (mempool.lookup(inv.hash, tx)) {
4291 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4294 pfrom->PushMessage("tx", ss);
4299 vNotFound.push_back(inv);
4303 // Track requests for our stuff.
4304 GetMainSignals().Inventory(inv.hash);
4306 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4311 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4313 if (!vNotFound.empty()) {
4314 // Let the peer know that we didn't find what it asked for, so it doesn't
4315 // have to wait around forever. Currently only SPV clients actually care
4316 // about this message: it's needed when they are recursively walking the
4317 // dependencies of relevant unconfirmed transactions. SPV clients want to
4318 // do that because they want to know about (and store and rebroadcast and
4319 // risk analyze) the dependencies of transactions relevant to them, without
4320 // having to download the entire memory pool.
4321 pfrom->PushMessage("notfound", vNotFound);
4325 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4327 const CChainParams& chainparams = Params();
4328 RandAddSeedPerfmon();
4329 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4330 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4332 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4339 if (strCommand == "version")
4341 // Each connection can only send one version message
4342 if (pfrom->nVersion != 0)
4344 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4345 Misbehaving(pfrom->GetId(), 1);
4352 uint64_t nNonce = 1;
4353 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4354 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4356 // disconnect from peers older than this proto version
4357 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4358 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4359 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4360 pfrom->fDisconnect = true;
4364 if (pfrom->nVersion == 10300)
4365 pfrom->nVersion = 300;
4367 vRecv >> addrFrom >> nNonce;
4368 if (!vRecv.empty()) {
4369 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4370 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4373 vRecv >> pfrom->nStartingHeight;
4375 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4377 pfrom->fRelayTxes = true;
4379 // Disconnect if we connected to ourself
4380 if (nNonce == nLocalHostNonce && nNonce > 1)
4382 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4383 pfrom->fDisconnect = true;
4387 pfrom->addrLocal = addrMe;
4388 if (pfrom->fInbound && addrMe.IsRoutable())
4393 // Be shy and don't send version until we hear
4394 if (pfrom->fInbound)
4395 pfrom->PushVersion();
4397 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4399 // Potentially mark this peer as a preferred download peer.
4400 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4403 pfrom->PushMessage("verack");
4404 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4406 if (!pfrom->fInbound)
4408 // Advertise our address
4409 if (fListen && !IsInitialBlockDownload())
4411 CAddress addr = GetLocalAddress(&pfrom->addr);
4412 if (addr.IsRoutable())
4414 pfrom->PushAddress(addr);
4415 } else if (IsPeerAddrLocalGood(pfrom)) {
4416 addr.SetIP(pfrom->addrLocal);
4417 pfrom->PushAddress(addr);
4421 // Get recent addresses
4422 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4424 pfrom->PushMessage("getaddr");
4425 pfrom->fGetAddr = true;
4427 addrman.Good(pfrom->addr);
4429 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4431 addrman.Add(addrFrom, addrFrom);
4432 addrman.Good(addrFrom);
4439 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4440 item.second.RelayTo(pfrom);
4443 pfrom->fSuccessfullyConnected = true;
4447 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4449 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4450 pfrom->cleanSubVer, pfrom->nVersion,
4451 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4454 int64_t nTimeOffset = nTime - GetTime();
4455 pfrom->nTimeOffset = nTimeOffset;
4456 AddTimeData(pfrom->addr, nTimeOffset);
4460 else if (pfrom->nVersion == 0)
4462 // Must have a version message before anything else
4463 Misbehaving(pfrom->GetId(), 1);
4468 else if (strCommand == "verack")
4470 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4472 // Mark this node as currently connected, so we update its timestamp later.
4473 if (pfrom->fNetworkNode) {
4475 State(pfrom->GetId())->fCurrentlyConnected = true;
4480 else if (strCommand == "addr")
4482 vector<CAddress> vAddr;
4485 // Don't want addr from older versions unless seeding
4486 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4488 if (vAddr.size() > 1000)
4490 Misbehaving(pfrom->GetId(), 20);
4491 return error("message addr size() = %u", vAddr.size());
4494 // Store the new addresses
4495 vector<CAddress> vAddrOk;
4496 int64_t nNow = GetAdjustedTime();
4497 int64_t nSince = nNow - 10 * 60;
4498 BOOST_FOREACH(CAddress& addr, vAddr)
4500 boost::this_thread::interruption_point();
4502 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4503 addr.nTime = nNow - 5 * 24 * 60 * 60;
4504 pfrom->AddAddressKnown(addr);
4505 bool fReachable = IsReachable(addr);
4506 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4508 // Relay to a limited number of other nodes
4511 // Use deterministic randomness to send to the same nodes for 24 hours
4512 // at a time so the addrKnowns of the chosen nodes prevent repeats
4513 static uint256 hashSalt;
4514 if (hashSalt.IsNull())
4515 hashSalt = GetRandHash();
4516 uint64_t hashAddr = addr.GetHash();
4517 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4518 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4519 multimap<uint256, CNode*> mapMix;
4520 BOOST_FOREACH(CNode* pnode, vNodes)
4522 if (pnode->nVersion < CADDR_TIME_VERSION)
4524 unsigned int nPointer;
4525 memcpy(&nPointer, &pnode, sizeof(nPointer));
4526 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4527 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4528 mapMix.insert(make_pair(hashKey, pnode));
4530 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4531 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4532 ((*mi).second)->PushAddress(addr);
4535 // Do not store addresses outside our network
4537 vAddrOk.push_back(addr);
4539 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4540 if (vAddr.size() < 1000)
4541 pfrom->fGetAddr = false;
4542 if (pfrom->fOneShot)
4543 pfrom->fDisconnect = true;
4547 else if (strCommand == "inv")
4551 if (vInv.size() > MAX_INV_SZ)
4553 Misbehaving(pfrom->GetId(), 20);
4554 return error("message inv size() = %u", vInv.size());
4559 std::vector<CInv> vToFetch;
4561 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4563 const CInv &inv = vInv[nInv];
4565 boost::this_thread::interruption_point();
4566 pfrom->AddInventoryKnown(inv);
4568 bool fAlreadyHave = AlreadyHave(inv);
4569 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4571 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4574 if (inv.type == MSG_BLOCK) {
4575 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4576 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4577 // First request the headers preceding the announced block. In the normal fully-synced
4578 // case where a new block is announced that succeeds the current tip (no reorganization),
4579 // there are no such headers.
4580 // Secondly, and only when we are close to being synced, we request the announced block directly,
4581 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4582 // time the block arrives, the header chain leading up to it is already validated. Not
4583 // doing this will result in the received block being rejected as an orphan in case it is
4584 // not a direct successor.
4585 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4586 CNodeState *nodestate = State(pfrom->GetId());
4587 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4588 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4589 vToFetch.push_back(inv);
4590 // Mark block as in flight already, even though the actual "getdata" message only goes out
4591 // later (within the same cs_main lock, though).
4592 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4594 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4598 // Track requests for our stuff
4599 GetMainSignals().Inventory(inv.hash);
4601 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4602 Misbehaving(pfrom->GetId(), 50);
4603 return error("send buffer size() = %u", pfrom->nSendSize);
4607 if (!vToFetch.empty())
4608 pfrom->PushMessage("getdata", vToFetch);
4612 else if (strCommand == "getdata")
4616 if (vInv.size() > MAX_INV_SZ)
4618 Misbehaving(pfrom->GetId(), 20);
4619 return error("message getdata size() = %u", vInv.size());
4622 if (fDebug || (vInv.size() != 1))
4623 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4625 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4626 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4628 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4629 ProcessGetData(pfrom);
4633 else if (strCommand == "getblocks")
4635 CBlockLocator locator;
4637 vRecv >> locator >> hashStop;
4641 // Find the last block the caller has in the main chain
4642 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4644 // Send the rest of the chain
4646 pindex = chainActive.Next(pindex);
4648 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4649 for (; pindex; pindex = chainActive.Next(pindex))
4651 if (pindex->GetBlockHash() == hashStop)
4653 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4656 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4659 // When this block is requested, we'll send an inv that'll
4660 // trigger the peer to getblocks the next batch of inventory.
4661 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4662 pfrom->hashContinue = pindex->GetBlockHash();
4669 else if (strCommand == "getheaders")
4671 CBlockLocator locator;
4673 vRecv >> locator >> hashStop;
4677 if (IsInitialBlockDownload())
4680 CBlockIndex* pindex = NULL;
4681 if (locator.IsNull())
4683 // If locator is null, return the hashStop block
4684 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4685 if (mi == mapBlockIndex.end())
4687 pindex = (*mi).second;
4691 // Find the last block the caller has in the main chain
4692 pindex = FindForkInGlobalIndex(chainActive, locator);
4694 pindex = chainActive.Next(pindex);
4697 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4698 vector<CBlock> vHeaders;
4699 int nLimit = MAX_HEADERS_RESULTS;
4700 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4701 for (; pindex; pindex = chainActive.Next(pindex))
4703 vHeaders.push_back(pindex->GetBlockHeader());
4704 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4707 pfrom->PushMessage("headers", vHeaders);
4711 else if (strCommand == "tx")
4713 vector<uint256> vWorkQueue;
4714 vector<uint256> vEraseQueue;
4718 CInv inv(MSG_TX, tx.GetHash());
4719 pfrom->AddInventoryKnown(inv);
4723 bool fMissingInputs = false;
4724 CValidationState state;
4726 pfrom->setAskFor.erase(inv.hash);
4727 mapAlreadyAskedFor.erase(inv);
4729 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4731 mempool.check(pcoinsTip);
4732 RelayTransaction(tx);
4733 vWorkQueue.push_back(inv.hash);
4735 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4736 pfrom->id, pfrom->cleanSubVer,
4737 tx.GetHash().ToString(),
4738 mempool.mapTx.size());
4740 // Recursively process any orphan transactions that depended on this one
4741 set<NodeId> setMisbehaving;
4742 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4744 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4745 if (itByPrev == mapOrphanTransactionsByPrev.end())
4747 for (set<uint256>::iterator mi = itByPrev->second.begin();
4748 mi != itByPrev->second.end();
4751 const uint256& orphanHash = *mi;
4752 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4753 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4754 bool fMissingInputs2 = false;
4755 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4756 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4757 // anyone relaying LegitTxX banned)
4758 CValidationState stateDummy;
4761 if (setMisbehaving.count(fromPeer))
4763 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4765 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4766 RelayTransaction(orphanTx);
4767 vWorkQueue.push_back(orphanHash);
4768 vEraseQueue.push_back(orphanHash);
4770 else if (!fMissingInputs2)
4773 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4775 // Punish peer that gave us an invalid orphan tx
4776 Misbehaving(fromPeer, nDos);
4777 setMisbehaving.insert(fromPeer);
4778 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4780 // Has inputs but not accepted to mempool
4781 // Probably non-standard or insufficient fee/priority
4782 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4783 vEraseQueue.push_back(orphanHash);
4784 assert(recentRejects);
4785 recentRejects->insert(orphanHash);
4787 mempool.check(pcoinsTip);
4791 BOOST_FOREACH(uint256 hash, vEraseQueue)
4792 EraseOrphanTx(hash);
4794 // TODO: currently, prohibit joinsplits from entering mapOrphans
4795 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4797 AddOrphanTx(tx, pfrom->GetId());
4799 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4800 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4801 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4803 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4805 assert(recentRejects);
4806 recentRejects->insert(tx.GetHash());
4808 if (pfrom->fWhitelisted) {
4809 // Always relay transactions received from whitelisted peers, even
4810 // if they were already in the mempool or rejected from it due
4811 // to policy, allowing the node to function as a gateway for
4812 // nodes hidden behind it.
4814 // Never relay transactions that we would assign a non-zero DoS
4815 // score for, as we expect peers to do the same with us in that
4818 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4819 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4820 RelayTransaction(tx);
4822 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4823 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4828 if (state.IsInvalid(nDoS))
4830 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4831 pfrom->id, pfrom->cleanSubVer,
4832 state.GetRejectReason());
4833 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4834 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4836 Misbehaving(pfrom->GetId(), nDoS);
4841 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4843 std::vector<CBlockHeader> headers;
4845 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4846 unsigned int nCount = ReadCompactSize(vRecv);
4847 if (nCount > MAX_HEADERS_RESULTS) {
4848 Misbehaving(pfrom->GetId(), 20);
4849 return error("headers message size = %u", nCount);
4851 headers.resize(nCount);
4852 for (unsigned int n = 0; n < nCount; n++) {
4853 vRecv >> headers[n];
4854 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4860 // Nothing interesting. Stop asking this peers for more headers.
4864 CBlockIndex *pindexLast = NULL;
4865 BOOST_FOREACH(const CBlockHeader& header, headers) {
4866 CValidationState state;
4867 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4868 Misbehaving(pfrom->GetId(), 20);
4869 return error("non-continuous headers sequence");
4871 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4873 if (state.IsInvalid(nDoS)) {
4875 Misbehaving(pfrom->GetId(), nDoS);
4876 return error("invalid header received");
4882 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4884 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4885 // Headers message had its maximum size; the peer may have more headers.
4886 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4887 // from there instead.
4888 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4889 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4895 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4900 CInv inv(MSG_BLOCK, block.GetHash());
4901 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4903 pfrom->AddInventoryKnown(inv);
4905 CValidationState state;
4906 // Process all blocks from whitelisted peers, even if not requested,
4907 // unless we're still syncing with the network.
4908 // Such an unrequested block may still be processed, subject to the
4909 // conditions in AcceptBlock().
4910 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4911 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4913 if (state.IsInvalid(nDoS)) {
4914 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4915 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4918 Misbehaving(pfrom->GetId(), nDoS);
4925 // This asymmetric behavior for inbound and outbound connections was introduced
4926 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4927 // to users' AddrMan and later request them by sending getaddr messages.
4928 // Making nodes which are behind NAT and can only make outgoing connections ignore
4929 // the getaddr message mitigates the attack.
4930 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4932 // Only send one GetAddr response per connection to reduce resource waste
4933 // and discourage addr stamping of INV announcements.
4934 if (pfrom->fSentAddr) {
4935 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4938 pfrom->fSentAddr = true;
4940 pfrom->vAddrToSend.clear();
4941 vector<CAddress> vAddr = addrman.GetAddr();
4942 BOOST_FOREACH(const CAddress &addr, vAddr)
4943 pfrom->PushAddress(addr);
4947 else if (strCommand == "mempool")
4949 LOCK2(cs_main, pfrom->cs_filter);
4951 std::vector<uint256> vtxid;
4952 mempool.queryHashes(vtxid);
4954 BOOST_FOREACH(uint256& hash, vtxid) {
4955 CInv inv(MSG_TX, hash);
4957 bool fInMemPool = mempool.lookup(hash, tx);
4958 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4959 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4961 vInv.push_back(inv);
4962 if (vInv.size() == MAX_INV_SZ) {
4963 pfrom->PushMessage("inv", vInv);
4967 if (vInv.size() > 0)
4968 pfrom->PushMessage("inv", vInv);
4972 else if (strCommand == "ping")
4974 if (pfrom->nVersion > BIP0031_VERSION)
4978 // Echo the message back with the nonce. This allows for two useful features:
4980 // 1) A remote node can quickly check if the connection is operational
4981 // 2) Remote nodes can measure the latency of the network thread. If this node
4982 // is overloaded it won't respond to pings quickly and the remote node can
4983 // avoid sending us more work, like chain download requests.
4985 // The nonce stops the remote getting confused between different pings: without
4986 // it, if the remote node sends a ping once per second and this node takes 5
4987 // seconds to respond to each, the 5th ping the remote sends would appear to
4988 // return very quickly.
4989 pfrom->PushMessage("pong", nonce);
4994 else if (strCommand == "pong")
4996 int64_t pingUsecEnd = nTimeReceived;
4998 size_t nAvail = vRecv.in_avail();
4999 bool bPingFinished = false;
5000 std::string sProblem;
5002 if (nAvail >= sizeof(nonce)) {
5005 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5006 if (pfrom->nPingNonceSent != 0) {
5007 if (nonce == pfrom->nPingNonceSent) {
5008 // Matching pong received, this ping is no longer outstanding
5009 bPingFinished = true;
5010 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5011 if (pingUsecTime > 0) {
5012 // Successful ping time measurement, replace previous
5013 pfrom->nPingUsecTime = pingUsecTime;
5014 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5016 // This should never happen
5017 sProblem = "Timing mishap";
5020 // Nonce mismatches are normal when pings are overlapping
5021 sProblem = "Nonce mismatch";
5023 // This is most likely a bug in another implementation somewhere; cancel this ping
5024 bPingFinished = true;
5025 sProblem = "Nonce zero";
5029 sProblem = "Unsolicited pong without ping";
5032 // This is most likely a bug in another implementation somewhere; cancel this ping
5033 bPingFinished = true;
5034 sProblem = "Short payload";
5037 if (!(sProblem.empty())) {
5038 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5042 pfrom->nPingNonceSent,
5046 if (bPingFinished) {
5047 pfrom->nPingNonceSent = 0;
5052 else if (fAlerts && strCommand == "alert")
5057 uint256 alertHash = alert.GetHash();
5058 if (pfrom->setKnown.count(alertHash) == 0)
5060 if (alert.ProcessAlert(Params().AlertKey()))
5063 pfrom->setKnown.insert(alertHash);
5066 BOOST_FOREACH(CNode* pnode, vNodes)
5067 alert.RelayTo(pnode);
5071 // Small DoS penalty so peers that send us lots of
5072 // duplicate/expired/invalid-signature/whatever alerts
5073 // eventually get banned.
5074 // This isn't a Misbehaving(100) (immediate ban) because the
5075 // peer might be an older or different implementation with
5076 // a different signature key, etc.
5077 Misbehaving(pfrom->GetId(), 10);
5083 else if (strCommand == "filterload")
5085 CBloomFilter filter;
5088 if (!filter.IsWithinSizeConstraints())
5089 // There is no excuse for sending a too-large filter
5090 Misbehaving(pfrom->GetId(), 100);
5093 LOCK(pfrom->cs_filter);
5094 delete pfrom->pfilter;
5095 pfrom->pfilter = new CBloomFilter(filter);
5096 pfrom->pfilter->UpdateEmptyFull();
5098 pfrom->fRelayTxes = true;
5102 else if (strCommand == "filteradd")
5104 vector<unsigned char> vData;
5107 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5108 // and thus, the maximum size any matched object can have) in a filteradd message
5109 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5111 Misbehaving(pfrom->GetId(), 100);
5113 LOCK(pfrom->cs_filter);
5115 pfrom->pfilter->insert(vData);
5117 Misbehaving(pfrom->GetId(), 100);
5122 else if (strCommand == "filterclear")
5124 LOCK(pfrom->cs_filter);
5125 delete pfrom->pfilter;
5126 pfrom->pfilter = new CBloomFilter();
5127 pfrom->fRelayTxes = true;
5131 else if (strCommand == "reject")
5135 string strMsg; unsigned char ccode; string strReason;
5136 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5139 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5141 if (strMsg == "block" || strMsg == "tx")
5145 ss << ": hash " << hash.ToString();
5147 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5148 } catch (const std::ios_base::failure&) {
5149 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5150 LogPrint("net", "Unparseable reject message received\n");
5154 else if (strCommand == "notfound") {
5155 // We do not care about the NOTFOUND message, but logging an Unknown Command
5156 // message would be undesirable as we transmit it ourselves.
5160 // Ignore unknown commands for extensibility
5161 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5169 // requires LOCK(cs_vRecvMsg)
5170 bool ProcessMessages(CNode* pfrom)
5173 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5177 // (4) message start
5185 if (!pfrom->vRecvGetData.empty())
5186 ProcessGetData(pfrom);
5188 // this maintains the order of responses
5189 if (!pfrom->vRecvGetData.empty()) return fOk;
5191 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5192 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5193 // Don't bother if send buffer is too full to respond anyway
5194 if (pfrom->nSendSize >= SendBufferSize())
5198 CNetMessage& msg = *it;
5201 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5202 // msg.hdr.nMessageSize, msg.vRecv.size(),
5203 // msg.complete() ? "Y" : "N");
5205 // end, if an incomplete message is found
5206 if (!msg.complete())
5209 // at this point, any failure means we can delete the current message
5212 // Scan for message start
5213 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5214 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5220 CMessageHeader& hdr = msg.hdr;
5221 if (!hdr.IsValid(Params().MessageStart()))
5223 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5226 string strCommand = hdr.GetCommand();
5229 unsigned int nMessageSize = hdr.nMessageSize;
5232 CDataStream& vRecv = msg.vRecv;
5233 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5234 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5235 if (nChecksum != hdr.nChecksum)
5237 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5238 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5246 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5247 boost::this_thread::interruption_point();
5249 catch (const std::ios_base::failure& e)
5251 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5252 if (strstr(e.what(), "end of data"))
5254 // Allow exceptions from under-length message on vRecv
5255 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());
5257 else if (strstr(e.what(), "size too large"))
5259 // Allow exceptions from over-long size
5260 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5264 PrintExceptionContinue(&e, "ProcessMessages()");
5267 catch (const boost::thread_interrupted&) {
5270 catch (const std::exception& e) {
5271 PrintExceptionContinue(&e, "ProcessMessages()");
5273 PrintExceptionContinue(NULL, "ProcessMessages()");
5277 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5282 // In case the connection got shut down, its receive buffer was wiped
5283 if (!pfrom->fDisconnect)
5284 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5290 bool SendMessages(CNode* pto, bool fSendTrickle)
5292 const Consensus::Params& consensusParams = Params().GetConsensus();
5294 // Don't send anything until we get its version message
5295 if (pto->nVersion == 0)
5301 bool pingSend = false;
5302 if (pto->fPingQueued) {
5303 // RPC ping request by user
5306 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5307 // Ping automatically sent as a latency probe & keepalive.
5312 while (nonce == 0) {
5313 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5315 pto->fPingQueued = false;
5316 pto->nPingUsecStart = GetTimeMicros();
5317 if (pto->nVersion > BIP0031_VERSION) {
5318 pto->nPingNonceSent = nonce;
5319 pto->PushMessage("ping", nonce);
5321 // Peer is too old to support ping command with nonce, pong will never arrive.
5322 pto->nPingNonceSent = 0;
5323 pto->PushMessage("ping");
5327 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5331 // Address refresh broadcast
5332 static int64_t nLastRebroadcast;
5333 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5336 BOOST_FOREACH(CNode* pnode, vNodes)
5338 // Periodically clear addrKnown to allow refresh broadcasts
5339 if (nLastRebroadcast)
5340 pnode->addrKnown.reset();
5342 // Rebroadcast our address
5343 AdvertizeLocal(pnode);
5345 if (!vNodes.empty())
5346 nLastRebroadcast = GetTime();
5354 vector<CAddress> vAddr;
5355 vAddr.reserve(pto->vAddrToSend.size());
5356 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5358 if (!pto->addrKnown.contains(addr.GetKey()))
5360 pto->addrKnown.insert(addr.GetKey());
5361 vAddr.push_back(addr);
5362 // receiver rejects addr messages larger than 1000
5363 if (vAddr.size() >= 1000)
5365 pto->PushMessage("addr", vAddr);
5370 pto->vAddrToSend.clear();
5372 pto->PushMessage("addr", vAddr);
5375 CNodeState &state = *State(pto->GetId());
5376 if (state.fShouldBan) {
5377 if (pto->fWhitelisted)
5378 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5380 pto->fDisconnect = true;
5381 if (pto->addr.IsLocal())
5382 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5385 CNode::Ban(pto->addr);
5388 state.fShouldBan = false;
5391 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5392 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5393 state.rejects.clear();
5396 if (pindexBestHeader == NULL)
5397 pindexBestHeader = chainActive.Tip();
5398 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.
5399 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5400 // Only actively request headers from a single peer, unless we're close to today.
5401 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5402 state.fSyncStarted = true;
5404 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5405 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5406 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5410 // Resend wallet transactions that haven't gotten in a block yet
5411 // Except during reindex, importing and IBD, when old wallet
5412 // transactions become unconfirmed and spams other nodes.
5413 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5415 GetMainSignals().Broadcast(nTimeBestReceived);
5419 // Message: inventory
5422 vector<CInv> vInvWait;
5424 LOCK(pto->cs_inventory);
5425 vInv.reserve(pto->vInventoryToSend.size());
5426 vInvWait.reserve(pto->vInventoryToSend.size());
5427 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5429 if (pto->setInventoryKnown.count(inv))
5432 // trickle out tx inv to protect privacy
5433 if (inv.type == MSG_TX && !fSendTrickle)
5435 // 1/4 of tx invs blast to all immediately
5436 static uint256 hashSalt;
5437 if (hashSalt.IsNull())
5438 hashSalt = GetRandHash();
5439 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5440 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5441 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5445 vInvWait.push_back(inv);
5450 // returns true if wasn't already contained in the set
5451 if (pto->setInventoryKnown.insert(inv).second)
5453 vInv.push_back(inv);
5454 if (vInv.size() >= 1000)
5456 pto->PushMessage("inv", vInv);
5461 pto->vInventoryToSend = vInvWait;
5464 pto->PushMessage("inv", vInv);
5466 // Detect whether we're stalling
5467 int64_t nNow = GetTimeMicros();
5468 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5469 // Stalling only triggers when the block download window cannot move. During normal steady state,
5470 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5471 // should only happen during initial block download.
5472 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5473 pto->fDisconnect = true;
5475 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5476 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5477 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5478 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5479 // to unreasonably increase our timeout.
5480 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5481 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5482 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5483 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5484 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5485 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5486 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5487 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5488 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5489 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5490 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5492 if (queuedBlock.nTimeDisconnect < nNow) {
5493 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5494 pto->fDisconnect = true;
5499 // Message: getdata (blocks)
5501 vector<CInv> vGetData;
5502 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5503 vector<CBlockIndex*> vToDownload;
5504 NodeId staller = -1;
5505 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5506 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5507 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5508 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5509 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5510 pindex->nHeight, pto->id);
5512 if (state.nBlocksInFlight == 0 && staller != -1) {
5513 if (State(staller)->nStallingSince == 0) {
5514 State(staller)->nStallingSince = nNow;
5515 LogPrint("net", "Stall started peer=%d\n", staller);
5521 // Message: getdata (non-blocks)
5523 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5525 const CInv& inv = (*pto->mapAskFor.begin()).second;
5526 if (!AlreadyHave(inv))
5529 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5530 vGetData.push_back(inv);
5531 if (vGetData.size() >= 1000)
5533 pto->PushMessage("getdata", vGetData);
5537 //If we're not going to ask, don't expect a response.
5538 pto->setAskFor.erase(inv.hash);
5540 pto->mapAskFor.erase(pto->mapAskFor.begin());
5542 if (!vGetData.empty())
5543 pto->PushMessage("getdata", vGetData);
5549 std::string CBlockFileInfo::ToString() const {
5550 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));
5561 BlockMap::iterator it1 = mapBlockIndex.begin();
5562 for (; it1 != mapBlockIndex.end(); it1++)
5563 delete (*it1).second;
5564 mapBlockIndex.clear();
5566 // orphan transactions
5567 mapOrphanTransactions.clear();
5568 mapOrphanTransactionsByPrev.clear();
5570 } instance_of_cmaincleanup;
5572 extern "C" const char* getDataDir()
5574 return GetDataDir().string().c_str();