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"
29 #include "wallet/asyncrpcoperation_sendmany.h"
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/filesystem/fstream.hpp>
36 #include <boost/math/distributions/poisson.hpp>
37 #include <boost/thread.hpp>
38 #include <boost/static_assert.hpp>
43 # error "Zcash cannot be compiled without assertions."
51 CCriticalSection cs_main;
53 BlockMap mapBlockIndex;
55 CBlockIndex *pindexBestHeader = NULL;
56 int64_t nTimeBestReceived = 0;
57 CWaitableCriticalSection csBestBlock;
58 CConditionVariable cvBlockChange;
59 int nScriptCheckThreads = 0;
60 bool fExperimentalMode = false;
61 bool fImporting = false;
62 bool fReindex = false;
63 bool fTxIndex = false;
64 bool fHavePruned = false;
65 bool fPruneMode = false;
66 bool fIsBareMultisigStd = true;
67 bool fCheckBlockIndex = false;
68 bool fCheckpointsEnabled = true;
69 bool fCoinbaseEnforcedProtectionEnabled = true;
70 size_t nCoinCacheUsage = 5000 * 300;
71 uint64_t nPruneTarget = 0;
72 bool fAlerts = DEFAULT_ALERTS;
74 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
75 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
77 CTxMemPool mempool(::minRelayTxFee);
83 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
84 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
85 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
88 * Returns true if there are nRequired or more blocks of minVersion or above
89 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
91 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
92 static void CheckBlockIndex();
94 /** Constant stuff for coinbase transactions we create: */
95 CScript COINBASE_FLAGS;
97 const string strMessageMagic = "Komodo Signed Message:\n";
102 struct CBlockIndexWorkComparator
104 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
105 // First sort by most total work, ...
106 if (pa->nChainWork > pb->nChainWork) return false;
107 if (pa->nChainWork < pb->nChainWork) return true;
109 // ... then by earliest time received, ...
110 if (pa->nSequenceId < pb->nSequenceId) return false;
111 if (pa->nSequenceId > pb->nSequenceId) return true;
113 // Use pointer address as tie breaker (should only happen with blocks
114 // loaded from disk, as those all have id 0).
115 if (pa < pb) return false;
116 if (pa > pb) return true;
123 CBlockIndex *pindexBestInvalid;
126 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
127 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
128 * missing the data for the block.
130 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
131 /** Number of nodes with fSyncStarted. */
132 int nSyncStarted = 0;
133 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
134 * Pruned nodes may have entries where B is missing data.
136 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
138 CCriticalSection cs_LastBlockFile;
139 std::vector<CBlockFileInfo> vinfoBlockFile;
140 int nLastBlockFile = 0;
141 /** Global flag to indicate we should check to see if there are
142 * block/undo files that should be deleted. Set on startup
143 * or if we allocate more file space when we're in prune mode
145 bool fCheckForPruning = false;
148 * Every received block is assigned a unique and increasing identifier, so we
149 * know which one to give priority in case of a fork.
151 CCriticalSection cs_nBlockSequenceId;
152 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
153 uint32_t nBlockSequenceId = 1;
156 * Sources of received blocks, saved to be able to send them reject
157 * messages or ban them when processing happens afterwards. Protected by
160 map<uint256, NodeId> mapBlockSource;
163 * Filter for transactions that were recently rejected by
164 * AcceptToMemoryPool. These are not rerequested until the chain tip
165 * changes, at which point the entire filter is reset. Protected by
168 * Without this filter we'd be re-requesting txs from each of our peers,
169 * increasing bandwidth consumption considerably. For instance, with 100
170 * peers, half of which relay a tx we don't accept, that might be a 50x
171 * bandwidth increase. A flooding attacker attempting to roll-over the
172 * filter using minimum-sized, 60byte, transactions might manage to send
173 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
174 * two minute window to send invs to us.
176 * Decreasing the false positive rate is fairly cheap, so we pick one in a
177 * million to make it highly unlikely for users to have issues with this
182 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
183 uint256 hashRecentRejectsChainTip;
185 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
188 CBlockIndex *pindex; //! Optional.
189 int64_t nTime; //! Time of "getdata" request in microseconds.
190 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
191 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
193 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
195 /** Number of blocks in flight with validated headers. */
196 int nQueuedValidatedHeaders = 0;
198 /** Number of preferable block download peers. */
199 int nPreferredDownload = 0;
201 /** Dirty block index entries. */
202 set<CBlockIndex*> setDirtyBlockIndex;
204 /** Dirty block file entries. */
205 set<int> setDirtyFileInfo;
208 //////////////////////////////////////////////////////////////////////////////
210 // Registration of network node signals.
215 struct CBlockReject {
216 unsigned char chRejectCode;
217 string strRejectReason;
222 * Maintain validation-specific state about nodes, protected by cs_main, instead
223 * by CNode's own locks. This simplifies asynchronous operation, where
224 * processing of incoming data is done after the ProcessMessage call returns,
225 * and we're no longer holding the node's locks.
228 //! The peer's address
230 //! Whether we have a fully established connection.
231 bool fCurrentlyConnected;
232 //! Accumulated misbehaviour score for this peer.
234 //! Whether this peer should be disconnected and banned (unless whitelisted).
236 //! String name of this peer (debugging/logging purposes).
238 //! List of asynchronously-determined block rejections to notify this peer about.
239 std::vector<CBlockReject> rejects;
240 //! The best known block we know this peer has announced.
241 CBlockIndex *pindexBestKnownBlock;
242 //! The hash of the last unknown block this peer has announced.
243 uint256 hashLastUnknownBlock;
244 //! The last full block we both have.
245 CBlockIndex *pindexLastCommonBlock;
246 //! Whether we've started headers synchronization with this peer.
248 //! Since when we're stalling block download progress (in microseconds), or 0.
249 int64_t nStallingSince;
250 list<QueuedBlock> vBlocksInFlight;
252 int nBlocksInFlightValidHeaders;
253 //! Whether we consider this a preferred download peer.
254 bool fPreferredDownload;
257 fCurrentlyConnected = false;
260 pindexBestKnownBlock = NULL;
261 hashLastUnknownBlock.SetNull();
262 pindexLastCommonBlock = NULL;
263 fSyncStarted = false;
266 nBlocksInFlightValidHeaders = 0;
267 fPreferredDownload = false;
271 /** Map maintaining per-node state. Requires cs_main. */
272 map<NodeId, CNodeState> mapNodeState;
275 CNodeState *State(NodeId pnode) {
276 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
277 if (it == mapNodeState.end())
285 return chainActive.Height();
288 void UpdatePreferredDownload(CNode* node, CNodeState* state)
290 nPreferredDownload -= state->fPreferredDownload;
292 // Whether this node should be marked as a preferred download node.
293 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
295 nPreferredDownload += state->fPreferredDownload;
298 // Returns time at which to timeout block request (nTime in microseconds)
299 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
301 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
304 void InitializeNode(NodeId nodeid, const CNode *pnode) {
306 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
307 state.name = pnode->addrName;
308 state.address = pnode->addr;
311 void FinalizeNode(NodeId nodeid) {
313 CNodeState *state = State(nodeid);
315 if (state->fSyncStarted)
318 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
319 AddressCurrentlyConnected(state->address);
322 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
323 mapBlocksInFlight.erase(entry.hash);
324 EraseOrphansFor(nodeid);
325 nPreferredDownload -= state->fPreferredDownload;
327 mapNodeState.erase(nodeid);
330 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)
332 /* int expired = pool.Expire(GetTime() - age);
334 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
336 std::vector<uint256> vNoSpendsRemaining;
337 pool.TrimToSize(limit, &vNoSpendsRemaining);
338 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
339 pcoinsTip->Uncache(removed);*/
343 // Returns a bool indicating whether we requested this block.
344 bool MarkBlockAsReceived(const uint256& hash) {
345 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
346 if (itInFlight != mapBlocksInFlight.end()) {
347 CNodeState *state = State(itInFlight->second.first);
348 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
349 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
350 state->vBlocksInFlight.erase(itInFlight->second.second);
351 state->nBlocksInFlight--;
352 state->nStallingSince = 0;
353 mapBlocksInFlight.erase(itInFlight);
360 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
361 CNodeState *state = State(nodeid);
362 assert(state != NULL);
364 // Make sure it's not listed somewhere already.
365 MarkBlockAsReceived(hash);
367 int64_t nNow = GetTimeMicros();
368 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
369 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
370 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
371 state->nBlocksInFlight++;
372 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
373 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
376 /** Check whether the last unknown block a peer advertized is not yet known. */
377 void ProcessBlockAvailability(NodeId nodeid) {
378 CNodeState *state = State(nodeid);
379 assert(state != NULL);
381 if (!state->hashLastUnknownBlock.IsNull()) {
382 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
383 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0)
385 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
386 state->pindexBestKnownBlock = itOld->second;
387 state->hashLastUnknownBlock.SetNull();
392 /** Update tracking information about which blocks a peer is assumed to have. */
393 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
394 CNodeState *state = State(nodeid);
395 assert(state != NULL);
397 /*ProcessBlockAvailability(nodeid);
399 BlockMap::iterator it = mapBlockIndex.find(hash);
400 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
401 // An actually better block was announced.
402 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
403 state->pindexBestKnownBlock = it->second;
406 // An unknown block was announced; just assume that the latest one is the best one.
407 state->hashLastUnknownBlock = hash;
411 /** Find the last common ancestor two blocks have.
412 * Both pa and pb must be non-NULL. */
413 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
414 if (pa->nHeight > pb->nHeight) {
415 pa = pa->GetAncestor(pb->nHeight);
416 } else if (pb->nHeight > pa->nHeight) {
417 pb = pb->GetAncestor(pa->nHeight);
420 while (pa != pb && pa && pb) {
425 // Eventually all chain branches meet at the genesis block.
430 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
431 * at most count entries. */
432 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
436 vBlocks.reserve(vBlocks.size() + count);
437 CNodeState *state = State(nodeid);
438 assert(state != NULL);
440 // Make sure pindexBestKnownBlock is up to date, we'll need it.
441 ProcessBlockAvailability(nodeid);
443 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
444 // This peer has nothing interesting.
448 if (state->pindexLastCommonBlock == NULL) {
449 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
450 // Guessing wrong in either direction is not a problem.
451 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
454 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
455 // of its current tip anymore. Go back enough to fix that.
456 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
457 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
460 std::vector<CBlockIndex*> vToFetch;
461 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
462 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
463 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
464 // download that next block if the window were 1 larger.
465 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
466 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
467 NodeId waitingfor = -1;
468 while (pindexWalk->nHeight < nMaxHeight) {
469 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
470 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
471 // as iterating over ~100 CBlockIndex* entries anyway.
472 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
473 vToFetch.resize(nToFetch);
474 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
475 vToFetch[nToFetch - 1] = pindexWalk;
476 for (unsigned int i = nToFetch - 1; i > 0; i--) {
477 vToFetch[i - 1] = vToFetch[i]->pprev;
480 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
481 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
482 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
483 // already part of our chain (and therefore don't need it even if pruned).
484 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
485 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
486 // We consider the chain that this peer is on invalid.
489 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
490 if (pindex->nChainTx)
491 state->pindexLastCommonBlock = pindex;
492 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
493 // The block is not already downloaded, and not yet in flight.
494 if (pindex->nHeight > nWindowEnd) {
495 // We reached the end of the window.
496 if (vBlocks.size() == 0 && waitingfor != nodeid) {
497 // We aren't able to fetch anything, but we would be if the download window was one larger.
498 nodeStaller = waitingfor;
502 vBlocks.push_back(pindex);
503 if (vBlocks.size() == count) {
506 } else if (waitingfor == -1) {
507 // This is the first already-in-flight block.
508 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
516 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
518 CNodeState *state = State(nodeid);
521 stats.nMisbehavior = state->nMisbehavior;
522 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
523 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
524 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
526 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
531 void RegisterNodeSignals(CNodeSignals& nodeSignals)
533 nodeSignals.GetHeight.connect(&GetHeight);
534 nodeSignals.ProcessMessages.connect(&ProcessMessages);
535 nodeSignals.SendMessages.connect(&SendMessages);
536 nodeSignals.InitializeNode.connect(&InitializeNode);
537 nodeSignals.FinalizeNode.connect(&FinalizeNode);
540 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
542 nodeSignals.GetHeight.disconnect(&GetHeight);
543 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
544 nodeSignals.SendMessages.disconnect(&SendMessages);
545 nodeSignals.InitializeNode.disconnect(&InitializeNode);
546 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
549 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
551 // Find the first block the caller has in the main chain
552 BOOST_FOREACH(const uint256& hash, locator.vHave) {
553 BlockMap::iterator mi = mapBlockIndex.find(hash);
554 if (mi != mapBlockIndex.end())
556 CBlockIndex* pindex = (*mi).second;
557 if (pindex != 0 && chain.Contains(pindex))
561 return chain.Genesis();
564 CCoinsViewCache *pcoinsTip = NULL;
565 CBlockTreeDB *pblocktree = NULL;
572 //////////////////////////////////////////////////////////////////////////////
574 // mapOrphanTransactions
577 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
579 uint256 hash = tx.GetHash();
580 if (mapOrphanTransactions.count(hash))
583 // Ignore big transactions, to avoid a
584 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
585 // large transaction with a missing parent then we assume
586 // it will rebroadcast it later, after the parent transaction(s)
587 // have been mined or received.
588 // 10,000 orphans, each of which is at most 5,000 bytes big is
589 // at most 500 megabytes of orphans:
590 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
593 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
597 mapOrphanTransactions[hash].tx = tx;
598 mapOrphanTransactions[hash].fromPeer = peer;
599 BOOST_FOREACH(const CTxIn& txin, tx.vin)
600 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
602 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
603 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
607 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
609 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
610 if (it == mapOrphanTransactions.end())
612 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
614 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
615 if (itPrev == mapOrphanTransactionsByPrev.end())
617 itPrev->second.erase(hash);
618 if (itPrev->second.empty())
619 mapOrphanTransactionsByPrev.erase(itPrev);
621 mapOrphanTransactions.erase(it);
624 void EraseOrphansFor(NodeId peer)
627 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
628 while (iter != mapOrphanTransactions.end())
630 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
631 if (maybeErase->second.fromPeer == peer)
633 EraseOrphanTx(maybeErase->second.tx.GetHash());
637 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
641 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
643 unsigned int nEvicted = 0;
644 while (mapOrphanTransactions.size() > nMaxOrphans)
646 // Evict a random orphan:
647 uint256 randomhash = GetRandHash();
648 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
649 if (it == mapOrphanTransactions.end())
650 it = mapOrphanTransactions.begin();
651 EraseOrphanTx(it->first);
663 bool IsStandardTx(const CTransaction& tx, string& reason)
665 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
670 BOOST_FOREACH(const CTxIn& txin, tx.vin)
672 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
673 // keys. (remember the 520 byte limit on redeemScript size) That works
674 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
675 // bytes of scriptSig, which we round off to 1650 bytes for some minor
676 // future-proofing. That's also enough to spend a 20-of-20
677 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
678 // considered standard)
679 if (txin.scriptSig.size() > 1650) {
680 reason = "scriptsig-size";
683 if (!txin.scriptSig.IsPushOnly()) {
684 reason = "scriptsig-not-pushonly";
689 unsigned int v=0,nDataOut = 0;
690 txnouttype whichType;
691 BOOST_FOREACH(const CTxOut& txout, tx.vout)
693 if (!::IsStandard(txout.scriptPubKey, whichType))
695 reason = "scriptpubkey";
696 fprintf(stderr,">>>>>>>>>>>>>>> vout.%d nDataout.%d\n",v,nDataOut);
700 if (whichType == TX_NULL_DATA)
703 //fprintf(stderr,"is OP_RETURN\n");
705 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
706 reason = "bare-multisig";
708 } else if (txout.IsDust(::minRelayTxFee)) {
715 // only one OP_RETURN txout is permitted
717 reason = "multi-op-return";
724 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
727 if (tx.nLockTime == 0)
729 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
731 BOOST_FOREACH(const CTxIn& txin, tx.vin)
733 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)) )
737 else if (!txin.IsFinal())
739 printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime);
746 bool CheckFinalTx(const CTransaction &tx, int flags)
748 AssertLockHeld(cs_main);
750 // By convention a negative value for flags indicates that the
751 // current network-enforced consensus rules should be used. In
752 // a future soft-fork scenario that would mean checking which
753 // rules would be enforced for the next block and setting the
754 // appropriate flags. At the present time no soft-forks are
755 // scheduled, so no flags are set.
756 flags = std::max(flags, 0);
758 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
759 // nLockTime because when IsFinalTx() is called within
760 // CBlock::AcceptBlock(), the height of the block *being*
761 // evaluated is what is used. Thus if we want to know if a
762 // transaction can be part of the *next* block, we need to call
763 // IsFinalTx() with one more than chainActive.Height().
764 const int nBlockHeight = chainActive.Height() + 1;
766 // Timestamps on the other hand don't get any special treatment,
767 // because we can't know what timestamp the next block will have,
768 // and there aren't timestamp applications where it matters.
769 // However this changes once median past time-locks are enforced:
770 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
771 ? chainActive.Tip()->GetMedianTimePast()
774 return IsFinalTx(tx, nBlockHeight, nBlockTime);
778 * Check transaction inputs to mitigate two
779 * potential denial-of-service attacks:
781 * 1. scriptSigs with extra data stuffed into them,
782 * not consumed by scriptPubKey (or P2SH script)
783 * 2. P2SH scripts with a crazy number of expensive
784 * CHECKSIG/CHECKMULTISIG operations
786 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
789 return true; // Coinbases don't use vin normally
791 for (unsigned int i = 0; i < tx.vin.size(); i++)
793 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
795 vector<vector<unsigned char> > vSolutions;
796 txnouttype whichType;
797 // get the scriptPubKey corresponding to this input:
798 const CScript& prevScript = prev.scriptPubKey;
799 if (!Solver(prevScript, whichType, vSolutions))
801 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
802 if (nArgsExpected < 0)
805 // Transactions with extra stuff in their scriptSigs are
806 // non-standard. Note that this EvalScript() call will
807 // be quick, because if there are any operations
808 // beside "push data" in the scriptSig
809 // IsStandardTx() will have already returned false
810 // and this method isn't called.
811 vector<vector<unsigned char> > stack;
812 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
815 if (whichType == TX_SCRIPTHASH)
819 CScript subscript(stack.back().begin(), stack.back().end());
820 vector<vector<unsigned char> > vSolutions2;
821 txnouttype whichType2;
822 if (Solver(subscript, whichType2, vSolutions2))
824 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
827 nArgsExpected += tmpExpected;
831 // Any other Script with less than 15 sigops OK:
832 unsigned int sigops = subscript.GetSigOpCount(true);
833 // ... extra data left on the stack after execution is OK, too:
834 return (sigops <= MAX_P2SH_SIGOPS);
838 if (stack.size() != (unsigned int)nArgsExpected)
845 unsigned int GetLegacySigOpCount(const CTransaction& tx)
847 unsigned int nSigOps = 0;
848 BOOST_FOREACH(const CTxIn& txin, tx.vin)
850 nSigOps += txin.scriptSig.GetSigOpCount(false);
852 BOOST_FOREACH(const CTxOut& txout, tx.vout)
854 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
859 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
864 unsigned int nSigOps = 0;
865 for (unsigned int i = 0; i < tx.vin.size(); i++)
867 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
868 if (prevout.scriptPubKey.IsPayToScriptHash())
869 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
874 bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash::ProofVerifier& verifier)
876 static uint256 array[64]; static int32_t numbanned,indallvouts; int32_t j,k,n;
877 if ( *(int32_t *)&array[0] == 0 )
878 numbanned = komodo_bannedset(&indallvouts,array,(int32_t)(sizeof(array)/sizeof(*array)));
882 for (k=0; k<numbanned; k++)
884 if ( tx.vin[j].prevout.hash == array[k] && (tx.vin[j].prevout.n == 1 || k >= indallvouts) )
886 static uint32_t counter;
887 if ( counter++ < 100 )
888 printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->nHeight,j);
893 // Don't count coinbase transactions because mining skews the count
894 if (!tx.IsCoinBase()) {
895 transactionsValidated.increment();
898 if (!CheckTransactionWithoutProofVerification(tx, state)) {
901 // Ensure that zk-SNARKs verify
902 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
903 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
904 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
905 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
912 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
914 // Basic checks that don't depend on any context
916 // Check transaction version
917 if (tx.nVersion < MIN_TX_VERSION) {
918 return state.DoS(100, error("CheckTransaction(): version too low"),
919 REJECT_INVALID, "bad-txns-version-too-low");
922 // Transactions can contain empty `vin` and `vout` so long as
923 // `vjoinsplit` is non-empty.
924 if (tx.vin.empty() && tx.vjoinsplit.empty())
925 return state.DoS(10, error("CheckTransaction(): vin empty"),
926 REJECT_INVALID, "bad-txns-vin-empty");
927 if (tx.vout.empty() && tx.vjoinsplit.empty())
928 return state.DoS(10, error("CheckTransaction(): vout empty"),
929 REJECT_INVALID, "bad-txns-vout-empty");
932 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
933 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
934 return state.DoS(100, error("CheckTransaction(): size limits failed"),
935 REJECT_INVALID, "bad-txns-oversize");
937 // Check for negative or overflow output values
938 CAmount nValueOut = 0;
939 BOOST_FOREACH(const CTxOut& txout, tx.vout)
941 if (txout.nValue < 0)
942 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
943 REJECT_INVALID, "bad-txns-vout-negative");
944 if (txout.nValue > MAX_MONEY)
946 fprintf(stderr,"%.8f > max %.8f\n",(double)txout.nValue/COIN,(double)MAX_MONEY/COIN);
947 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),REJECT_INVALID, "bad-txns-vout-toolarge");
949 nValueOut += txout.nValue;
950 if (!MoneyRange(nValueOut))
951 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
952 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
955 // Ensure that joinsplit values are well-formed
956 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
958 if (joinsplit.vpub_old < 0) {
959 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
960 REJECT_INVALID, "bad-txns-vpub_old-negative");
963 if (joinsplit.vpub_new < 0) {
964 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
965 REJECT_INVALID, "bad-txns-vpub_new-negative");
968 if (joinsplit.vpub_old > MAX_MONEY) {
969 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
970 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
973 if (joinsplit.vpub_new > MAX_MONEY) {
974 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
975 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
978 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
979 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
980 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
983 nValueOut += joinsplit.vpub_old;
984 if (!MoneyRange(nValueOut)) {
985 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
986 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
990 // Ensure input values do not exceed MAX_MONEY
991 // We have not resolved the txin values at this stage,
992 // but we do know what the joinsplits claim to add
993 // to the value pool.
995 CAmount nValueIn = 0;
996 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
998 nValueIn += it->vpub_new;
1000 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1001 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1002 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1008 // Check for duplicate inputs
1009 set<COutPoint> vInOutPoints;
1010 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1012 if (vInOutPoints.count(txin.prevout))
1013 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1014 REJECT_INVALID, "bad-txns-inputs-duplicate");
1015 vInOutPoints.insert(txin.prevout);
1018 // Check for duplicate joinsplit nullifiers in this transaction
1019 set<uint256> vJoinSplitNullifiers;
1020 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1022 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1024 if (vJoinSplitNullifiers.count(nf))
1025 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1026 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1028 vJoinSplitNullifiers.insert(nf);
1032 if (tx.IsCoinBase())
1034 // There should be no joinsplits in a coinbase transaction
1035 if (tx.vjoinsplit.size() > 0)
1036 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1037 REJECT_INVALID, "bad-cb-has-joinsplits");
1039 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1040 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1041 REJECT_INVALID, "bad-cb-length");
1045 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1046 if (txin.prevout.IsNull())
1047 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1048 REJECT_INVALID, "bad-txns-prevout-null");
1050 if (tx.vjoinsplit.size() > 0) {
1051 // Empty output script.
1053 uint256 dataToBeSigned;
1055 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1056 } catch (std::logic_error ex) {
1057 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1058 REJECT_INVALID, "error-computing-signature-hash");
1061 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1063 // We rely on libsodium to check that the signature is canonical.
1064 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1065 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1066 dataToBeSigned.begin(), 32,
1067 tx.joinSplitPubKey.begin()
1069 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1070 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1078 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1080 extern int32_t KOMODO_ON_DEMAND;
1083 uint256 hash = tx.GetHash();
1084 double dPriorityDelta = 0;
1085 CAmount nFeeDelta = 0;
1086 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1087 if (dPriorityDelta > 0 || nFeeDelta > 0)
1091 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1095 // There is a free transaction area in blocks created by most miners,
1096 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1097 // to be considered to fall into this category. We don't want to encourage sending
1098 // multiple transactions instead of one big transaction to avoid fees.
1099 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1103 if (!MoneyRange(nMinFee))
1104 nMinFee = MAX_MONEY;
1109 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
1111 AssertLockHeld(cs_main);
1112 if (pfMissingInputs)
1113 *pfMissingInputs = false;
1114 auto verifier = libzcash::ProofVerifier::Strict();
1115 if ( komodo_validate_interest(tx,chainActive.Tip()->nHeight+1,chainActive.Tip()->GetMedianTimePast() + 777,0) < 0 )
1117 //fprintf(stderr,"AcceptToMemoryPool komodo_validate_interest failure\n");
1118 return error("AcceptToMemoryPool: komodo_validate_interest failed");
1120 if (!CheckTransaction(tx, state, verifier))
1122 fprintf(stderr,"accept failure.0\n");
1123 return error("AcceptToMemoryPool: CheckTransaction failed");
1125 // Coinbase is only valid in a block, not as a loose transaction
1126 if (tx.IsCoinBase())
1128 fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
1129 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
1131 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1133 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1135 fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str());
1136 return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
1138 // Only accept nLockTime-using transactions that can be mined in the next
1139 // block; we don't want our mempool filled up with transactions that can't
1141 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1143 //fprintf(stderr,"AcceptToMemoryPool reject non-final\n");
1144 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1146 // is it already in the memory pool?
1147 uint256 hash = tx.GetHash();
1148 if (pool.exists(hash))
1150 fprintf(stderr,"already in mempool\n");
1154 // Check for conflicts with in-memory transactions
1156 LOCK(pool.cs); // protect pool.mapNextTx
1157 for (unsigned int i = 0; i < tx.vin.size(); i++)
1159 COutPoint outpoint = tx.vin[i].prevout;
1160 if (pool.mapNextTx.count(outpoint))
1162 static uint32_t counter;
1163 // Disable replacement feature for now
1164 //if ( counter++ < 100 )
1165 fprintf(stderr,"Disable replacement feature for now\n");
1169 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1170 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1171 if (pool.mapNullifiers.count(nf))
1173 fprintf(stderr,"pool.mapNullifiers.count\n");
1182 CCoinsViewCache view(&dummy);
1184 CAmount nValueIn = 0;
1187 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1188 view.SetBackend(viewMemPool);
1190 // do we already have it?
1191 if (view.HaveCoins(hash))
1193 fprintf(stderr,"view.HaveCoins(hash) error\n");
1197 // do all inputs exist?
1198 // Note that this does not check for the presence of actual outputs (see the next check for that),
1199 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1200 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1201 if (!view.HaveCoins(txin.prevout.hash)) {
1202 if (pfMissingInputs)
1203 *pfMissingInputs = true;
1204 //fprintf(stderr,"missing inputs\n");
1209 // are the actual inputs available?
1210 if (!view.HaveInputs(tx))
1212 //fprintf(stderr,"accept failure.1\n");
1213 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent");
1215 // are the joinsplit's requirements met?
1216 if (!view.HaveJoinSplitRequirements(tx))
1218 fprintf(stderr,"accept failure.2\n");
1219 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1222 // Bring the best block into scope
1223 view.GetBestBlock();
1225 nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
1226 if ( 0 && interest != 0 )
1227 fprintf(stderr,"add interest %.8f\n",(double)interest/COIN);
1228 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1229 view.SetBackend(dummy);
1232 // Check for non-standard pay-to-script-hash in inputs
1233 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1235 fprintf(stderr,"accept failure.3\n");
1236 return error("AcceptToMemoryPool: nonstandard transaction input");
1239 // Check that the transaction doesn't have an excessive number of
1240 // sigops, making it impossible to mine. Since the coinbase transaction
1241 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1242 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1243 // merely non-standard transaction.
1244 unsigned int nSigOps = GetLegacySigOpCount(tx);
1245 nSigOps += GetP2SHSigOpCount(tx, view);
1246 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1248 fprintf(stderr,"accept failure.4\n");
1249 return state.DoS(0, error("AcceptToMemoryPool: too many sigops %s, %d > %d", hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1252 CAmount nValueOut = tx.GetValueOut();
1253 CAmount nFees = nValueIn-nValueOut;
1254 double dPriority = view.GetPriority(tx, chainActive.Height());
1256 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1257 unsigned int nSize = entry.GetTxSize();
1259 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1260 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1261 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1263 // Don't accept it if it can't get into a block
1264 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1265 if (fLimitFree && nFees < txMinFee)
1267 fprintf(stderr,"accept failure.5\n");
1268 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee");
1272 // Require that free transactions have sufficient priority to be mined in the next block.
1273 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1274 fprintf(stderr,"accept failure.6\n");
1275 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1278 // Continuously rate-limit free (really, very-low-fee) transactions
1279 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1280 // be annoying or make others' transactions take longer to confirm.
1281 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1283 static CCriticalSection csFreeLimiter;
1284 static double dFreeCount;
1285 static int64_t nLastTime;
1286 int64_t nNow = GetTime();
1288 LOCK(csFreeLimiter);
1290 // Use an exponentially decaying ~10-minute window:
1291 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1293 // -limitfreerelay unit is thousand-bytes-per-minute
1294 // At default rate it would take over a month to fill 1GB
1295 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1297 fprintf(stderr,"accept failure.7\n");
1298 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1300 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1301 dFreeCount += nSize;
1304 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000 && nFees > nValueOut/20 )
1306 fprintf(stderr,"accept failure.8\n");
1307 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1310 // Check against previous transactions
1311 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1312 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1314 fprintf(stderr,"accept failure.9\n");
1315 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1318 // Check again against just the consensus-critical mandatory script
1319 // verification flags, in case of bugs in the standard flags that cause
1320 // transactions to pass as valid when they're actually invalid. For
1321 // instance the STRICTENC flag was incorrectly allowing certain
1322 // CHECKSIG NOT scripts to pass, even though they were invalid.
1324 // There is a similar check in CreateNewBlock() to prevent creating
1325 // invalid blocks, however allowing such transactions into the mempool
1326 // can be exploited as a DoS attack.
1327 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1329 fprintf(stderr,"accept failure.10\n");
1330 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1333 // Store transaction in memory
1334 if ( komodo_is_notarytx(tx) == 0 )
1336 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1339 SyncWithWallets(tx, NULL);
1344 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1345 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1347 CBlockIndex *pindexSlow = NULL;
1351 if (mempool.lookup(hash, txOut))
1358 if (pblocktree->ReadTxIndex(hash, postx)) {
1359 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1361 return error("%s: OpenBlockFile failed", __func__);
1362 CBlockHeader header;
1365 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1367 } catch (const std::exception& e) {
1368 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1370 hashBlock = header.GetHash();
1371 if (txOut.GetHash() != hash)
1372 return error("%s: txid mismatch", __func__);
1377 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1380 CCoinsViewCache &view = *pcoinsTip;
1381 const CCoins* coins = view.AccessCoins(hash);
1383 nHeight = coins->nHeight;
1386 pindexSlow = chainActive[nHeight];
1391 if (ReadBlockFromDisk(block, pindexSlow)) {
1392 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1393 if (tx.GetHash() == hash) {
1395 hashBlock = pindexSlow->GetBlockHash();
1405 /*char *komodo_getspendscript(uint256 hash,int32_t n)
1407 CTransaction tx; uint256 hashBlock;
1408 if ( !GetTransaction(hash,tx,hashBlock,true) )
1410 printf("null GetTransaction\n");
1413 if ( n >= 0 && n < tx.vout.size() )
1414 return((char *)tx.vout[n].scriptPubKey.ToString().c_str());
1415 else printf("getspendscript illegal n.%d\n",n);
1420 //////////////////////////////////////////////////////////////////////////////
1422 // CBlock and CBlockIndex
1425 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1427 // Open history file to append
1428 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1429 if (fileout.IsNull())
1430 return error("WriteBlockToDisk: OpenBlockFile failed");
1432 // Write index header
1433 unsigned int nSize = fileout.GetSerializeSize(block);
1434 fileout << FLATDATA(messageStart) << nSize;
1437 long fileOutPos = ftell(fileout.Get());
1439 return error("WriteBlockToDisk: ftell failed");
1440 pos.nPos = (unsigned int)fileOutPos;
1446 bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos)
1448 uint8_t pubkey33[33];
1451 // Open history file to read
1452 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1453 if (filein.IsNull())
1455 //fprintf(stderr,"readblockfromdisk err A\n");
1456 return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1463 catch (const std::exception& e) {
1464 fprintf(stderr,"readblockfromdisk err B\n");
1465 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1468 komodo_block2pubkey33(pubkey33,block);
1469 if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus())))
1471 int32_t i; for (i=0; i<33; i++)
1472 printf("%02x",pubkey33[i]);
1473 fprintf(stderr," warning unexpected diff at ht.%d\n",height);
1475 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1480 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1484 if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos()))
1486 if (block.GetHash() != pindex->GetBlockHash())
1487 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1488 pindex->ToString(), pindex->GetBlockPos().ToString());
1492 uint64_t komodo_moneysupply(int32_t height);
1493 extern char ASSETCHAINS_SYMBOL[16];
1494 extern uint32_t ASSETCHAINS_MAGIC;
1495 extern uint64_t ASSETCHAINS_SUPPLY;
1497 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1499 CAmount nSubsidy = 3 * COIN;
1500 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1503 return(100000000 * COIN); // ICO allocation
1504 else if ( komodo_moneysupply(nHeight) < MAX_MONEY )
1511 return(ASSETCHAINS_SUPPLY * COIN + (ASSETCHAINS_MAGIC & 0xffffff));
1515 // Mining slow start
1516 // The subsidy is ramped up linearly, skipping the middle payout of
1517 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1518 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1519 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1520 nSubsidy *= nHeight;
1522 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1523 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1524 nSubsidy *= (nHeight+1);
1528 assert(nHeight > consensusParams.SubsidySlowStartShift());
1529 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/
1530 // Force block reward to zero when right shift is undefined.
1531 //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1532 //if (halvings >= 64)
1535 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1536 //nSubsidy >>= halvings;
1540 bool IsInitialBlockDownload()
1542 const CChainParams& chainParams = Params();
1544 if (fImporting || fReindex)
1546 //fprintf(stderr,"IsInitialBlockDownload: fImporting %d || %d fReindex\n",(int32_t)fImporting,(int32_t)fReindex);
1549 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1551 //fprintf(stderr,"IsInitialBlockDownload: checkpoint -> initialdownload\n");
1554 static bool lockIBDState = false;
1557 //fprintf(stderr,"lockIBDState true %d < %d\n",chainActive.Height(),pindexBestHeader->nHeight - 10);
1560 bool state; CBlockIndex *ptr = chainActive.Tip();
1562 ptr = pindexBestHeader;
1563 else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight )
1564 ptr = pindexBestHeader;
1565 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1566 state = ((chainActive.Height() < ptr->nHeight - 24*60) ||
1567 ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge()));
1568 else state = (chainActive.Height() < ptr->nHeight - 3);
1569 //fprintf(stderr,"state.%d ht.%d vs %d, t.%u %u\n",state,(int32_t)chainActive.Height(),(uint32_t)ptr->nHeight,(int32_t)ptr->GetBlockTime(),(uint32_t)(GetTime() - chainParams.MaxTipAge()));
1572 lockIBDState = true;
1577 bool fLargeWorkForkFound = false;
1578 bool fLargeWorkInvalidChainFound = false;
1579 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1581 void CheckForkWarningConditions()
1583 AssertLockHeld(cs_main);
1584 // Before we get past initial download, we cannot reliably alert about forks
1585 // (we assume we don't get stuck on a fork before the last checkpoint)
1586 if (IsInitialBlockDownload())
1589 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1590 // of our head, drop it
1591 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1592 pindexBestForkTip = NULL;
1594 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1596 if (!fLargeWorkForkFound && pindexBestForkBase)
1598 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1599 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1600 CAlert::Notify(warning, true);
1602 if (pindexBestForkTip && pindexBestForkBase)
1604 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__,
1605 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1606 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1607 fLargeWorkForkFound = true;
1611 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1612 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1613 CAlert::Notify(warning, true);
1614 fLargeWorkInvalidChainFound = true;
1619 fLargeWorkForkFound = false;
1620 fLargeWorkInvalidChainFound = false;
1624 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1626 AssertLockHeld(cs_main);
1627 // If we are on a fork that is sufficiently large, set a warning flag
1628 CBlockIndex* pfork = pindexNewForkTip;
1629 CBlockIndex* plonger = chainActive.Tip();
1630 while (pfork && pfork != plonger)
1632 while (plonger && plonger->nHeight > pfork->nHeight)
1633 plonger = plonger->pprev;
1634 if (pfork == plonger)
1636 pfork = pfork->pprev;
1639 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1640 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1641 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1642 // hash rate operating on the fork.
1643 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1644 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1645 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1646 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1647 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1648 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1650 pindexBestForkTip = pindexNewForkTip;
1651 pindexBestForkBase = pfork;
1654 CheckForkWarningConditions();
1657 // Requires cs_main.
1658 void Misbehaving(NodeId pnode, int howmuch)
1663 CNodeState *state = State(pnode);
1667 state->nMisbehavior += howmuch;
1668 int banscore = GetArg("-banscore", 100);
1669 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1671 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1672 state->fShouldBan = true;
1674 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1677 void static InvalidChainFound(CBlockIndex* pindexNew)
1679 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1680 pindexBestInvalid = pindexNew;
1682 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1683 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1684 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1685 pindexNew->GetBlockTime()));
1686 CBlockIndex *tip = chainActive.Tip();
1688 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1689 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1690 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1691 CheckForkWarningConditions();
1694 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1696 if (state.IsInvalid(nDoS)) {
1697 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1698 if (it != mapBlockSource.end() && State(it->second)) {
1699 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1700 State(it->second)->rejects.push_back(reject);
1702 Misbehaving(it->second, nDoS);
1705 if (!state.CorruptionPossible()) {
1706 pindex->nStatus |= BLOCK_FAILED_VALID;
1707 setDirtyBlockIndex.insert(pindex);
1708 setBlockIndexCandidates.erase(pindex);
1709 InvalidChainFound(pindex);
1713 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1715 if (!tx.IsCoinBase()) // mark inputs spent
1717 txundo.vprevout.reserve(tx.vin.size());
1718 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1719 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1720 unsigned nPos = txin.prevout.n;
1722 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1724 // mark an outpoint spent, and construct undo information
1725 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1727 if (coins->vout.size() == 0) {
1728 CTxInUndo& undo = txundo.vprevout.back();
1729 undo.nHeight = coins->nHeight;
1730 undo.fCoinBase = coins->fCoinBase;
1731 undo.nVersion = coins->nVersion;
1735 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { // spend nullifiers
1736 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1737 inputs.SetNullifier(nf, true);
1740 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); // add outputs
1743 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1746 UpdateCoins(tx, state, inputs, txundo, nHeight);
1749 bool CScriptCheck::operator()() {
1750 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1751 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1752 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1757 int GetSpendHeight(const CCoinsViewCache& inputs)
1760 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1761 return pindexPrev->nHeight + 1;
1764 namespace Consensus {
1765 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1767 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1768 // for an attacker to attempt to split the network.
1769 if (!inputs.HaveInputs(tx))
1770 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1772 // are the JoinSplit's requirements met?
1773 if (!inputs.HaveJoinSplitRequirements(tx))
1774 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1776 CAmount nValueIn = 0;
1778 for (unsigned int i = 0; i < tx.vin.size(); i++)
1780 const COutPoint &prevout = tx.vin[i].prevout;
1781 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1784 if (coins->IsCoinBase()) {
1785 // Ensure that coinbases are matured
1786 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1787 return state.Invalid(
1788 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1789 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1792 // Ensure that coinbases cannot be spent to transparent outputs
1793 // Disabled on regtest
1794 if (fCoinbaseEnforcedProtectionEnabled &&
1795 consensusParams.fCoinbaseMustBeProtected &&
1797 return state.Invalid(
1798 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1799 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1803 // Check for negative or overflow input values
1804 nValueIn += coins->vout[prevout.n].nValue;
1805 #ifdef KOMODO_ENABLE_INTEREST
1806 if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 )
1808 if ( coins->vout[prevout.n].nValue >= 10*COIN )
1810 int64_t interest; int32_t txheight; uint32_t locktime;
1811 if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue)) != 0 )
1813 //printf("checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime);
1814 //fprintf(stderr,"checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime);
1815 nValueIn += interest;
1820 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1821 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1822 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1826 nValueIn += tx.GetJoinSplitValueIn();
1827 if (!MoneyRange(nValueIn))
1828 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1829 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1831 if (nValueIn < tx.GetValueOut())
1832 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f",
1833 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout");
1835 // Tally transaction fees
1836 CAmount nTxFee = nValueIn - tx.GetValueOut();
1838 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1839 REJECT_INVALID, "bad-txns-fee-negative");
1841 if (!MoneyRange(nFees))
1842 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1843 REJECT_INVALID, "bad-txns-fee-outofrange");
1846 }// namespace Consensus
1848 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)
1850 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams))
1853 if (!tx.IsCoinBase())
1856 pvChecks->reserve(tx.vin.size());
1858 // The first loop above does all the inexpensive checks.
1859 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1860 // Helps prevent CPU exhaustion attacks.
1862 // Skip ECDSA signature verification when connecting blocks
1863 // before the last block chain checkpoint. This is safe because block merkle hashes are
1864 // still computed and checked, and any change will be caught at the next checkpoint.
1865 if (fScriptChecks) {
1866 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1867 const COutPoint &prevout = tx.vin[i].prevout;
1868 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1872 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1874 pvChecks->push_back(CScriptCheck());
1875 check.swap(pvChecks->back());
1876 } else if (!check()) {
1877 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1878 // Check whether the failure was caused by a
1879 // non-mandatory script verification check, such as
1880 // non-standard DER encodings or non-null dummy
1881 // arguments; if so, don't trigger DoS protection to
1882 // avoid splitting the network between upgraded and
1883 // non-upgraded nodes.
1884 CScriptCheck check(*coins, tx, i,
1885 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1887 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1889 // Failures of other flags indicate a transaction that is
1890 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1891 // such nodes as they are not following the protocol. That
1892 // said during an upgrade careful thought should be taken
1893 // as to the correct behavior - we may want to continue
1894 // peering with non-upgraded nodes even after a soft-fork
1895 // super-majority vote has passed.
1896 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1906 /*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)
1908 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1909 fprintf(stderr,"ContextualCheckInputs failure.0\n");
1913 if (!tx.IsCoinBase())
1915 // While checking, GetBestBlock() refers to the parent block.
1916 // This is also true for mempool checks.
1917 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1918 int nSpendHeight = pindexPrev->nHeight + 1;
1919 for (unsigned int i = 0; i < tx.vin.size(); i++)
1921 const COutPoint &prevout = tx.vin[i].prevout;
1922 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1923 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1927 // If prev is coinbase, check that it's matured
1928 if (coins->IsCoinBase()) {
1929 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1930 COINBASE_MATURITY = _COINBASE_MATURITY;
1931 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1932 fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size());
1934 return state.Invalid(
1935 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1946 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1948 // Open history file to append
1949 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1950 if (fileout.IsNull())
1951 return error("%s: OpenUndoFile failed", __func__);
1953 // Write index header
1954 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1955 fileout << FLATDATA(messageStart) << nSize;
1958 long fileOutPos = ftell(fileout.Get());
1960 return error("%s: ftell failed", __func__);
1961 pos.nPos = (unsigned int)fileOutPos;
1962 fileout << blockundo;
1964 // calculate & write checksum
1965 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1966 hasher << hashBlock;
1967 hasher << blockundo;
1968 fileout << hasher.GetHash();
1973 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1975 // Open history file to read
1976 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1977 if (filein.IsNull())
1978 return error("%s: OpenBlockFile failed", __func__);
1981 uint256 hashChecksum;
1983 filein >> blockundo;
1984 filein >> hashChecksum;
1986 catch (const std::exception& e) {
1987 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1991 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1992 hasher << hashBlock;
1993 hasher << blockundo;
1994 if (hashChecksum != hasher.GetHash())
1995 return error("%s: Checksum mismatch", __func__);
2000 /** Abort with a message */
2001 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2003 strMiscWarning = strMessage;
2004 LogPrintf("*** %s\n", strMessage);
2005 uiInterface.ThreadSafeMessageBox(
2006 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2007 "", CClientUIInterface::MSG_ERROR);
2012 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2014 AbortNode(strMessage, userMessage);
2015 return state.Error(strMessage);
2021 * Apply the undo operation of a CTxInUndo to the given chain state.
2022 * @param undo The undo object.
2023 * @param view The coins view to which to apply the changes.
2024 * @param out The out point that corresponds to the tx input.
2025 * @return True on success.
2027 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2031 CCoinsModifier coins = view.ModifyCoins(out.hash);
2032 if (undo.nHeight != 0) {
2033 // undo data contains height: this is the last output of the prevout tx being spent
2034 if (!coins->IsPruned())
2035 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2037 coins->fCoinBase = undo.fCoinBase;
2038 coins->nHeight = undo.nHeight;
2039 coins->nVersion = undo.nVersion;
2041 if (coins->IsPruned())
2042 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2044 if (coins->IsAvailable(out.n))
2045 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2046 if (coins->vout.size() < out.n+1)
2047 coins->vout.resize(out.n+1);
2048 coins->vout[out.n] = undo.txout;
2053 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2055 assert(pindex->GetBlockHash() == view.GetBestBlock());
2061 komodo_disconnect(pindex,block);
2062 CBlockUndo blockUndo;
2063 CDiskBlockPos pos = pindex->GetUndoPos();
2065 return error("DisconnectBlock(): no undo data available");
2066 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2067 return error("DisconnectBlock(): failure reading undo data");
2069 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2070 return error("DisconnectBlock(): block and undo data inconsistent");
2072 // undo transactions in reverse order
2073 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2074 const CTransaction &tx = block.vtx[i];
2075 uint256 hash = tx.GetHash();
2077 // Check that all outputs are available and match the outputs in the block itself
2080 CCoinsModifier outs = view.ModifyCoins(hash);
2081 outs->ClearUnspendable();
2083 CCoins outsBlock(tx, pindex->nHeight);
2084 // The CCoins serialization does not serialize negative numbers.
2085 // No network rules currently depend on the version here, so an inconsistency is harmless
2086 // but it must be corrected before txout nversion ever influences a network rule.
2087 if (outsBlock.nVersion < 0)
2088 outs->nVersion = outsBlock.nVersion;
2089 if (*outs != outsBlock)
2090 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2096 // unspend nullifiers
2097 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2098 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2099 view.SetNullifier(nf, false);
2104 if (i > 0) { // not coinbases
2105 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2106 if (txundo.vprevout.size() != tx.vin.size())
2107 return error("DisconnectBlock(): transaction and undo data inconsistent");
2108 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2109 const COutPoint &out = tx.vin[j].prevout;
2110 const CTxInUndo &undo = txundo.vprevout[j];
2111 if (!ApplyTxInUndo(undo, view, out))
2117 // set the old best anchor back
2118 view.PopAnchor(blockUndo.old_tree_root);
2120 // move best block pointer to prevout block
2121 view.SetBestBlock(pindex->pprev->GetBlockHash());
2131 void static FlushBlockFile(bool fFinalize = false)
2133 LOCK(cs_LastBlockFile);
2135 CDiskBlockPos posOld(nLastBlockFile, 0);
2137 FILE *fileOld = OpenBlockFile(posOld);
2140 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2141 FileCommit(fileOld);
2145 fileOld = OpenUndoFile(posOld);
2148 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2149 FileCommit(fileOld);
2154 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2156 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2158 void ThreadScriptCheck() {
2159 RenameThread("zcash-scriptch");
2160 scriptcheckqueue.Thread();
2164 // Called periodically asynchronously; alerts if it smells like
2165 // we're being fed a bad chain (blocks being generated much
2166 // too slowly or too quickly).
2168 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2169 int64_t nPowTargetSpacing)
2171 if (bestHeader == NULL || initialDownloadCheck()) return;
2173 static int64_t lastAlertTime = 0;
2174 int64_t now = GetAdjustedTime();
2175 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2177 const int SPAN_HOURS=4;
2178 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2179 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2181 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2183 std::string strWarning;
2184 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2187 const CBlockIndex* i = bestHeader;
2189 while (i->GetBlockTime() >= startTime) {
2192 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2195 // How likely is it to find that many by chance?
2196 double p = boost::math::pdf(poisson, nBlocks);
2198 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2199 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2201 // Aim for one false-positive about every fifty years of normal running:
2202 const int FIFTY_YEARS = 50*365*24*60*60;
2203 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2205 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2207 // Many fewer blocks than expected: alert!
2208 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2209 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2211 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2213 // Many more blocks than expected: alert!
2214 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2215 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2217 if (!strWarning.empty())
2219 strMiscWarning = strWarning;
2220 CAlert::Notify(strWarning, true);
2221 lastAlertTime = now;
2225 static int64_t nTimeVerify = 0;
2226 static int64_t nTimeConnect = 0;
2227 static int64_t nTimeIndex = 0;
2228 static int64_t nTimeCallbacks = 0;
2229 static int64_t nTimeTotal = 0;
2231 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2233 const CChainParams& chainparams = Params();
2234 AssertLockHeld(cs_main);
2236 // Check it again in case a previous version let a bad block in
2237 bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2240 bool fExpensiveChecks = true;
2241 if (fCheckpointsEnabled) {
2242 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2243 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2244 // This block is an ancestor of a checkpoint: disable script checks
2245 fExpensiveChecks = false;
2248 //>>>>>>> zcash/master
2249 auto verifier = libzcash::ProofVerifier::Strict();
2250 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2252 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2253 if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2256 // verify that the view's current state corresponds to the previous block
2257 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2258 assert(hashPrevBlock == view.GetBestBlock());
2260 // Special case for the genesis block, skipping connection of its transactions
2261 // (its coinbase is unspendable)
2262 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2264 view.SetBestBlock(pindex->GetBlockHash());
2265 // Before the genesis block, there was an empty tree
2266 ZCIncrementalMerkleTree tree;
2267 pindex->hashAnchor = tree.root();
2268 // The genesis block contained no JoinSplits
2269 pindex->hashAnchorEnd = pindex->hashAnchor;
2274 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2275 //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet"
2277 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2278 // unless those are already completely spent.
2279 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2280 const CCoins* coins = view.AccessCoins(tx.GetHash());
2281 if (coins && !coins->IsPruned())
2282 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2283 REJECT_INVALID, "bad-txns-BIP30");
2286 unsigned int flags = SCRIPT_VERIFY_P2SH;
2288 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2289 // when 75% of the network has upgraded:
2290 if (block.nVersion >= 3) {
2291 flags |= SCRIPT_VERIFY_DERSIG;
2294 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2295 // blocks, when 75% of the network has upgraded:
2296 if (block.nVersion >= 4) {
2297 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2300 CBlockUndo blockundo;
2302 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2304 int64_t nTimeStart = GetTimeMicros();
2307 int64_t interest,sum = 0;
2308 unsigned int nSigOps = 0;
2309 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2310 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2311 vPos.reserve(block.vtx.size());
2312 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2314 // Construct the incremental merkle tree at the current
2316 auto old_tree_root = view.GetBestAnchor();
2317 // saving the top anchor in the block index as we go.
2319 pindex->hashAnchor = old_tree_root;
2321 ZCIncrementalMerkleTree tree;
2322 // This should never fail: we should always be able to get the root
2323 // that is on the tip of our chain
2324 assert(view.GetAnchorAt(old_tree_root, tree));
2327 // Consistency check: the root of the tree we're given should
2328 // match what we asked for.
2329 assert(tree.root() == old_tree_root);
2332 for (unsigned int i = 0; i < block.vtx.size(); i++)
2334 const CTransaction &tx = block.vtx[i];
2335 nInputs += tx.vin.size();
2336 nSigOps += GetLegacySigOpCount(tx);
2337 if (nSigOps > MAX_BLOCK_SIGOPS)
2338 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2339 REJECT_INVALID, "bad-blk-sigops");
2340 //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
2341 if (!tx.IsCoinBase())
2343 if (!view.HaveInputs(tx))
2344 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2345 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2347 // are the JoinSplit's requirements met?
2348 if (!view.HaveJoinSplitRequirements(tx))
2349 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2350 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2352 // Add in sigops done by pay-to-script-hash inputs;
2353 // this is to prevent a "rogue miner" from creating
2354 // an incredibly-expensive-to-validate block.
2355 nSigOps += GetP2SHSigOpCount(tx, view);
2356 if (nSigOps > MAX_BLOCK_SIGOPS)
2357 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2358 REJECT_INVALID, "bad-blk-sigops");
2360 nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
2362 std::vector<CScriptCheck> vChecks;
2363 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2365 control.Add(vChecks);
2367 komodo_earned_interest(pindex->nHeight,sum);
2370 blockundo.vtxundo.push_back(CTxUndo());
2372 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2374 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2375 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2376 // Insert the note commitments into our temporary tree.
2378 tree.append(note_commitment);
2382 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2383 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2386 view.PushAnchor(tree);
2388 pindex->hashAnchorEnd = tree.root();
2390 blockundo.old_tree_root = old_tree_root;
2392 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2393 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);
2395 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2396 if (block.vtx[0].vout[0].nValue > blockReward)
2397 //if (block.vtx[0].GetValueOut() > blockReward)
2398 return state.DoS(100,
2399 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2400 block.vtx[0].GetValueOut(), blockReward),
2401 REJECT_INVALID, "bad-cb-amount");
2403 if (!control.Wait())
2404 return state.DoS(100, false);
2405 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2406 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);
2411 // Write undo information to disk
2412 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2414 if (pindex->GetUndoPos().IsNull()) {
2416 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2417 return error("ConnectBlock(): FindUndoPos failed");
2418 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2419 return AbortNode(state, "Failed to write undo data");
2421 // update nUndoPos in block index
2422 pindex->nUndoPos = pos.nPos;
2423 pindex->nStatus |= BLOCK_HAVE_UNDO;
2426 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2427 setDirtyBlockIndex.insert(pindex);
2431 if (!pblocktree->WriteTxIndex(vPos))
2432 return AbortNode(state, "Failed to write transaction index");
2434 // add this block to the view's block chain
2435 view.SetBestBlock(pindex->GetBlockHash());
2437 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2438 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2440 // Watch for changes to the previous coinbase transaction.
2441 static uint256 hashPrevBestCoinBase;
2442 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2443 hashPrevBestCoinBase = block.vtx[0].GetHash();
2445 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2446 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2448 //FlushStateToDisk();
2449 komodo_connectblock(pindex,*(CBlock *)&block);
2453 enum FlushStateMode {
2455 FLUSH_STATE_IF_NEEDED,
2456 FLUSH_STATE_PERIODIC,
2461 * Update the on-disk chain state.
2462 * The caches and indexes are flushed depending on the mode we're called with
2463 * if they're too large, if it's been a while since the last write,
2464 * or always and in all cases if we're in prune mode and are deleting files.
2466 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2467 LOCK2(cs_main, cs_LastBlockFile);
2468 static int64_t nLastWrite = 0;
2469 static int64_t nLastFlush = 0;
2470 static int64_t nLastSetChain = 0;
2471 std::set<int> setFilesToPrune;
2472 bool fFlushForPrune = false;
2474 if (fPruneMode && fCheckForPruning && !fReindex) {
2475 FindFilesToPrune(setFilesToPrune);
2476 fCheckForPruning = false;
2477 if (!setFilesToPrune.empty()) {
2478 fFlushForPrune = true;
2480 pblocktree->WriteFlag("prunedblockfiles", true);
2485 int64_t nNow = GetTimeMicros();
2486 // Avoid writing/flushing immediately after startup.
2487 if (nLastWrite == 0) {
2490 if (nLastFlush == 0) {
2493 if (nLastSetChain == 0) {
2494 nLastSetChain = nNow;
2496 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2497 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2498 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2499 // The cache is over the limit, we have to write now.
2500 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2501 // 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.
2502 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2503 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2504 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2505 // Combine all conditions that result in a full cache flush.
2506 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2507 // Write blocks and block index to disk.
2508 if (fDoFullFlush || fPeriodicWrite) {
2509 // Depend on nMinDiskSpace to ensure we can write block index
2510 if (!CheckDiskSpace(0))
2511 return state.Error("out of disk space");
2512 // First make sure all block and undo data is flushed to disk.
2514 // Then update all block file information (which may refer to block and undo files).
2516 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2517 vFiles.reserve(setDirtyFileInfo.size());
2518 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2519 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2520 setDirtyFileInfo.erase(it++);
2522 std::vector<const CBlockIndex*> vBlocks;
2523 vBlocks.reserve(setDirtyBlockIndex.size());
2524 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2525 vBlocks.push_back(*it);
2526 setDirtyBlockIndex.erase(it++);
2528 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2529 return AbortNode(state, "Files to write to block index database");
2532 // Finally remove any pruned files
2534 UnlinkPrunedFiles(setFilesToPrune);
2537 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2539 // Typical CCoins structures on disk are around 128 bytes in size.
2540 // Pushing a new one to the database can cause it to be written
2541 // twice (once in the log, and once in the tables). This is already
2542 // an overestimation, as most will delete an existing entry or
2543 // overwrite one. Still, use a conservative safety factor of 2.
2544 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2545 return state.Error("out of disk space");
2546 // Flush the chainstate (which may refer to block index entries).
2547 if (!pcoinsTip->Flush())
2548 return AbortNode(state, "Failed to write to coin database");
2551 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2552 // Update best block in wallet (so we can detect restored wallets).
2553 GetMainSignals().SetBestChain(chainActive.GetLocator());
2554 nLastSetChain = nNow;
2556 } catch (const std::runtime_error& e) {
2557 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2562 void FlushStateToDisk() {
2563 CValidationState state;
2564 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2567 void PruneAndFlush() {
2568 CValidationState state;
2569 fCheckForPruning = true;
2570 FlushStateToDisk(state, FLUSH_STATE_NONE);
2573 /** Update chainActive and related internal data structures. */
2574 void static UpdateTip(CBlockIndex *pindexNew) {
2575 const CChainParams& chainParams = Params();
2576 chainActive.SetTip(pindexNew);
2579 nTimeBestReceived = GetTime();
2580 mempool.AddTransactionsUpdated(1);
2582 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2583 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2584 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2585 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2587 cvBlockChange.notify_all();
2589 // Check the version of the last 100 blocks to see if we need to upgrade:
2590 static bool fWarned = false;
2591 if (!IsInitialBlockDownload() && !fWarned)
2594 const CBlockIndex* pindex = chainActive.Tip();
2595 for (int i = 0; i < 100 && pindex != NULL; i++)
2597 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2599 pindex = pindex->pprev;
2602 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2603 if (nUpgraded > 100/2)
2605 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2606 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2607 CAlert::Notify(strMiscWarning, true);
2613 /** Disconnect chainActive's tip. */
2614 bool static DisconnectTip(CValidationState &state) {
2615 CBlockIndex *pindexDelete = chainActive.Tip();
2616 assert(pindexDelete);
2617 mempool.check(pcoinsTip);
2618 // Read block from disk.
2620 if (!ReadBlockFromDisk(block, pindexDelete))
2621 return AbortNode(state, "Failed to read block");
2622 // Apply the block atomically to the chain state.
2623 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2624 int64_t nStart = GetTimeMicros();
2626 CCoinsViewCache view(pcoinsTip);
2627 if (!DisconnectBlock(block, state, pindexDelete, view))
2628 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2629 assert(view.Flush());
2631 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2632 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2633 // Write the chain state to disk, if necessary.
2634 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2636 // Resurrect mempool transactions from the disconnected block.
2637 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2638 // ignore validation errors in resurrected transactions
2639 list<CTransaction> removed;
2640 CValidationState stateDummy;
2641 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2642 mempool.remove(tx, removed, true);
2644 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2645 // The anchor may not change between block disconnects,
2646 // in which case we don't want to evict from the mempool yet!
2647 mempool.removeWithAnchor(anchorBeforeDisconnect);
2649 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2650 mempool.check(pcoinsTip);
2651 // Update chainActive and related variables.
2652 UpdateTip(pindexDelete->pprev);
2653 // Get the current commitment tree
2654 ZCIncrementalMerkleTree newTree;
2655 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2656 // Let wallets know transactions went from 1-confirmed to
2657 // 0-confirmed or conflicted:
2658 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2659 SyncWithWallets(tx, NULL);
2661 // Update cached incremental witnesses
2662 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2666 static int64_t nTimeReadFromDisk = 0;
2667 static int64_t nTimeConnectTotal = 0;
2668 static int64_t nTimeFlush = 0;
2669 static int64_t nTimeChainState = 0;
2670 static int64_t nTimePostConnect = 0;
2673 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2674 * corresponding to pindexNew, to bypass loading it again from disk.
2676 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2678 assert(pindexNew->pprev == chainActive.Tip());
2679 mempool.check(pcoinsTip);
2680 // Read block from disk.
2681 int64_t nTime1 = GetTimeMicros();
2684 if (!ReadBlockFromDisk(block, pindexNew))
2685 return AbortNode(state, "Failed to read block");
2688 // Get the current commitment tree
2689 ZCIncrementalMerkleTree oldTree;
2690 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2691 // Apply the block atomically to the chain state.
2692 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2694 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2696 CCoinsViewCache view(pcoinsTip);
2697 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2698 GetMainSignals().BlockChecked(*pblock, state);
2700 if (state.IsInvalid())
2701 InvalidBlockFound(pindexNew, state);
2702 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2704 mapBlockSource.erase(pindexNew->GetBlockHash());
2705 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2706 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2707 assert(view.Flush());
2709 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2710 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2711 // Write the chain state to disk, if necessary.
2712 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2714 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2715 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2716 // Remove conflicting transactions from the mempool.
2717 list<CTransaction> txConflicted;
2718 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2719 mempool.check(pcoinsTip);
2720 // Update chainActive & related variables.
2721 UpdateTip(pindexNew);
2722 // Tell wallet about transactions that went from mempool
2724 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2725 SyncWithWallets(tx, NULL);
2727 // ... and about transactions that got confirmed:
2728 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2729 SyncWithWallets(tx, pblock);
2731 // Update cached incremental witnesses
2732 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2734 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2735 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2736 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2741 * Return the tip of the chain with the most work in it, that isn't
2742 * known to be invalid (it's however far from certain to be valid).
2744 static CBlockIndex* FindMostWorkChain() {
2746 CBlockIndex *pindexNew = NULL;
2748 // Find the best candidate header.
2750 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2751 if (it == setBlockIndexCandidates.rend())
2756 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2757 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2758 CBlockIndex *pindexTest = pindexNew;
2759 bool fInvalidAncestor = false;
2760 while (pindexTest && !chainActive.Contains(pindexTest)) {
2761 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2763 // Pruned nodes may have entries in setBlockIndexCandidates for
2764 // which block files have been deleted. Remove those as candidates
2765 // for the most work chain if we come across them; we can't switch
2766 // to a chain unless we have all the non-active-chain parent blocks.
2767 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2768 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2769 if (fFailedChain || fMissingData) {
2770 // Candidate chain is not usable (either invalid or missing data)
2771 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2772 pindexBestInvalid = pindexNew;
2773 CBlockIndex *pindexFailed = pindexNew;
2774 // Remove the entire chain from the set.
2775 while (pindexTest != pindexFailed) {
2777 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2778 } else if (fMissingData) {
2779 // If we're missing data, then add back to mapBlocksUnlinked,
2780 // so that if the block arrives in the future we can try adding
2781 // to setBlockIndexCandidates again.
2782 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2784 setBlockIndexCandidates.erase(pindexFailed);
2785 pindexFailed = pindexFailed->pprev;
2787 setBlockIndexCandidates.erase(pindexTest);
2788 fInvalidAncestor = true;
2791 pindexTest = pindexTest->pprev;
2793 if (!fInvalidAncestor)
2798 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2799 static void PruneBlockIndexCandidates() {
2800 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2801 // reorganization to a better block fails.
2802 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2803 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2804 setBlockIndexCandidates.erase(it++);
2806 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2807 assert(!setBlockIndexCandidates.empty());
2811 * Try to make some progress towards making pindexMostWork the active block.
2812 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2814 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2815 AssertLockHeld(cs_main);
2816 bool fInvalidFound = false;
2817 const CBlockIndex *pindexOldTip = chainActive.Tip();
2818 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2820 // Disconnect active blocks which are no longer in the best chain.
2821 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2822 if (!DisconnectTip(state))
2825 if ( KOMODO_REWIND != 0 )
2827 fprintf(stderr,"rewind start ht.%d\n",chainActive.Tip()->nHeight);
2828 while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND )
2830 if ( !DisconnectTip(state) )
2832 InvalidateBlock(state,chainActive.Tip());
2836 fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli stop\n",KOMODO_REWIND);
2841 // Build list of new blocks to connect.
2842 std::vector<CBlockIndex*> vpindexToConnect;
2843 bool fContinue = true;
2844 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2845 while (fContinue && nHeight != pindexMostWork->nHeight) {
2846 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2847 // a few blocks along the way.
2848 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2849 vpindexToConnect.clear();
2850 vpindexToConnect.reserve(nTargetHeight - nHeight);
2851 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2852 while (pindexIter && pindexIter->nHeight != nHeight) {
2853 vpindexToConnect.push_back(pindexIter);
2854 pindexIter = pindexIter->pprev;
2856 nHeight = nTargetHeight;
2858 // Connect new blocks.
2859 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2860 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2861 if (state.IsInvalid()) {
2862 // The block violates a consensus rule.
2863 if (!state.CorruptionPossible())
2864 InvalidChainFound(vpindexToConnect.back());
2865 state = CValidationState();
2866 fInvalidFound = true;
2870 // A system error occurred (disk space, database error, ...).
2874 PruneBlockIndexCandidates();
2875 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2876 // We're in a better position than we were. Return temporarily to release the lock.
2884 // Callbacks/notifications for a new best chain.
2886 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2888 CheckForkWarningConditions();
2894 * Make the best chain active, in multiple steps. The result is either failure
2895 * or an activated best chain. pblock is either NULL or a pointer to a block
2896 * that is already loaded (to avoid loading it again from disk).
2898 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2899 CBlockIndex *pindexNewTip = NULL;
2900 CBlockIndex *pindexMostWork = NULL;
2901 const CChainParams& chainParams = Params();
2903 boost::this_thread::interruption_point();
2905 bool fInitialDownload;
2908 pindexMostWork = FindMostWorkChain();
2910 // Whether we have anything to do at all.
2911 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2914 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2916 pindexNewTip = chainActive.Tip();
2917 fInitialDownload = IsInitialBlockDownload();
2919 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2921 // Notifications/callbacks that can run without cs_main
2922 if (!fInitialDownload) {
2923 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2924 // Relay inventory, but don't relay old inventory during initial block download.
2925 int nBlockEstimate = 0;
2926 if (fCheckpointsEnabled)
2927 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2928 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2929 // in a stalled download if the block file is pruned before the request.
2930 if (nLocalServices & NODE_NETWORK) {
2932 BOOST_FOREACH(CNode* pnode, vNodes)
2933 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2934 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2936 // Notify external listeners about the new tip.
2937 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2938 uiInterface.NotifyBlockTip(hashNewTip);
2939 } //else fprintf(stderr,"initial download skips propagation\n");
2940 } while(pindexMostWork != chainActive.Tip());
2943 // Write changes periodically to disk, after relay.
2944 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2951 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2952 AssertLockHeld(cs_main);
2954 // Mark the block itself as invalid.
2955 pindex->nStatus |= BLOCK_FAILED_VALID;
2956 setDirtyBlockIndex.insert(pindex);
2957 setBlockIndexCandidates.erase(pindex);
2959 while (chainActive.Contains(pindex)) {
2960 CBlockIndex *pindexWalk = chainActive.Tip();
2961 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2962 setDirtyBlockIndex.insert(pindexWalk);
2963 setBlockIndexCandidates.erase(pindexWalk);
2964 // ActivateBestChain considers blocks already in chainActive
2965 // unconditionally valid already, so force disconnect away from it.
2966 if (!DisconnectTip(state)) {
2970 //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2972 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2974 BlockMap::iterator it = mapBlockIndex.begin();
2975 while (it != mapBlockIndex.end() && it->second != 0 ) {
2976 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2977 setBlockIndexCandidates.insert(it->second);
2982 InvalidChainFound(pindex);
2986 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2987 AssertLockHeld(cs_main);
2989 int nHeight = pindex->nHeight;
2991 // Remove the invalidity flag from this block and all its descendants.
2992 BlockMap::iterator it = mapBlockIndex.begin();
2993 while (it != mapBlockIndex.end()) {
2994 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2995 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2996 setDirtyBlockIndex.insert(it->second);
2997 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2998 setBlockIndexCandidates.insert(it->second);
3000 if (it->second == pindexBestInvalid) {
3001 // Reset invalid block marker if it was pointing to one of those.
3002 pindexBestInvalid = NULL;
3008 // Remove the invalidity flag from all ancestors too.
3009 while (pindex != NULL) {
3010 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3011 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3012 setDirtyBlockIndex.insert(pindex);
3014 pindex = pindex->pprev;
3019 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3021 // Check for duplicate
3022 uint256 hash = block.GetHash();
3023 BlockMap::iterator it = mapBlockIndex.find(hash);
3024 if (it != mapBlockIndex.end())
3027 // Construct new block index object
3028 CBlockIndex* pindexNew = new CBlockIndex(block);
3030 // We assign the sequence id to blocks only when the full data is available,
3031 // to avoid miners withholding blocks but broadcasting headers, to get a
3032 // competitive advantage.
3033 pindexNew->nSequenceId = 0;
3034 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3035 pindexNew->phashBlock = &((*mi).first);
3036 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3037 if (miPrev != mapBlockIndex.end())
3039 pindexNew->pprev = (*miPrev).second;
3040 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3041 pindexNew->BuildSkip();
3043 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3044 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3045 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3046 pindexBestHeader = pindexNew;
3048 setDirtyBlockIndex.insert(pindexNew);
3053 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3054 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3056 pindexNew->nTx = block.vtx.size();
3057 pindexNew->nChainTx = 0;
3058 pindexNew->nFile = pos.nFile;
3059 pindexNew->nDataPos = pos.nPos;
3060 pindexNew->nUndoPos = 0;
3061 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3062 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3063 setDirtyBlockIndex.insert(pindexNew);
3065 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3066 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3067 deque<CBlockIndex*> queue;
3068 queue.push_back(pindexNew);
3070 // Recursively process any descendant blocks that now may be eligible to be connected.
3071 while (!queue.empty()) {
3072 CBlockIndex *pindex = queue.front();
3074 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3076 LOCK(cs_nBlockSequenceId);
3077 pindex->nSequenceId = nBlockSequenceId++;
3079 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3080 setBlockIndexCandidates.insert(pindex);
3082 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3083 while (range.first != range.second) {
3084 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3085 queue.push_back(it->second);
3087 mapBlocksUnlinked.erase(it);
3091 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3092 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3099 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3101 LOCK(cs_LastBlockFile);
3103 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3104 if (vinfoBlockFile.size() <= nFile) {
3105 vinfoBlockFile.resize(nFile + 1);
3109 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3111 if (vinfoBlockFile.size() <= nFile) {
3112 vinfoBlockFile.resize(nFile + 1);
3116 pos.nPos = vinfoBlockFile[nFile].nSize;
3119 if (nFile != nLastBlockFile) {
3121 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3123 FlushBlockFile(!fKnown);
3124 nLastBlockFile = nFile;
3127 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3129 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3131 vinfoBlockFile[nFile].nSize += nAddSize;
3134 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3135 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3136 if (nNewChunks > nOldChunks) {
3138 fCheckForPruning = true;
3139 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3140 FILE *file = OpenBlockFile(pos);
3142 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3143 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3148 return state.Error("out of disk space");
3152 setDirtyFileInfo.insert(nFile);
3156 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3160 LOCK(cs_LastBlockFile);
3162 unsigned int nNewSize;
3163 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3164 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3165 setDirtyFileInfo.insert(nFile);
3167 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3168 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3169 if (nNewChunks > nOldChunks) {
3171 fCheckForPruning = true;
3172 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3173 FILE *file = OpenUndoFile(pos);
3175 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3176 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3181 return state.Error("out of disk space");
3187 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3189 uint8_t pubkey33[33];
3193 uint256 hash; int32_t i;
3194 hash = blockhdr.GetHash();
3195 for (i=31; i>=0; i--)
3196 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3197 fprintf(stderr," <- CheckBlockHeader\n");
3198 if ( chainActive.Tip() != 0 )
3200 hash = chainActive.Tip()->GetBlockHash();
3201 for (i=31; i>=0; i--)
3202 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3203 fprintf(stderr," <- chainTip\n");
3206 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3207 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3208 // Check block version
3209 //if (block.nVersion < MIN_BLOCK_VERSION)
3210 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3212 // Check Equihash solution is valid
3213 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3214 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3216 // Check proof of work matches claimed amount
3217 komodo_index2pubkey33(pubkey33,pindex,height);
3218 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3219 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3223 int32_t komodo_check_deposit(int32_t height,const CBlock& block);
3224 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
3225 libzcash::ProofVerifier& verifier,
3226 bool fCheckPOW, bool fCheckMerkleRoot)
3228 // These are checks that are independent of context.
3230 // Check that the header is valid (particularly PoW). This is mostly
3231 // redundant with the call in AcceptBlockHeader.
3232 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3235 // Check the merkle root.
3236 if (fCheckMerkleRoot) {
3238 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3239 if (block.hashMerkleRoot != hashMerkleRoot2)
3240 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3241 REJECT_INVALID, "bad-txnmrklroot", true);
3243 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3244 // of transactions in a block without affecting the merkle root of a block,
3245 // while still invalidating it.
3247 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3248 REJECT_INVALID, "bad-txns-duplicate", true);
3251 // All potential-corruption validation must be done before we do any
3252 // transaction validation, as otherwise we may mark the header as invalid
3253 // because we receive the wrong transactions for it.
3256 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3257 return state.DoS(100, error("CheckBlock(): size limits failed"),
3258 REJECT_INVALID, "bad-blk-length");
3260 // First transaction must be coinbase, the rest must not be
3261 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3262 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3263 REJECT_INVALID, "bad-cb-missing");
3264 for (unsigned int i = 1; i < block.vtx.size(); i++)
3265 if (block.vtx[i].IsCoinBase())
3266 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3267 REJECT_INVALID, "bad-cb-multiple");
3269 // Check transactions
3270 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3272 if ( komodo_validate_interest(tx,komodo_block2height((CBlock *)&block),block.nTime,1) < 0 )
3273 return error("CheckBlock: komodo_validate_interest failed");
3274 if (!CheckTransaction(tx, state, verifier))
3275 return error("CheckBlock(): CheckTransaction failed");
3277 unsigned int nSigOps = 0;
3278 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3280 nSigOps += GetLegacySigOpCount(tx);
3282 if (nSigOps > MAX_BLOCK_SIGOPS)
3283 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3284 REJECT_INVALID, "bad-blk-sigops", true);
3285 if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block) < 0 )
3287 static uint32_t counter;
3288 if ( counter++ < 100 )
3289 fprintf(stderr,"check deposit rejection\n");
3295 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3297 const CChainParams& chainParams = Params();
3298 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3299 uint256 hash = block.GetHash();
3300 if (hash == consensusParams.hashGenesisBlock)
3305 int nHeight = pindexPrev->nHeight+1;
3307 // Check proof of work
3308 if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3310 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3311 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3312 REJECT_INVALID, "bad-diffbits");
3315 // Check timestamp against prev
3316 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3317 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3318 REJECT_INVALID, "time-too-old");
3320 if (fCheckpointsEnabled)
3322 // Check that the block chain matches the known block chain up to a checkpoint
3323 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3324 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3326 // Don't accept any forks from the main chain prior to last checkpoint
3327 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3328 int32_t notarized_height;
3329 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3330 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3331 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3332 return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3334 // Reject block.nVersion < 4 blocks
3335 if (block.nVersion < 4)
3336 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3337 REJECT_OBSOLETE, "bad-version");
3342 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3344 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3345 const Consensus::Params& consensusParams = Params().GetConsensus();
3347 // Check that all transactions are finalized
3348 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3349 int nLockTimeFlags = 0;
3350 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3351 ? pindexPrev->GetMedianTimePast()
3352 : block.GetBlockTime();
3353 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3354 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3358 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3359 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3360 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3361 // This rule is not applied to the genesis block, which didn't include the height
3365 CScript expect = CScript() << nHeight;
3366 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3367 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3368 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3375 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3377 const CChainParams& chainparams = Params();
3378 AssertLockHeld(cs_main);
3379 // Check for duplicate
3380 uint256 hash = block.GetHash();
3381 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3382 CBlockIndex *pindex = NULL;
3383 if (miSelf != mapBlockIndex.end()) {
3384 // Block header is already known.
3385 pindex = miSelf->second;
3388 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3389 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3393 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3396 // Get prev block index
3397 CBlockIndex* pindexPrev = NULL;
3398 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3399 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3400 if (mi == mapBlockIndex.end())
3401 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3402 pindexPrev = (*mi).second;
3403 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3404 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3406 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3409 pindex = AddToBlockIndex(block);
3415 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3417 const CChainParams& chainparams = Params();
3418 AssertLockHeld(cs_main);
3420 CBlockIndex *&pindex = *ppindex;
3421 if (!AcceptBlockHeader(block, state, &pindex))
3425 fprintf(stderr,"AcceptBlock error null pindex\n");
3428 // Try to process all requested blocks that we don't have, but only
3429 // process an unrequested block if it's new and has enough work to
3430 // advance our tip, and isn't too many blocks ahead.
3431 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3432 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3433 // Blocks that are too out-of-order needlessly limit the effectiveness of
3434 // pruning, because pruning will not delete block files that contain any
3435 // blocks which are too close in height to the tip. Apply this test
3436 // regardless of whether pruning is enabled; it should generally be safe to
3437 // not process unrequested blocks.
3438 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3440 // TODO: deal better with return value and error conditions for duplicate
3441 // and unrequested blocks.
3442 if (fAlreadyHave) return true;
3443 if (!fRequested) { // If we didn't ask for it:
3444 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3445 if (!fHasMoreWork) return true; // Don't process less-work chains
3446 if (fTooFarAhead) return true; // Block height is too high
3449 // See method docstring for why this is always disabled
3450 auto verifier = libzcash::ProofVerifier::Disabled();
3451 if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3452 if (state.IsInvalid() && !state.CorruptionPossible()) {
3453 pindex->nStatus |= BLOCK_FAILED_VALID;
3454 setDirtyBlockIndex.insert(pindex);
3459 int nHeight = pindex->nHeight;
3461 // Write block to history file
3463 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3464 CDiskBlockPos blockPos;
3467 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3468 return error("AcceptBlock(): FindBlockPos failed");
3470 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3471 AbortNode(state, "Failed to write block");
3472 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3473 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3474 } catch (const std::runtime_error& e) {
3475 return AbortNode(state, std::string("System error: ") + e.what());
3478 if (fCheckForPruning)
3479 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3484 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3486 unsigned int nFound = 0;
3487 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3489 if (pstart->nVersion >= minVersion)
3491 pstart = pstart->pprev;
3493 return (nFound >= nRequired);
3496 void komodo_currentheight_set(int32_t height);
3498 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3500 // Preliminary checks
3502 auto verifier = libzcash::ProofVerifier::Disabled();
3503 if ( chainActive.Tip() != 0 )
3504 komodo_currentheight_set(chainActive.Tip()->nHeight);
3505 if ( ASSETCHAINS_SYMBOL[0] == 0 )
3506 checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3507 else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3510 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3511 fRequested |= fForceProcessing;
3514 Misbehaving(pfrom->GetId(), 1);
3515 return error("%s: CheckBlock FAILED", __func__);
3519 CBlockIndex *pindex = NULL;
3520 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3521 if (pindex && pfrom) {
3522 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3526 return error("%s: AcceptBlock FAILED", __func__);
3529 if (!ActivateBestChain(state, pblock))
3530 return error("%s: ActivateBestChain failed", __func__);
3535 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3537 AssertLockHeld(cs_main);
3538 assert(pindexPrev == chainActive.Tip());
3540 CCoinsViewCache viewNew(pcoinsTip);
3541 CBlockIndex indexDummy(block);
3542 indexDummy.pprev = pindexPrev;
3543 indexDummy.nHeight = pindexPrev->nHeight + 1;
3544 // JoinSplit proofs are verified in ConnectBlock
3545 auto verifier = libzcash::ProofVerifier::Disabled();
3547 // NOTE: CheckBlockHeader is called by CheckBlock
3548 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3550 fprintf(stderr,"TestBlockValidity failure A\n");
3553 if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3555 //fprintf(stderr,"TestBlockValidity failure B\n");
3558 if (!ContextualCheckBlock(block, state, pindexPrev))
3560 fprintf(stderr,"TestBlockValidity failure C\n");
3563 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3565 fprintf(stderr,"TestBlockValidity failure D\n");
3568 assert(state.IsValid());
3574 * BLOCK PRUNING CODE
3577 /* Calculate the amount of disk space the block & undo files currently use */
3578 uint64_t CalculateCurrentUsage()
3580 uint64_t retval = 0;
3581 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3582 retval += file.nSize + file.nUndoSize;
3587 /* Prune a block file (modify associated database entries)*/
3588 void PruneOneBlockFile(const int fileNumber)
3590 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3591 CBlockIndex* pindex = it->second;
3592 if (pindex->nFile == fileNumber) {
3593 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3594 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3596 pindex->nDataPos = 0;
3597 pindex->nUndoPos = 0;
3598 setDirtyBlockIndex.insert(pindex);
3600 // Prune from mapBlocksUnlinked -- any block we prune would have
3601 // to be downloaded again in order to consider its chain, at which
3602 // point it would be considered as a candidate for
3603 // mapBlocksUnlinked or setBlockIndexCandidates.
3604 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3605 while (range.first != range.second) {
3606 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3608 if (it->second == pindex) {
3609 mapBlocksUnlinked.erase(it);
3615 vinfoBlockFile[fileNumber].SetNull();
3616 setDirtyFileInfo.insert(fileNumber);
3620 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3622 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3623 CDiskBlockPos pos(*it, 0);
3624 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3625 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3626 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3630 /* Calculate the block/rev files that should be deleted to remain under target*/
3631 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3633 LOCK2(cs_main, cs_LastBlockFile);
3634 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3637 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3641 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3642 uint64_t nCurrentUsage = CalculateCurrentUsage();
3643 // We don't check to prune until after we've allocated new space for files
3644 // So we should leave a buffer under our target to account for another allocation
3645 // before the next pruning.
3646 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3647 uint64_t nBytesToPrune;
3650 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3651 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3652 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3654 if (vinfoBlockFile[fileNumber].nSize == 0)
3657 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3660 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3661 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3664 PruneOneBlockFile(fileNumber);
3665 // Queue up the files for removal
3666 setFilesToPrune.insert(fileNumber);
3667 nCurrentUsage -= nBytesToPrune;
3672 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3673 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3674 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3675 nLastBlockWeCanPrune, count);
3678 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3680 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3682 // Check for nMinDiskSpace bytes (currently 50MB)
3683 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3684 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3689 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3693 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3694 boost::filesystem::create_directories(path.parent_path());
3695 FILE* file = fopen(path.string().c_str(), "rb+");
3696 if (!file && !fReadOnly)
3697 file = fopen(path.string().c_str(), "wb+");
3699 LogPrintf("Unable to open file %s\n", path.string());
3703 if (fseek(file, pos.nPos, SEEK_SET)) {
3704 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3712 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3713 return OpenDiskFile(pos, "blk", fReadOnly);
3716 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3717 return OpenDiskFile(pos, "rev", fReadOnly);
3720 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3722 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3725 CBlockIndex * InsertBlockIndex(uint256 hash)
3731 BlockMap::iterator mi = mapBlockIndex.find(hash);
3732 if (mi != mapBlockIndex.end())
3733 return (*mi).second;
3736 CBlockIndex* pindexNew = new CBlockIndex();
3738 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3739 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3740 pindexNew->phashBlock = &((*mi).first);
3745 bool static LoadBlockIndexDB()
3747 const CChainParams& chainparams = Params();
3748 if (!pblocktree->LoadBlockIndexGuts())
3751 boost::this_thread::interruption_point();
3753 // Calculate nChainWork
3754 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3755 vSortedByHeight.reserve(mapBlockIndex.size());
3756 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3758 CBlockIndex* pindex = item.second;
3759 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3761 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3762 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3764 CBlockIndex* pindex = item.second;
3765 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3766 // We can link the chain of blocks for which we've received transactions at some point.
3767 // Pruned nodes may have deleted the block.
3768 if (pindex->nTx > 0) {
3769 if (pindex->pprev) {
3770 if (pindex->pprev->nChainTx) {
3771 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3773 pindex->nChainTx = 0;
3774 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3777 pindex->nChainTx = pindex->nTx;
3780 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3781 setBlockIndexCandidates.insert(pindex);
3782 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3783 pindexBestInvalid = pindex;
3785 pindex->BuildSkip();
3786 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3787 pindexBestHeader = pindex;
3790 // Load block file info
3791 pblocktree->ReadLastBlockFile(nLastBlockFile);
3792 vinfoBlockFile.resize(nLastBlockFile + 1);
3793 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3794 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3795 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3797 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3798 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3799 CBlockFileInfo info;
3800 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3801 vinfoBlockFile.push_back(info);
3807 // Check presence of blk files
3808 LogPrintf("Checking all blk files are present...\n");
3809 set<int> setBlkDataFiles;
3810 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3812 CBlockIndex* pindex = item.second;
3813 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3814 setBlkDataFiles.insert(pindex->nFile);
3817 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3819 CDiskBlockPos pos(*it, 0);
3820 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3825 // Check whether we have ever pruned block & undo files
3826 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3828 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3830 // Check whether we need to continue reindexing
3831 bool fReindexing = false;
3832 pblocktree->ReadReindexing(fReindexing);
3833 fReindex |= fReindexing;
3835 // Check whether we have a transaction index
3836 pblocktree->ReadFlag("txindex", fTxIndex);
3837 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3839 // Fill in-memory data
3840 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3842 CBlockIndex* pindex = item.second;
3843 // - This relationship will always be true even if pprev has multiple
3844 // children, because hashAnchor is technically a property of pprev,
3845 // not its children.
3846 // - This will miss chain tips; we handle the best tip below, and other
3847 // tips will be handled by ConnectTip during a re-org.
3848 if (pindex->pprev) {
3849 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3853 // Load pointer to end of best chain
3854 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3855 if (it == mapBlockIndex.end())
3857 chainActive.SetTip(it->second);
3858 // Set hashAnchorEnd for the end of best chain
3859 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3861 PruneBlockIndexCandidates();
3863 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3864 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3865 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3866 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3871 CVerifyDB::CVerifyDB()
3873 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3876 CVerifyDB::~CVerifyDB()
3878 uiInterface.ShowProgress("", 100);
3881 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3884 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3887 // Verify blocks in the best chain
3888 if (nCheckDepth <= 0)
3889 nCheckDepth = 1000000000; // suffices until the year 19000
3890 if (nCheckDepth > chainActive.Height())
3891 nCheckDepth = chainActive.Height();
3892 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3893 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3894 CCoinsViewCache coins(coinsview);
3895 CBlockIndex* pindexState = chainActive.Tip();
3896 CBlockIndex* pindexFailure = NULL;
3897 int nGoodTransactions = 0;
3898 CValidationState state;
3899 // No need to verify JoinSplits twice
3900 auto verifier = libzcash::ProofVerifier::Disabled();
3901 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3903 boost::this_thread::interruption_point();
3904 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3905 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3908 // check level 0: read from disk
3909 if (!ReadBlockFromDisk(block, pindex))
3910 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3911 // check level 1: verify block validity
3912 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier))
3913 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3914 // check level 2: verify undo validity
3915 if (nCheckLevel >= 2 && pindex) {
3917 CDiskBlockPos pos = pindex->GetUndoPos();
3918 if (!pos.IsNull()) {
3919 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3920 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3923 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3924 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3926 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3927 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3928 pindexState = pindex->pprev;
3930 nGoodTransactions = 0;
3931 pindexFailure = pindex;
3933 nGoodTransactions += block.vtx.size();
3935 if (ShutdownRequested())
3939 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3941 // check level 4: try reconnecting blocks
3942 if (nCheckLevel >= 4) {
3943 CBlockIndex *pindex = pindexState;
3944 while (pindex != chainActive.Tip()) {
3945 boost::this_thread::interruption_point();
3946 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3947 pindex = chainActive.Next(pindex);
3949 if (!ReadBlockFromDisk(block, pindex))
3950 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3951 if (!ConnectBlock(block, state, pindex, coins))
3952 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3956 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3961 void UnloadBlockIndex()
3964 setBlockIndexCandidates.clear();
3965 chainActive.SetTip(NULL);
3966 pindexBestInvalid = NULL;
3967 pindexBestHeader = NULL;
3969 mapOrphanTransactions.clear();
3970 mapOrphanTransactionsByPrev.clear();
3972 mapBlocksUnlinked.clear();
3973 vinfoBlockFile.clear();
3975 nBlockSequenceId = 1;
3976 mapBlockSource.clear();
3977 mapBlocksInFlight.clear();
3978 nQueuedValidatedHeaders = 0;
3979 nPreferredDownload = 0;
3980 setDirtyBlockIndex.clear();
3981 setDirtyFileInfo.clear();
3982 mapNodeState.clear();
3983 recentRejects.reset(NULL);
3985 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3986 delete entry.second;
3988 mapBlockIndex.clear();
3989 fHavePruned = false;
3992 bool LoadBlockIndex()
3994 extern int32_t KOMODO_LOADINGBLOCKS;
3995 // Load block index from databases
3996 KOMODO_LOADINGBLOCKS = 1;
3997 if (!fReindex && !LoadBlockIndexDB())
3999 KOMODO_LOADINGBLOCKS = 0;
4002 KOMODO_LOADINGBLOCKS = 0;
4003 fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL);
4008 bool InitBlockIndex() {
4009 const CChainParams& chainparams = Params();
4012 // Initialize global variables that cannot be constructed at startup.
4013 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4015 // Check whether we're already initialized
4016 if (chainActive.Genesis() != NULL)
4019 // Use the provided setting for -txindex in the new database
4020 fTxIndex = GetBoolArg("-txindex", false);
4021 pblocktree->WriteFlag("txindex", fTxIndex);
4022 LogPrintf("Initializing databases...\n");
4024 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4027 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4028 // Start new block file
4029 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4030 CDiskBlockPos blockPos;
4031 CValidationState state;
4032 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4033 return error("LoadBlockIndex(): FindBlockPos failed");
4034 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4035 return error("LoadBlockIndex(): writing genesis block to disk failed");
4036 CBlockIndex *pindex = AddToBlockIndex(block);
4037 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4038 return error("LoadBlockIndex(): genesis block not accepted");
4039 if (!ActivateBestChain(state, &block))
4040 return error("LoadBlockIndex(): genesis block cannot be activated");
4041 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4042 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4043 } catch (const std::runtime_error& e) {
4044 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4053 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4055 const CChainParams& chainparams = Params();
4056 // Map of disk positions for blocks with unknown parent (only used for reindex)
4057 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4058 int64_t nStart = GetTimeMillis();
4062 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4063 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4064 uint64_t nRewind = blkdat.GetPos();
4065 while (!blkdat.eof()) {
4066 boost::this_thread::interruption_point();
4068 blkdat.SetPos(nRewind);
4069 nRewind++; // start one byte further next time, in case of failure
4070 blkdat.SetLimit(); // remove former limit
4071 unsigned int nSize = 0;
4074 unsigned char buf[MESSAGE_START_SIZE];
4075 blkdat.FindByte(Params().MessageStart()[0]);
4076 nRewind = blkdat.GetPos()+1;
4077 blkdat >> FLATDATA(buf);
4078 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4082 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4084 } catch (const std::exception&) {
4085 // no valid block header found; don't complain
4090 uint64_t nBlockPos = blkdat.GetPos();
4092 dbp->nPos = nBlockPos;
4093 blkdat.SetLimit(nBlockPos + nSize);
4094 blkdat.SetPos(nBlockPos);
4097 nRewind = blkdat.GetPos();
4099 // detect out of order blocks, and store them for later
4100 uint256 hash = block.GetHash();
4101 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4102 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4103 block.hashPrevBlock.ToString());
4105 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4109 // process in case the block isn't known yet
4110 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4111 CValidationState state;
4112 if (ProcessNewBlock(0,state, NULL, &block, true, dbp))
4114 if (state.IsError())
4116 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4117 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4120 // Recursively process earlier encountered successors of this block
4121 deque<uint256> queue;
4122 queue.push_back(hash);
4123 while (!queue.empty()) {
4124 uint256 head = queue.front();
4126 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4127 while (range.first != range.second) {
4128 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4129 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
4131 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4133 CValidationState dummy;
4134 if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second))
4137 queue.push_back(block.GetHash());
4141 mapBlocksUnknownParent.erase(it);
4144 } catch (const std::exception& e) {
4145 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4148 } catch (const std::runtime_error& e) {
4149 AbortNode(std::string("System error: ") + e.what());
4152 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4156 void static CheckBlockIndex()
4158 const Consensus::Params& consensusParams = Params().GetConsensus();
4159 if (!fCheckBlockIndex) {
4165 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4166 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4167 // iterating the block tree require that chainActive has been initialized.)
4168 if (chainActive.Height() < 0) {
4169 assert(mapBlockIndex.size() <= 1);
4173 // Build forward-pointing map of the entire block tree.
4174 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4175 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4176 forward.insert(std::make_pair(it->second->pprev, it->second));
4179 assert(forward.size() == mapBlockIndex.size());
4181 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4182 CBlockIndex *pindex = rangeGenesis.first->second;
4183 rangeGenesis.first++;
4184 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4186 // Iterate over the entire block tree, using depth-first search.
4187 // Along the way, remember whether there are blocks on the path from genesis
4188 // block being explored which are the first to have certain properties.
4191 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4192 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4193 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4194 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4195 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4196 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4197 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4198 while (pindex != NULL) {
4200 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4201 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4202 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4203 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4204 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4205 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4206 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4208 // Begin: actual consistency checks.
4209 if (pindex->pprev == NULL) {
4210 // Genesis block checks.
4211 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4212 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4214 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4215 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4216 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4218 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4219 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4220 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4222 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4223 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4225 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4226 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4227 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4228 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4229 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4230 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4231 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.
4232 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4233 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4234 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4235 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4236 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4237 if (pindexFirstInvalid == NULL) {
4238 // Checks for not-invalid blocks.
4239 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4241 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4242 if (pindexFirstInvalid == NULL) {
4243 // If this block sorts at least as good as the current tip and
4244 // is valid and we have all data for its parents, it must be in
4245 // setBlockIndexCandidates. chainActive.Tip() must also be there
4246 // even if some data has been pruned.
4247 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4248 assert(setBlockIndexCandidates.count(pindex));
4250 // If some parent is missing, then it could be that this block was in
4251 // setBlockIndexCandidates but had to be removed because of the missing data.
4252 // In this case it must be in mapBlocksUnlinked -- see test below.
4254 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4255 assert(setBlockIndexCandidates.count(pindex) == 0);
4257 // Check whether this block is in mapBlocksUnlinked.
4258 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4259 bool foundInUnlinked = false;
4260 while (rangeUnlinked.first != rangeUnlinked.second) {
4261 assert(rangeUnlinked.first->first == pindex->pprev);
4262 if (rangeUnlinked.first->second == pindex) {
4263 foundInUnlinked = true;
4266 rangeUnlinked.first++;
4268 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4269 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4270 assert(foundInUnlinked);
4272 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4273 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4274 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4275 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4276 assert(fHavePruned); // We must have pruned.
4277 // This block may have entered mapBlocksUnlinked if:
4278 // - it has a descendant that at some point had more work than the
4280 // - we tried switching to that descendant but were missing
4281 // data for some intermediate block between chainActive and the
4283 // So if this block is itself better than chainActive.Tip() and it wasn't in
4284 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4285 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4286 if (pindexFirstInvalid == NULL) {
4287 assert(foundInUnlinked);
4291 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4292 // End: actual consistency checks.
4294 // Try descending into the first subnode.
4295 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4296 if (range.first != range.second) {
4297 // A subnode was found.
4298 pindex = range.first->second;
4302 // This is a leaf node.
4303 // Move upwards until we reach a node of which we have not yet visited the last child.
4305 // We are going to either move to a parent or a sibling of pindex.
4306 // If pindex was the first with a certain property, unset the corresponding variable.
4307 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4308 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4309 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4310 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4311 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4312 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4313 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4315 CBlockIndex* pindexPar = pindex->pprev;
4316 // Find which child we just visited.
4317 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4318 while (rangePar.first->second != pindex) {
4319 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4322 // Proceed to the next one.
4324 if (rangePar.first != rangePar.second) {
4325 // Move to the sibling.
4326 pindex = rangePar.first->second;
4337 // Check that we actually traversed the entire map.
4338 assert(nNodes == forward.size());
4341 //////////////////////////////////////////////////////////////////////////////
4346 std::string GetWarnings(const std::string& strFor)
4349 string strStatusBar;
4352 if (!CLIENT_VERSION_IS_RELEASE)
4353 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4355 if (GetBoolArg("-testsafemode", false))
4356 strStatusBar = strRPC = "testsafemode enabled";
4358 // Misc warnings like out of disk space and clock is wrong
4359 if (strMiscWarning != "")
4362 strStatusBar = strMiscWarning;
4365 if (fLargeWorkForkFound)
4368 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4370 else if (fLargeWorkInvalidChainFound)
4373 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.");
4379 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4381 const CAlert& alert = item.second;
4382 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4384 nPriority = alert.nPriority;
4385 strStatusBar = alert.strStatusBar;
4386 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4387 strRPC = alert.strRPCError;
4393 if (strFor == "statusbar")
4394 return strStatusBar;
4395 else if (strFor == "rpc")
4397 assert(!"GetWarnings(): invalid parameter");
4408 //////////////////////////////////////////////////////////////////////////////
4414 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4420 assert(recentRejects);
4421 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4423 // If the chain tip has changed previously rejected transactions
4424 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4425 // or a double-spend. Reset the rejects filter and give those
4426 // txs a second chance.
4427 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4428 recentRejects->reset();
4431 return recentRejects->contains(inv.hash) ||
4432 mempool.exists(inv.hash) ||
4433 mapOrphanTransactions.count(inv.hash) ||
4434 pcoinsTip->HaveCoins(inv.hash);
4437 return mapBlockIndex.count(inv.hash);
4439 // Don't know what it is, just say we already got one
4443 void static ProcessGetData(CNode* pfrom)
4445 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4447 vector<CInv> vNotFound;
4451 while (it != pfrom->vRecvGetData.end()) {
4452 // Don't bother if send buffer is too full to respond anyway
4453 if (pfrom->nSendSize >= SendBufferSize())
4456 const CInv &inv = *it;
4458 boost::this_thread::interruption_point();
4461 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4464 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4465 if (mi != mapBlockIndex.end())
4467 if (chainActive.Contains(mi->second)) {
4470 static const int nOneMonth = 30 * 24 * 60 * 60;
4471 // To prevent fingerprinting attacks, only send blocks outside of the active
4472 // chain if they are valid, and no more than a month older (both in time, and in
4473 // best equivalent proof of work) than the best header chain we know about.
4474 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4475 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4476 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4478 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4482 // Pruned nodes may have deleted the block, so check whether
4483 // it's available before trying to send.
4484 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4486 // Send block from disk
4488 if (!ReadBlockFromDisk(block, (*mi).second))
4490 assert(!"cannot load block from disk");
4494 if (inv.type == MSG_BLOCK)
4495 pfrom->PushMessage("block", block);
4496 else // MSG_FILTERED_BLOCK)
4498 LOCK(pfrom->cs_filter);
4501 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4502 pfrom->PushMessage("merkleblock", merkleBlock);
4503 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4504 // This avoids hurting performance by pointlessly requiring a round-trip
4505 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4506 // they must either disconnect and retry or request the full block.
4507 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4508 // however we MUST always provide at least what the remote peer needs
4509 typedef std::pair<unsigned int, uint256> PairType;
4510 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4511 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4512 pfrom->PushMessage("tx", block.vtx[pair.first]);
4518 // Trigger the peer node to send a getblocks request for the next batch of inventory
4519 if (inv.hash == pfrom->hashContinue)
4521 // Bypass PushInventory, this must send even if redundant,
4522 // and we want it right after the last block so they don't
4523 // wait for other stuff first.
4525 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4526 pfrom->PushMessage("inv", vInv);
4527 pfrom->hashContinue.SetNull();
4531 else if (inv.IsKnownType())
4533 // Send stream from relay memory
4534 bool pushed = false;
4537 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4538 if (mi != mapRelay.end()) {
4539 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4543 if (!pushed && inv.type == MSG_TX) {
4545 if (mempool.lookup(inv.hash, tx)) {
4546 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4549 pfrom->PushMessage("tx", ss);
4554 vNotFound.push_back(inv);
4558 // Track requests for our stuff.
4559 GetMainSignals().Inventory(inv.hash);
4561 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4566 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4568 if (!vNotFound.empty()) {
4569 // Let the peer know that we didn't find what it asked for, so it doesn't
4570 // have to wait around forever. Currently only SPV clients actually care
4571 // about this message: it's needed when they are recursively walking the
4572 // dependencies of relevant unconfirmed transactions. SPV clients want to
4573 // do that because they want to know about (and store and rebroadcast and
4574 // risk analyze) the dependencies of transactions relevant to them, without
4575 // having to download the entire memory pool.
4576 pfrom->PushMessage("notfound", vNotFound);
4580 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4582 const CChainParams& chainparams = Params();
4583 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4584 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4586 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4593 if (strCommand == "version")
4595 // Each connection can only send one version message
4596 if (pfrom->nVersion != 0)
4598 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4599 Misbehaving(pfrom->GetId(), 1);
4606 uint64_t nNonce = 1;
4607 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4608 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4610 // disconnect from peers older than this proto version
4611 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4612 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4613 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4614 pfrom->fDisconnect = true;
4618 if (pfrom->nVersion == 10300)
4619 pfrom->nVersion = 300;
4621 vRecv >> addrFrom >> nNonce;
4622 if (!vRecv.empty()) {
4623 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4624 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4627 vRecv >> pfrom->nStartingHeight;
4629 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4631 pfrom->fRelayTxes = true;
4633 // Disconnect if we connected to ourself
4634 if (nNonce == nLocalHostNonce && nNonce > 1)
4636 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4637 pfrom->fDisconnect = true;
4641 pfrom->addrLocal = addrMe;
4642 if (pfrom->fInbound && addrMe.IsRoutable())
4647 // Be shy and don't send version until we hear
4648 if (pfrom->fInbound)
4649 pfrom->PushVersion();
4651 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4653 // Potentially mark this peer as a preferred download peer.
4654 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4657 pfrom->PushMessage("verack");
4658 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4660 if (!pfrom->fInbound)
4662 // Advertise our address
4663 if (fListen && !IsInitialBlockDownload())
4665 CAddress addr = GetLocalAddress(&pfrom->addr);
4666 if (addr.IsRoutable())
4668 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4669 pfrom->PushAddress(addr);
4670 } else if (IsPeerAddrLocalGood(pfrom)) {
4671 addr.SetIP(pfrom->addrLocal);
4672 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4673 pfrom->PushAddress(addr);
4677 // Get recent addresses
4678 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4680 pfrom->PushMessage("getaddr");
4681 pfrom->fGetAddr = true;
4683 addrman.Good(pfrom->addr);
4685 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4687 addrman.Add(addrFrom, addrFrom);
4688 addrman.Good(addrFrom);
4695 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4696 item.second.RelayTo(pfrom);
4699 pfrom->fSuccessfullyConnected = true;
4703 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4705 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4706 pfrom->cleanSubVer, pfrom->nVersion,
4707 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4710 int64_t nTimeOffset = nTime - GetTime();
4711 pfrom->nTimeOffset = nTimeOffset;
4712 AddTimeData(pfrom->addr, nTimeOffset);
4716 else if (pfrom->nVersion == 0)
4718 // Must have a version message before anything else
4719 Misbehaving(pfrom->GetId(), 1);
4724 else if (strCommand == "verack")
4726 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4728 // Mark this node as currently connected, so we update its timestamp later.
4729 if (pfrom->fNetworkNode) {
4731 State(pfrom->GetId())->fCurrentlyConnected = true;
4736 else if (strCommand == "addr")
4738 vector<CAddress> vAddr;
4741 // Don't want addr from older versions unless seeding
4742 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4744 if (vAddr.size() > 1000)
4746 Misbehaving(pfrom->GetId(), 20);
4747 return error("message addr size() = %u", vAddr.size());
4750 // Store the new addresses
4751 vector<CAddress> vAddrOk;
4752 int64_t nNow = GetAdjustedTime();
4753 int64_t nSince = nNow - 10 * 60;
4754 BOOST_FOREACH(CAddress& addr, vAddr)
4756 boost::this_thread::interruption_point();
4758 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4759 addr.nTime = nNow - 5 * 24 * 60 * 60;
4760 pfrom->AddAddressKnown(addr);
4761 bool fReachable = IsReachable(addr);
4762 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4764 // Relay to a limited number of other nodes
4767 // Use deterministic randomness to send to the same nodes for 24 hours
4768 // at a time so the addrKnowns of the chosen nodes prevent repeats
4769 static uint256 hashSalt;
4770 if (hashSalt.IsNull())
4771 hashSalt = GetRandHash();
4772 uint64_t hashAddr = addr.GetHash();
4773 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4774 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4775 multimap<uint256, CNode*> mapMix;
4776 BOOST_FOREACH(CNode* pnode, vNodes)
4778 if (pnode->nVersion < CADDR_TIME_VERSION)
4780 unsigned int nPointer;
4781 memcpy(&nPointer, &pnode, sizeof(nPointer));
4782 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4783 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4784 mapMix.insert(make_pair(hashKey, pnode));
4786 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4787 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4788 ((*mi).second)->PushAddress(addr);
4791 // Do not store addresses outside our network
4793 vAddrOk.push_back(addr);
4795 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4796 if (vAddr.size() < 1000)
4797 pfrom->fGetAddr = false;
4798 if (pfrom->fOneShot)
4799 pfrom->fDisconnect = true;
4803 else if (strCommand == "inv")
4807 if (vInv.size() > MAX_INV_SZ)
4809 Misbehaving(pfrom->GetId(), 20);
4810 return error("message inv size() = %u", vInv.size());
4815 std::vector<CInv> vToFetch;
4817 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4819 const CInv &inv = vInv[nInv];
4821 boost::this_thread::interruption_point();
4822 pfrom->AddInventoryKnown(inv);
4824 bool fAlreadyHave = AlreadyHave(inv);
4825 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4827 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4830 if (inv.type == MSG_BLOCK) {
4831 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4832 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4833 // First request the headers preceding the announced block. In the normal fully-synced
4834 // case where a new block is announced that succeeds the current tip (no reorganization),
4835 // there are no such headers.
4836 // Secondly, and only when we are close to being synced, we request the announced block directly,
4837 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4838 // time the block arrives, the header chain leading up to it is already validated. Not
4839 // doing this will result in the received block being rejected as an orphan in case it is
4840 // not a direct successor.
4841 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4842 CNodeState *nodestate = State(pfrom->GetId());
4843 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4844 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4845 vToFetch.push_back(inv);
4846 // Mark block as in flight already, even though the actual "getdata" message only goes out
4847 // later (within the same cs_main lock, though).
4848 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4850 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4854 // Track requests for our stuff
4855 GetMainSignals().Inventory(inv.hash);
4857 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4858 Misbehaving(pfrom->GetId(), 50);
4859 return error("send buffer size() = %u", pfrom->nSendSize);
4863 if (!vToFetch.empty())
4864 pfrom->PushMessage("getdata", vToFetch);
4868 else if (strCommand == "getdata")
4872 if (vInv.size() > MAX_INV_SZ)
4874 Misbehaving(pfrom->GetId(), 20);
4875 return error("message getdata size() = %u", vInv.size());
4878 if (fDebug || (vInv.size() != 1))
4879 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4881 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4882 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4884 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4885 ProcessGetData(pfrom);
4889 else if (strCommand == "getblocks")
4891 CBlockLocator locator;
4893 vRecv >> locator >> hashStop;
4897 // Find the last block the caller has in the main chain
4898 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4900 // Send the rest of the chain
4902 pindex = chainActive.Next(pindex);
4904 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4905 for (; pindex; pindex = chainActive.Next(pindex))
4907 if (pindex->GetBlockHash() == hashStop)
4909 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4912 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4915 // When this block is requested, we'll send an inv that'll
4916 // trigger the peer to getblocks the next batch of inventory.
4917 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4918 pfrom->hashContinue = pindex->GetBlockHash();
4925 else if (strCommand == "getheaders")
4927 CBlockLocator locator;
4929 vRecv >> locator >> hashStop;
4933 if (IsInitialBlockDownload())
4936 CBlockIndex* pindex = NULL;
4937 if (locator.IsNull())
4939 // If locator is null, return the hashStop block
4940 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4941 if (mi == mapBlockIndex.end())
4943 pindex = (*mi).second;
4947 // Find the last block the caller has in the main chain
4948 pindex = FindForkInGlobalIndex(chainActive, locator);
4950 pindex = chainActive.Next(pindex);
4953 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4954 vector<CBlock> vHeaders;
4955 int nLimit = MAX_HEADERS_RESULTS;
4956 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4957 for (; pindex; pindex = chainActive.Next(pindex))
4959 vHeaders.push_back(pindex->GetBlockHeader());
4960 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4963 pfrom->PushMessage("headers", vHeaders);
4967 else if (strCommand == "tx")
4969 vector<uint256> vWorkQueue;
4970 vector<uint256> vEraseQueue;
4974 CInv inv(MSG_TX, tx.GetHash());
4975 pfrom->AddInventoryKnown(inv);
4979 bool fMissingInputs = false;
4980 CValidationState state;
4982 pfrom->setAskFor.erase(inv.hash);
4983 mapAlreadyAskedFor.erase(inv);
4985 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4987 mempool.check(pcoinsTip);
4988 RelayTransaction(tx);
4989 vWorkQueue.push_back(inv.hash);
4991 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4992 pfrom->id, pfrom->cleanSubVer,
4993 tx.GetHash().ToString(),
4994 mempool.mapTx.size());
4996 // Recursively process any orphan transactions that depended on this one
4997 set<NodeId> setMisbehaving;
4998 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5000 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5001 if (itByPrev == mapOrphanTransactionsByPrev.end())
5003 for (set<uint256>::iterator mi = itByPrev->second.begin();
5004 mi != itByPrev->second.end();
5007 const uint256& orphanHash = *mi;
5008 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5009 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5010 bool fMissingInputs2 = false;
5011 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5012 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5013 // anyone relaying LegitTxX banned)
5014 CValidationState stateDummy;
5017 if (setMisbehaving.count(fromPeer))
5019 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5021 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5022 RelayTransaction(orphanTx);
5023 vWorkQueue.push_back(orphanHash);
5024 vEraseQueue.push_back(orphanHash);
5026 else if (!fMissingInputs2)
5029 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5031 // Punish peer that gave us an invalid orphan tx
5032 Misbehaving(fromPeer, nDos);
5033 setMisbehaving.insert(fromPeer);
5034 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5036 // Has inputs but not accepted to mempool
5037 // Probably non-standard or insufficient fee/priority
5038 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5039 vEraseQueue.push_back(orphanHash);
5040 assert(recentRejects);
5041 recentRejects->insert(orphanHash);
5043 mempool.check(pcoinsTip);
5047 BOOST_FOREACH(uint256 hash, vEraseQueue)
5048 EraseOrphanTx(hash);
5050 // TODO: currently, prohibit joinsplits from entering mapOrphans
5051 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5053 AddOrphanTx(tx, pfrom->GetId());
5055 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5056 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5057 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5059 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5061 assert(recentRejects);
5062 recentRejects->insert(tx.GetHash());
5064 if (pfrom->fWhitelisted) {
5065 // Always relay transactions received from whitelisted peers, even
5066 // if they were already in the mempool or rejected from it due
5067 // to policy, allowing the node to function as a gateway for
5068 // nodes hidden behind it.
5070 // Never relay transactions that we would assign a non-zero DoS
5071 // score for, as we expect peers to do the same with us in that
5074 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5075 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5076 RelayTransaction(tx);
5078 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5079 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5084 if (state.IsInvalid(nDoS))
5086 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5087 pfrom->id, pfrom->cleanSubVer,
5088 state.GetRejectReason());
5089 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5090 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5092 Misbehaving(pfrom->GetId(), nDoS);
5097 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5099 std::vector<CBlockHeader> headers;
5101 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5102 unsigned int nCount = ReadCompactSize(vRecv);
5103 if (nCount > MAX_HEADERS_RESULTS) {
5104 Misbehaving(pfrom->GetId(), 20);
5105 return error("headers message size = %u", nCount);
5107 headers.resize(nCount);
5108 for (unsigned int n = 0; n < nCount; n++) {
5109 vRecv >> headers[n];
5110 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5116 // Nothing interesting. Stop asking this peers for more headers.
5120 CBlockIndex *pindexLast = NULL;
5121 BOOST_FOREACH(const CBlockHeader& header, headers) {
5122 CValidationState state;
5123 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5124 Misbehaving(pfrom->GetId(), 20);
5125 return error("non-continuous headers sequence");
5127 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5129 if (state.IsInvalid(nDoS)) {
5131 Misbehaving(pfrom->GetId(), nDoS/nDoS);
5132 return error("invalid header received");
5138 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5140 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5141 // Headers message had its maximum size; the peer may have more headers.
5142 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5143 // from there instead.
5144 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5145 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5151 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5156 CInv inv(MSG_BLOCK, block.GetHash());
5157 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5159 pfrom->AddInventoryKnown(inv);
5161 CValidationState state;
5162 // Process all blocks from whitelisted peers, even if not requested,
5163 // unless we're still syncing with the network.
5164 // Such an unrequested block may still be processed, subject to the
5165 // conditions in AcceptBlock().
5166 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5167 ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL);
5169 if (state.IsInvalid(nDoS)) {
5170 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5171 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5174 Misbehaving(pfrom->GetId(), nDoS);
5181 // This asymmetric behavior for inbound and outbound connections was introduced
5182 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5183 // to users' AddrMan and later request them by sending getaddr messages.
5184 // Making nodes which are behind NAT and can only make outgoing connections ignore
5185 // the getaddr message mitigates the attack.
5186 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5188 // Only send one GetAddr response per connection to reduce resource waste
5189 // and discourage addr stamping of INV announcements.
5190 if (pfrom->fSentAddr) {
5191 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5194 pfrom->fSentAddr = true;
5196 pfrom->vAddrToSend.clear();
5197 vector<CAddress> vAddr = addrman.GetAddr();
5198 BOOST_FOREACH(const CAddress &addr, vAddr)
5199 pfrom->PushAddress(addr);
5203 else if (strCommand == "mempool")
5205 LOCK2(cs_main, pfrom->cs_filter);
5207 std::vector<uint256> vtxid;
5208 mempool.queryHashes(vtxid);
5210 BOOST_FOREACH(uint256& hash, vtxid) {
5211 CInv inv(MSG_TX, hash);
5213 bool fInMemPool = mempool.lookup(hash, tx);
5214 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5215 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5217 vInv.push_back(inv);
5218 if (vInv.size() == MAX_INV_SZ) {
5219 pfrom->PushMessage("inv", vInv);
5223 if (vInv.size() > 0)
5224 pfrom->PushMessage("inv", vInv);
5228 else if (strCommand == "ping")
5230 if (pfrom->nVersion > BIP0031_VERSION)
5234 // Echo the message back with the nonce. This allows for two useful features:
5236 // 1) A remote node can quickly check if the connection is operational
5237 // 2) Remote nodes can measure the latency of the network thread. If this node
5238 // is overloaded it won't respond to pings quickly and the remote node can
5239 // avoid sending us more work, like chain download requests.
5241 // The nonce stops the remote getting confused between different pings: without
5242 // it, if the remote node sends a ping once per second and this node takes 5
5243 // seconds to respond to each, the 5th ping the remote sends would appear to
5244 // return very quickly.
5245 pfrom->PushMessage("pong", nonce);
5250 else if (strCommand == "pong")
5252 int64_t pingUsecEnd = nTimeReceived;
5254 size_t nAvail = vRecv.in_avail();
5255 bool bPingFinished = false;
5256 std::string sProblem;
5258 if (nAvail >= sizeof(nonce)) {
5261 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5262 if (pfrom->nPingNonceSent != 0) {
5263 if (nonce == pfrom->nPingNonceSent) {
5264 // Matching pong received, this ping is no longer outstanding
5265 bPingFinished = true;
5266 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5267 if (pingUsecTime > 0) {
5268 // Successful ping time measurement, replace previous
5269 pfrom->nPingUsecTime = pingUsecTime;
5270 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5272 // This should never happen
5273 sProblem = "Timing mishap";
5276 // Nonce mismatches are normal when pings are overlapping
5277 sProblem = "Nonce mismatch";
5279 // This is most likely a bug in another implementation somewhere; cancel this ping
5280 bPingFinished = true;
5281 sProblem = "Nonce zero";
5285 sProblem = "Unsolicited pong without ping";
5288 // This is most likely a bug in another implementation somewhere; cancel this ping
5289 bPingFinished = true;
5290 sProblem = "Short payload";
5293 if (!(sProblem.empty())) {
5294 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5298 pfrom->nPingNonceSent,
5302 if (bPingFinished) {
5303 pfrom->nPingNonceSent = 0;
5308 else if (fAlerts && strCommand == "alert")
5313 uint256 alertHash = alert.GetHash();
5314 if (pfrom->setKnown.count(alertHash) == 0)
5316 if (alert.ProcessAlert(Params().AlertKey()))
5319 pfrom->setKnown.insert(alertHash);
5322 BOOST_FOREACH(CNode* pnode, vNodes)
5323 alert.RelayTo(pnode);
5327 // Small DoS penalty so peers that send us lots of
5328 // duplicate/expired/invalid-signature/whatever alerts
5329 // eventually get banned.
5330 // This isn't a Misbehaving(100) (immediate ban) because the
5331 // peer might be an older or different implementation with
5332 // a different signature key, etc.
5333 Misbehaving(pfrom->GetId(), 10);
5339 else if (strCommand == "filterload")
5341 CBloomFilter filter;
5344 if (!filter.IsWithinSizeConstraints())
5345 // There is no excuse for sending a too-large filter
5346 Misbehaving(pfrom->GetId(), 100);
5349 LOCK(pfrom->cs_filter);
5350 delete pfrom->pfilter;
5351 pfrom->pfilter = new CBloomFilter(filter);
5352 pfrom->pfilter->UpdateEmptyFull();
5354 pfrom->fRelayTxes = true;
5358 else if (strCommand == "filteradd")
5360 vector<unsigned char> vData;
5363 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5364 // and thus, the maximum size any matched object can have) in a filteradd message
5365 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5367 Misbehaving(pfrom->GetId(), 100);
5369 LOCK(pfrom->cs_filter);
5371 pfrom->pfilter->insert(vData);
5373 Misbehaving(pfrom->GetId(), 100);
5378 else if (strCommand == "filterclear")
5380 LOCK(pfrom->cs_filter);
5381 delete pfrom->pfilter;
5382 pfrom->pfilter = new CBloomFilter();
5383 pfrom->fRelayTxes = true;
5387 else if (strCommand == "reject")
5391 string strMsg; unsigned char ccode; string strReason;
5392 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5395 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5397 if (strMsg == "block" || strMsg == "tx")
5401 ss << ": hash " << hash.ToString();
5403 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5404 } catch (const std::ios_base::failure&) {
5405 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5406 LogPrint("net", "Unparseable reject message received\n");
5410 else if (strCommand == "notfound") {
5411 // We do not care about the NOTFOUND message, but logging an Unknown Command
5412 // message would be undesirable as we transmit it ourselves.
5416 // Ignore unknown commands for extensibility
5417 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5425 // requires LOCK(cs_vRecvMsg)
5426 bool ProcessMessages(CNode* pfrom)
5429 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5433 // (4) message start
5441 if (!pfrom->vRecvGetData.empty())
5442 ProcessGetData(pfrom);
5444 // this maintains the order of responses
5445 if (!pfrom->vRecvGetData.empty()) return fOk;
5447 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5448 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5449 // Don't bother if send buffer is too full to respond anyway
5450 if (pfrom->nSendSize >= SendBufferSize())
5454 CNetMessage& msg = *it;
5457 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5458 // msg.hdr.nMessageSize, msg.vRecv.size(),
5459 // msg.complete() ? "Y" : "N");
5461 // end, if an incomplete message is found
5462 if (!msg.complete())
5465 // at this point, any failure means we can delete the current message
5468 // Scan for message start
5469 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5470 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5476 CMessageHeader& hdr = msg.hdr;
5477 if (!hdr.IsValid(Params().MessageStart()))
5479 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5482 string strCommand = hdr.GetCommand();
5485 unsigned int nMessageSize = hdr.nMessageSize;
5488 CDataStream& vRecv = msg.vRecv;
5489 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5490 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5491 if (nChecksum != hdr.nChecksum)
5493 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5494 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5502 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5503 boost::this_thread::interruption_point();
5505 catch (const std::ios_base::failure& e)
5507 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5508 if (strstr(e.what(), "end of data"))
5510 // Allow exceptions from under-length message on vRecv
5511 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());
5513 else if (strstr(e.what(), "size too large"))
5515 // Allow exceptions from over-long size
5516 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5520 //PrintExceptionContinue(&e, "ProcessMessages()");
5523 catch (const boost::thread_interrupted&) {
5526 catch (const std::exception& e) {
5527 PrintExceptionContinue(&e, "ProcessMessages()");
5529 PrintExceptionContinue(NULL, "ProcessMessages()");
5533 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5538 // In case the connection got shut down, its receive buffer was wiped
5539 if (!pfrom->fDisconnect)
5540 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5546 bool SendMessages(CNode* pto, bool fSendTrickle)
5548 const Consensus::Params& consensusParams = Params().GetConsensus();
5550 // Don't send anything until we get its version message
5551 if (pto->nVersion == 0)
5557 bool pingSend = false;
5558 if (pto->fPingQueued) {
5559 // RPC ping request by user
5562 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5563 // Ping automatically sent as a latency probe & keepalive.
5568 while (nonce == 0) {
5569 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5571 pto->fPingQueued = false;
5572 pto->nPingUsecStart = GetTimeMicros();
5573 if (pto->nVersion > BIP0031_VERSION) {
5574 pto->nPingNonceSent = nonce;
5575 pto->PushMessage("ping", nonce);
5577 // Peer is too old to support ping command with nonce, pong will never arrive.
5578 pto->nPingNonceSent = 0;
5579 pto->PushMessage("ping");
5583 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5587 // Address refresh broadcast
5588 static int64_t nLastRebroadcast;
5589 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5592 BOOST_FOREACH(CNode* pnode, vNodes)
5594 // Periodically clear addrKnown to allow refresh broadcasts
5595 if (nLastRebroadcast)
5596 pnode->addrKnown.reset();
5598 // Rebroadcast our address
5599 AdvertizeLocal(pnode);
5601 if (!vNodes.empty())
5602 nLastRebroadcast = GetTime();
5610 vector<CAddress> vAddr;
5611 vAddr.reserve(pto->vAddrToSend.size());
5612 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5614 if (!pto->addrKnown.contains(addr.GetKey()))
5616 pto->addrKnown.insert(addr.GetKey());
5617 vAddr.push_back(addr);
5618 // receiver rejects addr messages larger than 1000
5619 if (vAddr.size() >= 1000)
5621 pto->PushMessage("addr", vAddr);
5626 pto->vAddrToSend.clear();
5628 pto->PushMessage("addr", vAddr);
5631 CNodeState &state = *State(pto->GetId());
5632 if (state.fShouldBan) {
5633 if (pto->fWhitelisted)
5634 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5636 pto->fDisconnect = true;
5637 if (pto->addr.IsLocal())
5638 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5641 CNode::Ban(pto->addr);
5644 state.fShouldBan = false;
5647 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5648 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5649 state.rejects.clear();
5652 if (pindexBestHeader == NULL)
5653 pindexBestHeader = chainActive.Tip();
5654 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.
5655 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5656 // Only actively request headers from a single peer, unless we're close to today.
5657 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5658 state.fSyncStarted = true;
5660 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5661 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5662 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5666 // Resend wallet transactions that haven't gotten in a block yet
5667 // Except during reindex, importing and IBD, when old wallet
5668 // transactions become unconfirmed and spams other nodes.
5669 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5671 GetMainSignals().Broadcast(nTimeBestReceived);
5675 // Message: inventory
5678 vector<CInv> vInvWait;
5680 LOCK(pto->cs_inventory);
5681 vInv.reserve(pto->vInventoryToSend.size());
5682 vInvWait.reserve(pto->vInventoryToSend.size());
5683 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5685 if (pto->setInventoryKnown.count(inv))
5688 // trickle out tx inv to protect privacy
5689 if (inv.type == MSG_TX && !fSendTrickle)
5691 // 1/4 of tx invs blast to all immediately
5692 static uint256 hashSalt;
5693 if (hashSalt.IsNull())
5694 hashSalt = GetRandHash();
5695 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5696 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5697 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5701 vInvWait.push_back(inv);
5706 // returns true if wasn't already contained in the set
5707 if (pto->setInventoryKnown.insert(inv).second)
5709 vInv.push_back(inv);
5710 if (vInv.size() >= 1000)
5712 pto->PushMessage("inv", vInv);
5717 pto->vInventoryToSend = vInvWait;
5720 pto->PushMessage("inv", vInv);
5722 // Detect whether we're stalling
5723 int64_t nNow = GetTimeMicros();
5724 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5725 // Stalling only triggers when the block download window cannot move. During normal steady state,
5726 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5727 // should only happen during initial block download.
5728 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5729 pto->fDisconnect = true;
5731 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5732 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5733 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5734 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5735 // to unreasonably increase our timeout.
5736 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5737 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5738 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5739 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5740 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5741 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5742 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5743 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5744 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5745 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5746 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5748 if (queuedBlock.nTimeDisconnect < nNow) {
5749 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5750 pto->fDisconnect = true;
5755 // Message: getdata (blocks)
5757 vector<CInv> vGetData;
5758 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5759 vector<CBlockIndex*> vToDownload;
5760 NodeId staller = -1;
5761 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5762 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5763 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5764 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5765 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5766 pindex->nHeight, pto->id);
5768 if (state.nBlocksInFlight == 0 && staller != -1) {
5769 if (State(staller)->nStallingSince == 0) {
5770 State(staller)->nStallingSince = nNow;
5771 LogPrint("net", "Stall started peer=%d\n", staller);
5777 // Message: getdata (non-blocks)
5779 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5781 const CInv& inv = (*pto->mapAskFor.begin()).second;
5782 if (!AlreadyHave(inv))
5785 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5786 vGetData.push_back(inv);
5787 if (vGetData.size() >= 1000)
5789 pto->PushMessage("getdata", vGetData);
5793 //If we're not going to ask, don't expect a response.
5794 pto->setAskFor.erase(inv.hash);
5796 pto->mapAskFor.erase(pto->mapAskFor.begin());
5798 if (!vGetData.empty())
5799 pto->PushMessage("getdata", vGetData);
5805 std::string CBlockFileInfo::ToString() const {
5806 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));
5817 BlockMap::iterator it1 = mapBlockIndex.begin();
5818 for (; it1 != mapBlockIndex.end(); it1++)
5819 delete (*it1).second;
5820 mapBlockIndex.clear();
5822 // orphan transactions
5823 mapOrphanTransactions.clear();
5824 mapOrphanTransactionsByPrev.clear();
5826 } instance_of_cmaincleanup;
5828 extern "C" const char* getDataDir()
5830 return GetDataDir().string().c_str();