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 - 10);
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 && chainActive.Tip()->nHeight < 350000 )
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 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);
1814 nValueIn += interest;
1819 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1820 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1821 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1825 nValueIn += tx.GetJoinSplitValueIn();
1826 if (!MoneyRange(nValueIn))
1827 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1828 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1830 if (nValueIn < tx.GetValueOut())
1831 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f",
1832 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout");
1834 // Tally transaction fees
1835 CAmount nTxFee = nValueIn - tx.GetValueOut();
1837 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1838 REJECT_INVALID, "bad-txns-fee-negative");
1840 if (!MoneyRange(nFees))
1841 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1842 REJECT_INVALID, "bad-txns-fee-outofrange");
1845 }// namespace Consensus
1847 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)
1849 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams))
1852 if (!tx.IsCoinBase())
1855 pvChecks->reserve(tx.vin.size());
1857 // The first loop above does all the inexpensive checks.
1858 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1859 // Helps prevent CPU exhaustion attacks.
1861 // Skip ECDSA signature verification when connecting blocks
1862 // before the last block chain checkpoint. This is safe because block merkle hashes are
1863 // still computed and checked, and any change will be caught at the next checkpoint.
1864 if (fScriptChecks) {
1865 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1866 const COutPoint &prevout = tx.vin[i].prevout;
1867 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1871 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1873 pvChecks->push_back(CScriptCheck());
1874 check.swap(pvChecks->back());
1875 } else if (!check()) {
1876 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1877 // Check whether the failure was caused by a
1878 // non-mandatory script verification check, such as
1879 // non-standard DER encodings or non-null dummy
1880 // arguments; if so, don't trigger DoS protection to
1881 // avoid splitting the network between upgraded and
1882 // non-upgraded nodes.
1883 CScriptCheck check(*coins, tx, i,
1884 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1886 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1888 // Failures of other flags indicate a transaction that is
1889 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1890 // such nodes as they are not following the protocol. That
1891 // said during an upgrade careful thought should be taken
1892 // as to the correct behavior - we may want to continue
1893 // peering with non-upgraded nodes even after a soft-fork
1894 // super-majority vote has passed.
1895 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1905 /*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)
1907 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1908 fprintf(stderr,"ContextualCheckInputs failure.0\n");
1912 if (!tx.IsCoinBase())
1914 // While checking, GetBestBlock() refers to the parent block.
1915 // This is also true for mempool checks.
1916 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1917 int nSpendHeight = pindexPrev->nHeight + 1;
1918 for (unsigned int i = 0; i < tx.vin.size(); i++)
1920 const COutPoint &prevout = tx.vin[i].prevout;
1921 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1922 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1926 // If prev is coinbase, check that it's matured
1927 if (coins->IsCoinBase()) {
1928 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1929 COINBASE_MATURITY = _COINBASE_MATURITY;
1930 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1931 fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size());
1933 return state.Invalid(
1934 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1945 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1947 // Open history file to append
1948 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1949 if (fileout.IsNull())
1950 return error("%s: OpenUndoFile failed", __func__);
1952 // Write index header
1953 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1954 fileout << FLATDATA(messageStart) << nSize;
1957 long fileOutPos = ftell(fileout.Get());
1959 return error("%s: ftell failed", __func__);
1960 pos.nPos = (unsigned int)fileOutPos;
1961 fileout << blockundo;
1963 // calculate & write checksum
1964 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1965 hasher << hashBlock;
1966 hasher << blockundo;
1967 fileout << hasher.GetHash();
1972 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1974 // Open history file to read
1975 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1976 if (filein.IsNull())
1977 return error("%s: OpenBlockFile failed", __func__);
1980 uint256 hashChecksum;
1982 filein >> blockundo;
1983 filein >> hashChecksum;
1985 catch (const std::exception& e) {
1986 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1990 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1991 hasher << hashBlock;
1992 hasher << blockundo;
1993 if (hashChecksum != hasher.GetHash())
1994 return error("%s: Checksum mismatch", __func__);
1999 /** Abort with a message */
2000 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2002 strMiscWarning = strMessage;
2003 LogPrintf("*** %s\n", strMessage);
2004 uiInterface.ThreadSafeMessageBox(
2005 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2006 "", CClientUIInterface::MSG_ERROR);
2011 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2013 AbortNode(strMessage, userMessage);
2014 return state.Error(strMessage);
2020 * Apply the undo operation of a CTxInUndo to the given chain state.
2021 * @param undo The undo object.
2022 * @param view The coins view to which to apply the changes.
2023 * @param out The out point that corresponds to the tx input.
2024 * @return True on success.
2026 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2030 CCoinsModifier coins = view.ModifyCoins(out.hash);
2031 if (undo.nHeight != 0) {
2032 // undo data contains height: this is the last output of the prevout tx being spent
2033 if (!coins->IsPruned())
2034 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2036 coins->fCoinBase = undo.fCoinBase;
2037 coins->nHeight = undo.nHeight;
2038 coins->nVersion = undo.nVersion;
2040 if (coins->IsPruned())
2041 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2043 if (coins->IsAvailable(out.n))
2044 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2045 if (coins->vout.size() < out.n+1)
2046 coins->vout.resize(out.n+1);
2047 coins->vout[out.n] = undo.txout;
2052 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2054 assert(pindex->GetBlockHash() == view.GetBestBlock());
2060 komodo_disconnect(pindex,block);
2061 CBlockUndo blockUndo;
2062 CDiskBlockPos pos = pindex->GetUndoPos();
2064 return error("DisconnectBlock(): no undo data available");
2065 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2066 return error("DisconnectBlock(): failure reading undo data");
2068 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2069 return error("DisconnectBlock(): block and undo data inconsistent");
2071 // undo transactions in reverse order
2072 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2073 const CTransaction &tx = block.vtx[i];
2074 uint256 hash = tx.GetHash();
2076 // Check that all outputs are available and match the outputs in the block itself
2079 CCoinsModifier outs = view.ModifyCoins(hash);
2080 outs->ClearUnspendable();
2082 CCoins outsBlock(tx, pindex->nHeight);
2083 // The CCoins serialization does not serialize negative numbers.
2084 // No network rules currently depend on the version here, so an inconsistency is harmless
2085 // but it must be corrected before txout nversion ever influences a network rule.
2086 if (outsBlock.nVersion < 0)
2087 outs->nVersion = outsBlock.nVersion;
2088 if (*outs != outsBlock)
2089 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2095 // unspend nullifiers
2096 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2097 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2098 view.SetNullifier(nf, false);
2103 if (i > 0) { // not coinbases
2104 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2105 if (txundo.vprevout.size() != tx.vin.size())
2106 return error("DisconnectBlock(): transaction and undo data inconsistent");
2107 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2108 const COutPoint &out = tx.vin[j].prevout;
2109 const CTxInUndo &undo = txundo.vprevout[j];
2110 if (!ApplyTxInUndo(undo, view, out))
2116 // set the old best anchor back
2117 view.PopAnchor(blockUndo.old_tree_root);
2119 // move best block pointer to prevout block
2120 view.SetBestBlock(pindex->pprev->GetBlockHash());
2130 void static FlushBlockFile(bool fFinalize = false)
2132 LOCK(cs_LastBlockFile);
2134 CDiskBlockPos posOld(nLastBlockFile, 0);
2136 FILE *fileOld = OpenBlockFile(posOld);
2139 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2140 FileCommit(fileOld);
2144 fileOld = OpenUndoFile(posOld);
2147 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2148 FileCommit(fileOld);
2153 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2155 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2157 void ThreadScriptCheck() {
2158 RenameThread("zcash-scriptch");
2159 scriptcheckqueue.Thread();
2163 // Called periodically asynchronously; alerts if it smells like
2164 // we're being fed a bad chain (blocks being generated much
2165 // too slowly or too quickly).
2167 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2168 int64_t nPowTargetSpacing)
2170 if (bestHeader == NULL || initialDownloadCheck()) return;
2172 static int64_t lastAlertTime = 0;
2173 int64_t now = GetAdjustedTime();
2174 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2176 const int SPAN_HOURS=4;
2177 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2178 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2180 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2182 std::string strWarning;
2183 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2186 const CBlockIndex* i = bestHeader;
2188 while (i->GetBlockTime() >= startTime) {
2191 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2194 // How likely is it to find that many by chance?
2195 double p = boost::math::pdf(poisson, nBlocks);
2197 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2198 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2200 // Aim for one false-positive about every fifty years of normal running:
2201 const int FIFTY_YEARS = 50*365*24*60*60;
2202 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2204 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2206 // Many fewer blocks than expected: alert!
2207 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2208 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2210 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2212 // Many more blocks than expected: alert!
2213 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2214 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2216 if (!strWarning.empty())
2218 strMiscWarning = strWarning;
2219 CAlert::Notify(strWarning, true);
2220 lastAlertTime = now;
2224 static int64_t nTimeVerify = 0;
2225 static int64_t nTimeConnect = 0;
2226 static int64_t nTimeIndex = 0;
2227 static int64_t nTimeCallbacks = 0;
2228 static int64_t nTimeTotal = 0;
2230 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2232 const CChainParams& chainparams = Params();
2233 //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight);
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 //fprintf(stderr,"chaintip false\n");
2663 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2667 static int64_t nTimeReadFromDisk = 0;
2668 static int64_t nTimeConnectTotal = 0;
2669 static int64_t nTimeFlush = 0;
2670 static int64_t nTimeChainState = 0;
2671 static int64_t nTimePostConnect = 0;
2674 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2675 * corresponding to pindexNew, to bypass loading it again from disk.
2677 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2679 assert(pindexNew->pprev == chainActive.Tip());
2680 mempool.check(pcoinsTip);
2681 // Read block from disk.
2682 int64_t nTime1 = GetTimeMicros();
2685 if (!ReadBlockFromDisk(block, pindexNew))
2686 return AbortNode(state, "Failed to read block");
2689 // Get the current commitment tree
2690 ZCIncrementalMerkleTree oldTree;
2691 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2692 // Apply the block atomically to the chain state.
2693 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2695 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2697 CCoinsViewCache view(pcoinsTip);
2698 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2699 GetMainSignals().BlockChecked(*pblock, state);
2701 if (state.IsInvalid())
2702 InvalidBlockFound(pindexNew, state);
2703 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2705 mapBlockSource.erase(pindexNew->GetBlockHash());
2706 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2707 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2708 assert(view.Flush());
2710 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2711 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2712 // Write the chain state to disk, if necessary.
2713 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2715 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2716 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2717 // Remove conflicting transactions from the mempool.
2718 list<CTransaction> txConflicted;
2719 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2720 mempool.check(pcoinsTip);
2721 // Update chainActive & related variables.
2722 UpdateTip(pindexNew);
2723 // Tell wallet about transactions that went from mempool
2725 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2726 SyncWithWallets(tx, NULL);
2728 // ... and about transactions that got confirmed:
2729 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2730 SyncWithWallets(tx, pblock);
2732 // Update cached incremental witnesses
2733 //fprintf(stderr,"chaintip true\n");
2734 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2736 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2737 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2738 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2743 * Return the tip of the chain with the most work in it, that isn't
2744 * known to be invalid (it's however far from certain to be valid).
2746 static CBlockIndex* FindMostWorkChain() {
2748 CBlockIndex *pindexNew = NULL;
2750 // Find the best candidate header.
2752 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2753 if (it == setBlockIndexCandidates.rend())
2758 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2759 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2760 CBlockIndex *pindexTest = pindexNew;
2761 bool fInvalidAncestor = false;
2762 while (pindexTest && !chainActive.Contains(pindexTest)) {
2763 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2765 // Pruned nodes may have entries in setBlockIndexCandidates for
2766 // which block files have been deleted. Remove those as candidates
2767 // for the most work chain if we come across them; we can't switch
2768 // to a chain unless we have all the non-active-chain parent blocks.
2769 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2770 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2771 if (fFailedChain || fMissingData) {
2772 // Candidate chain is not usable (either invalid or missing data)
2773 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2774 pindexBestInvalid = pindexNew;
2775 CBlockIndex *pindexFailed = pindexNew;
2776 // Remove the entire chain from the set.
2777 while (pindexTest != pindexFailed) {
2779 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2780 } else if (fMissingData) {
2781 // If we're missing data, then add back to mapBlocksUnlinked,
2782 // so that if the block arrives in the future we can try adding
2783 // to setBlockIndexCandidates again.
2784 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2786 setBlockIndexCandidates.erase(pindexFailed);
2787 pindexFailed = pindexFailed->pprev;
2789 setBlockIndexCandidates.erase(pindexTest);
2790 fInvalidAncestor = true;
2793 pindexTest = pindexTest->pprev;
2795 if (!fInvalidAncestor)
2800 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2801 static void PruneBlockIndexCandidates() {
2802 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2803 // reorganization to a better block fails.
2804 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2805 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2806 setBlockIndexCandidates.erase(it++);
2808 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2809 assert(!setBlockIndexCandidates.empty());
2813 * Try to make some progress towards making pindexMostWork the active block.
2814 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2816 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2817 AssertLockHeld(cs_main);
2818 bool fInvalidFound = false;
2819 const CBlockIndex *pindexOldTip = chainActive.Tip();
2820 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2822 // Disconnect active blocks which are no longer in the best chain.
2823 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2824 if (!DisconnectTip(state))
2827 if ( KOMODO_REWIND != 0 )
2829 fprintf(stderr,"rewind start ht.%d\n",chainActive.Tip()->nHeight);
2830 while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND )
2832 if ( !DisconnectTip(state) )
2834 InvalidateBlock(state,chainActive.Tip());
2838 fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli stop\n",KOMODO_REWIND);
2843 // Build list of new blocks to connect.
2844 std::vector<CBlockIndex*> vpindexToConnect;
2845 bool fContinue = true;
2846 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2847 while (fContinue && nHeight != pindexMostWork->nHeight) {
2848 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2849 // a few blocks along the way.
2850 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2851 vpindexToConnect.clear();
2852 vpindexToConnect.reserve(nTargetHeight - nHeight);
2853 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2854 while (pindexIter && pindexIter->nHeight != nHeight) {
2855 vpindexToConnect.push_back(pindexIter);
2856 pindexIter = pindexIter->pprev;
2858 nHeight = nTargetHeight;
2860 // Connect new blocks.
2861 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2862 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2863 if (state.IsInvalid()) {
2864 // The block violates a consensus rule.
2865 if (!state.CorruptionPossible())
2866 InvalidChainFound(vpindexToConnect.back());
2867 state = CValidationState();
2868 fInvalidFound = true;
2872 // A system error occurred (disk space, database error, ...).
2876 PruneBlockIndexCandidates();
2877 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2878 // We're in a better position than we were. Return temporarily to release the lock.
2886 // Callbacks/notifications for a new best chain.
2888 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2890 CheckForkWarningConditions();
2896 * Make the best chain active, in multiple steps. The result is either failure
2897 * or an activated best chain. pblock is either NULL or a pointer to a block
2898 * that is already loaded (to avoid loading it again from disk).
2900 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2901 CBlockIndex *pindexNewTip = NULL;
2902 CBlockIndex *pindexMostWork = NULL;
2903 const CChainParams& chainParams = Params();
2905 boost::this_thread::interruption_point();
2907 bool fInitialDownload;
2910 pindexMostWork = FindMostWorkChain();
2912 // Whether we have anything to do at all.
2913 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2916 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2918 pindexNewTip = chainActive.Tip();
2919 fInitialDownload = IsInitialBlockDownload();
2921 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2923 // Notifications/callbacks that can run without cs_main
2924 if (!fInitialDownload) {
2925 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2926 // Relay inventory, but don't relay old inventory during initial block download.
2927 int nBlockEstimate = 0;
2928 if (fCheckpointsEnabled)
2929 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2930 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2931 // in a stalled download if the block file is pruned before the request.
2932 if (nLocalServices & NODE_NETWORK) {
2934 BOOST_FOREACH(CNode* pnode, vNodes)
2935 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2936 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2938 // Notify external listeners about the new tip.
2939 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2940 uiInterface.NotifyBlockTip(hashNewTip);
2941 } //else fprintf(stderr,"initial download skips propagation\n");
2942 } while(pindexMostWork != chainActive.Tip());
2945 // Write changes periodically to disk, after relay.
2946 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2953 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2954 AssertLockHeld(cs_main);
2956 // Mark the block itself as invalid.
2957 pindex->nStatus |= BLOCK_FAILED_VALID;
2958 setDirtyBlockIndex.insert(pindex);
2959 setBlockIndexCandidates.erase(pindex);
2961 while (chainActive.Contains(pindex)) {
2962 CBlockIndex *pindexWalk = chainActive.Tip();
2963 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2964 setDirtyBlockIndex.insert(pindexWalk);
2965 setBlockIndexCandidates.erase(pindexWalk);
2966 // ActivateBestChain considers blocks already in chainActive
2967 // unconditionally valid already, so force disconnect away from it.
2968 if (!DisconnectTip(state)) {
2972 //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2974 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2976 BlockMap::iterator it = mapBlockIndex.begin();
2977 while (it != mapBlockIndex.end() && it->second != 0 ) {
2978 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2979 setBlockIndexCandidates.insert(it->second);
2984 InvalidChainFound(pindex);
2988 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2989 AssertLockHeld(cs_main);
2991 int nHeight = pindex->nHeight;
2993 // Remove the invalidity flag from this block and all its descendants.
2994 BlockMap::iterator it = mapBlockIndex.begin();
2995 while (it != mapBlockIndex.end()) {
2996 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2997 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2998 setDirtyBlockIndex.insert(it->second);
2999 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3000 setBlockIndexCandidates.insert(it->second);
3002 if (it->second == pindexBestInvalid) {
3003 // Reset invalid block marker if it was pointing to one of those.
3004 pindexBestInvalid = NULL;
3010 // Remove the invalidity flag from all ancestors too.
3011 while (pindex != NULL) {
3012 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3013 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3014 setDirtyBlockIndex.insert(pindex);
3016 pindex = pindex->pprev;
3021 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3023 // Check for duplicate
3024 uint256 hash = block.GetHash();
3025 BlockMap::iterator it = mapBlockIndex.find(hash);
3026 if (it != mapBlockIndex.end())
3029 // Construct new block index object
3030 CBlockIndex* pindexNew = new CBlockIndex(block);
3032 // We assign the sequence id to blocks only when the full data is available,
3033 // to avoid miners withholding blocks but broadcasting headers, to get a
3034 // competitive advantage.
3035 pindexNew->nSequenceId = 0;
3036 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3037 pindexNew->phashBlock = &((*mi).first);
3038 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3039 if (miPrev != mapBlockIndex.end())
3041 pindexNew->pprev = (*miPrev).second;
3042 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3043 pindexNew->BuildSkip();
3045 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3046 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3047 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3048 pindexBestHeader = pindexNew;
3050 setDirtyBlockIndex.insert(pindexNew);
3055 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3056 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3058 pindexNew->nTx = block.vtx.size();
3059 pindexNew->nChainTx = 0;
3060 pindexNew->nFile = pos.nFile;
3061 pindexNew->nDataPos = pos.nPos;
3062 pindexNew->nUndoPos = 0;
3063 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3064 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3065 setDirtyBlockIndex.insert(pindexNew);
3067 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3068 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3069 deque<CBlockIndex*> queue;
3070 queue.push_back(pindexNew);
3072 // Recursively process any descendant blocks that now may be eligible to be connected.
3073 while (!queue.empty()) {
3074 CBlockIndex *pindex = queue.front();
3076 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3078 LOCK(cs_nBlockSequenceId);
3079 pindex->nSequenceId = nBlockSequenceId++;
3081 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3082 setBlockIndexCandidates.insert(pindex);
3084 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3085 while (range.first != range.second) {
3086 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3087 queue.push_back(it->second);
3089 mapBlocksUnlinked.erase(it);
3093 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3094 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3101 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3103 LOCK(cs_LastBlockFile);
3105 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3106 if (vinfoBlockFile.size() <= nFile) {
3107 vinfoBlockFile.resize(nFile + 1);
3111 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3113 if (vinfoBlockFile.size() <= nFile) {
3114 vinfoBlockFile.resize(nFile + 1);
3118 pos.nPos = vinfoBlockFile[nFile].nSize;
3121 if (nFile != nLastBlockFile) {
3123 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3125 FlushBlockFile(!fKnown);
3126 nLastBlockFile = nFile;
3129 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3131 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3133 vinfoBlockFile[nFile].nSize += nAddSize;
3136 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3137 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3138 if (nNewChunks > nOldChunks) {
3140 fCheckForPruning = true;
3141 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3142 FILE *file = OpenBlockFile(pos);
3144 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3145 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3150 return state.Error("out of disk space");
3154 setDirtyFileInfo.insert(nFile);
3158 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3162 LOCK(cs_LastBlockFile);
3164 unsigned int nNewSize;
3165 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3166 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3167 setDirtyFileInfo.insert(nFile);
3169 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3170 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3171 if (nNewChunks > nOldChunks) {
3173 fCheckForPruning = true;
3174 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3175 FILE *file = OpenUndoFile(pos);
3177 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3178 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3183 return state.Error("out of disk space");
3189 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3191 uint8_t pubkey33[33];
3195 uint256 hash; int32_t i;
3196 hash = blockhdr.GetHash();
3197 for (i=31; i>=0; i--)
3198 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3199 fprintf(stderr," <- CheckBlockHeader\n");
3200 if ( chainActive.Tip() != 0 )
3202 hash = chainActive.Tip()->GetBlockHash();
3203 for (i=31; i>=0; i--)
3204 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3205 fprintf(stderr," <- chainTip\n");
3208 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3209 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3210 // Check block version
3211 //if (block.nVersion < MIN_BLOCK_VERSION)
3212 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3214 // Check Equihash solution is valid
3215 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3216 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3218 // Check proof of work matches claimed amount
3219 komodo_index2pubkey33(pubkey33,pindex,height);
3220 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3221 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3225 int32_t komodo_check_deposit(int32_t height,const CBlock& block);
3226 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
3227 libzcash::ProofVerifier& verifier,
3228 bool fCheckPOW, bool fCheckMerkleRoot)
3230 // These are checks that are independent of context.
3232 // Check that the header is valid (particularly PoW). This is mostly
3233 // redundant with the call in AcceptBlockHeader.
3234 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3237 // Check the merkle root.
3238 if (fCheckMerkleRoot) {
3240 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3241 if (block.hashMerkleRoot != hashMerkleRoot2)
3242 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3243 REJECT_INVALID, "bad-txnmrklroot", true);
3245 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3246 // of transactions in a block without affecting the merkle root of a block,
3247 // while still invalidating it.
3249 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3250 REJECT_INVALID, "bad-txns-duplicate", true);
3253 // All potential-corruption validation must be done before we do any
3254 // transaction validation, as otherwise we may mark the header as invalid
3255 // because we receive the wrong transactions for it.
3258 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3259 return state.DoS(100, error("CheckBlock(): size limits failed"),
3260 REJECT_INVALID, "bad-blk-length");
3262 // First transaction must be coinbase, the rest must not be
3263 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3264 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3265 REJECT_INVALID, "bad-cb-missing");
3266 for (unsigned int i = 1; i < block.vtx.size(); i++)
3267 if (block.vtx[i].IsCoinBase())
3268 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3269 REJECT_INVALID, "bad-cb-multiple");
3271 // Check transactions
3272 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3274 if ( komodo_validate_interest(tx,komodo_block2height((CBlock *)&block),block.nTime,1) < 0 )
3275 return error("CheckBlock: komodo_validate_interest failed");
3276 if (!CheckTransaction(tx, state, verifier))
3277 return error("CheckBlock(): CheckTransaction failed");
3279 unsigned int nSigOps = 0;
3280 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3282 nSigOps += GetLegacySigOpCount(tx);
3284 if (nSigOps > MAX_BLOCK_SIGOPS)
3285 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3286 REJECT_INVALID, "bad-blk-sigops", true);
3287 if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block) < 0 )
3289 static uint32_t counter;
3290 if ( counter++ < 100 )
3291 fprintf(stderr,"check deposit rejection\n");
3297 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3299 const CChainParams& chainParams = Params();
3300 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3301 uint256 hash = block.GetHash();
3302 if (hash == consensusParams.hashGenesisBlock)
3307 int nHeight = pindexPrev->nHeight+1;
3309 // Check proof of work
3310 if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3312 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3313 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3314 REJECT_INVALID, "bad-diffbits");
3317 // Check timestamp against prev
3318 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3319 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3320 REJECT_INVALID, "time-too-old");
3322 if (fCheckpointsEnabled)
3324 // Check that the block chain matches the known block chain up to a checkpoint
3325 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3326 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3328 // Don't accept any forks from the main chain prior to last checkpoint
3329 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3330 int32_t notarized_height;
3331 if (pcheckpoint && (nHeight < pcheckpoint->nHeight || nHeight == 1 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight > 1) )
3332 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3333 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3334 return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3336 // Reject block.nVersion < 4 blocks
3337 if (block.nVersion < 4)
3338 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3339 REJECT_OBSOLETE, "bad-version");
3344 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3346 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3347 const Consensus::Params& consensusParams = Params().GetConsensus();
3349 // Check that all transactions are finalized
3350 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3351 int nLockTimeFlags = 0;
3352 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3353 ? pindexPrev->GetMedianTimePast()
3354 : block.GetBlockTime();
3355 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3356 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3360 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3361 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3362 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3363 // This rule is not applied to the genesis block, which didn't include the height
3367 CScript expect = CScript() << nHeight;
3368 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3369 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3370 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3377 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3379 const CChainParams& chainparams = Params();
3380 AssertLockHeld(cs_main);
3381 // Check for duplicate
3382 uint256 hash = block.GetHash();
3383 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3384 CBlockIndex *pindex = NULL;
3385 if (miSelf != mapBlockIndex.end()) {
3386 // Block header is already known.
3387 pindex = miSelf->second;
3390 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3391 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3395 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3398 // Get prev block index
3399 CBlockIndex* pindexPrev = NULL;
3400 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3401 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3402 if (mi == mapBlockIndex.end())
3403 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3404 pindexPrev = (*mi).second;
3405 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3406 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3408 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3411 pindex = AddToBlockIndex(block);
3417 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3419 const CChainParams& chainparams = Params();
3420 AssertLockHeld(cs_main);
3422 CBlockIndex *&pindex = *ppindex;
3423 if (!AcceptBlockHeader(block, state, &pindex))
3427 fprintf(stderr,"AcceptBlock error null pindex\n");
3430 // Try to process all requested blocks that we don't have, but only
3431 // process an unrequested block if it's new and has enough work to
3432 // advance our tip, and isn't too many blocks ahead.
3433 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3434 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3435 // Blocks that are too out-of-order needlessly limit the effectiveness of
3436 // pruning, because pruning will not delete block files that contain any
3437 // blocks which are too close in height to the tip. Apply this test
3438 // regardless of whether pruning is enabled; it should generally be safe to
3439 // not process unrequested blocks.
3440 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3442 // TODO: deal better with return value and error conditions for duplicate
3443 // and unrequested blocks.
3444 if (fAlreadyHave) return true;
3445 if (!fRequested) { // If we didn't ask for it:
3446 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3447 if (!fHasMoreWork) return true; // Don't process less-work chains
3448 if (fTooFarAhead) return true; // Block height is too high
3451 // See method docstring for why this is always disabled
3452 auto verifier = libzcash::ProofVerifier::Disabled();
3453 if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3454 if (state.IsInvalid() && !state.CorruptionPossible()) {
3455 pindex->nStatus |= BLOCK_FAILED_VALID;
3456 setDirtyBlockIndex.insert(pindex);
3461 int nHeight = pindex->nHeight;
3463 // Write block to history file
3465 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3466 CDiskBlockPos blockPos;
3469 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3470 return error("AcceptBlock(): FindBlockPos failed");
3472 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3473 AbortNode(state, "Failed to write block");
3474 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3475 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3476 } catch (const std::runtime_error& e) {
3477 return AbortNode(state, std::string("System error: ") + e.what());
3480 if (fCheckForPruning)
3481 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3486 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3488 unsigned int nFound = 0;
3489 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3491 if (pstart->nVersion >= minVersion)
3493 pstart = pstart->pprev;
3495 return (nFound >= nRequired);
3498 void komodo_currentheight_set(int32_t height);
3500 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3502 // Preliminary checks
3504 auto verifier = libzcash::ProofVerifier::Disabled();
3505 if ( chainActive.Tip() != 0 )
3506 komodo_currentheight_set(chainActive.Tip()->nHeight);
3507 if ( ASSETCHAINS_SYMBOL[0] == 0 )
3508 checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3509 else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3512 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3513 fRequested |= fForceProcessing;
3516 Misbehaving(pfrom->GetId(), 1);
3517 return error("%s: CheckBlock FAILED", __func__);
3521 CBlockIndex *pindex = NULL;
3522 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3523 if (pindex && pfrom) {
3524 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3528 return error("%s: AcceptBlock FAILED", __func__);
3531 if (!ActivateBestChain(state, pblock))
3532 return error("%s: ActivateBestChain failed", __func__);
3537 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3539 AssertLockHeld(cs_main);
3540 assert(pindexPrev == chainActive.Tip());
3542 CCoinsViewCache viewNew(pcoinsTip);
3543 CBlockIndex indexDummy(block);
3544 indexDummy.pprev = pindexPrev;
3545 indexDummy.nHeight = pindexPrev->nHeight + 1;
3546 // JoinSplit proofs are verified in ConnectBlock
3547 auto verifier = libzcash::ProofVerifier::Disabled();
3549 // NOTE: CheckBlockHeader is called by CheckBlock
3550 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3552 fprintf(stderr,"TestBlockValidity failure A\n");
3555 if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3557 //fprintf(stderr,"TestBlockValidity failure B\n");
3560 if (!ContextualCheckBlock(block, state, pindexPrev))
3562 fprintf(stderr,"TestBlockValidity failure C\n");
3565 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3567 fprintf(stderr,"TestBlockValidity failure D\n");
3570 assert(state.IsValid());
3576 * BLOCK PRUNING CODE
3579 /* Calculate the amount of disk space the block & undo files currently use */
3580 uint64_t CalculateCurrentUsage()
3582 uint64_t retval = 0;
3583 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3584 retval += file.nSize + file.nUndoSize;
3589 /* Prune a block file (modify associated database entries)*/
3590 void PruneOneBlockFile(const int fileNumber)
3592 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3593 CBlockIndex* pindex = it->second;
3594 if (pindex->nFile == fileNumber) {
3595 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3596 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3598 pindex->nDataPos = 0;
3599 pindex->nUndoPos = 0;
3600 setDirtyBlockIndex.insert(pindex);
3602 // Prune from mapBlocksUnlinked -- any block we prune would have
3603 // to be downloaded again in order to consider its chain, at which
3604 // point it would be considered as a candidate for
3605 // mapBlocksUnlinked or setBlockIndexCandidates.
3606 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3607 while (range.first != range.second) {
3608 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3610 if (it->second == pindex) {
3611 mapBlocksUnlinked.erase(it);
3617 vinfoBlockFile[fileNumber].SetNull();
3618 setDirtyFileInfo.insert(fileNumber);
3622 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3624 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3625 CDiskBlockPos pos(*it, 0);
3626 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3627 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3628 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3632 /* Calculate the block/rev files that should be deleted to remain under target*/
3633 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3635 LOCK2(cs_main, cs_LastBlockFile);
3636 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3639 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3643 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3644 uint64_t nCurrentUsage = CalculateCurrentUsage();
3645 // We don't check to prune until after we've allocated new space for files
3646 // So we should leave a buffer under our target to account for another allocation
3647 // before the next pruning.
3648 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3649 uint64_t nBytesToPrune;
3652 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3653 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3654 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3656 if (vinfoBlockFile[fileNumber].nSize == 0)
3659 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3662 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3663 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3666 PruneOneBlockFile(fileNumber);
3667 // Queue up the files for removal
3668 setFilesToPrune.insert(fileNumber);
3669 nCurrentUsage -= nBytesToPrune;
3674 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3675 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3676 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3677 nLastBlockWeCanPrune, count);
3680 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3682 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3684 // Check for nMinDiskSpace bytes (currently 50MB)
3685 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3686 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3691 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3695 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3696 boost::filesystem::create_directories(path.parent_path());
3697 FILE* file = fopen(path.string().c_str(), "rb+");
3698 if (!file && !fReadOnly)
3699 file = fopen(path.string().c_str(), "wb+");
3701 LogPrintf("Unable to open file %s\n", path.string());
3705 if (fseek(file, pos.nPos, SEEK_SET)) {
3706 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3714 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3715 return OpenDiskFile(pos, "blk", fReadOnly);
3718 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3719 return OpenDiskFile(pos, "rev", fReadOnly);
3722 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3724 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3727 CBlockIndex * InsertBlockIndex(uint256 hash)
3733 BlockMap::iterator mi = mapBlockIndex.find(hash);
3734 if (mi != mapBlockIndex.end())
3735 return (*mi).second;
3738 CBlockIndex* pindexNew = new CBlockIndex();
3740 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3741 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3742 pindexNew->phashBlock = &((*mi).first);
3747 bool static LoadBlockIndexDB()
3749 const CChainParams& chainparams = Params();
3750 if (!pblocktree->LoadBlockIndexGuts())
3753 boost::this_thread::interruption_point();
3755 // Calculate nChainWork
3756 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3757 vSortedByHeight.reserve(mapBlockIndex.size());
3758 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3760 CBlockIndex* pindex = item.second;
3761 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3763 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3764 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3766 CBlockIndex* pindex = item.second;
3767 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3768 // We can link the chain of blocks for which we've received transactions at some point.
3769 // Pruned nodes may have deleted the block.
3770 if (pindex->nTx > 0) {
3771 if (pindex->pprev) {
3772 if (pindex->pprev->nChainTx) {
3773 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3775 pindex->nChainTx = 0;
3776 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3779 pindex->nChainTx = pindex->nTx;
3782 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3783 setBlockIndexCandidates.insert(pindex);
3784 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3785 pindexBestInvalid = pindex;
3787 pindex->BuildSkip();
3788 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3789 pindexBestHeader = pindex;
3792 // Load block file info
3793 pblocktree->ReadLastBlockFile(nLastBlockFile);
3794 vinfoBlockFile.resize(nLastBlockFile + 1);
3795 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3796 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3797 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3799 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3800 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3801 CBlockFileInfo info;
3802 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3803 vinfoBlockFile.push_back(info);
3809 // Check presence of blk files
3810 LogPrintf("Checking all blk files are present...\n");
3811 set<int> setBlkDataFiles;
3812 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3814 CBlockIndex* pindex = item.second;
3815 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3816 setBlkDataFiles.insert(pindex->nFile);
3819 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3821 CDiskBlockPos pos(*it, 0);
3822 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3827 // Check whether we have ever pruned block & undo files
3828 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3830 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3832 // Check whether we need to continue reindexing
3833 bool fReindexing = false;
3834 pblocktree->ReadReindexing(fReindexing);
3835 fReindex |= fReindexing;
3837 // Check whether we have a transaction index
3838 pblocktree->ReadFlag("txindex", fTxIndex);
3839 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3841 // Fill in-memory data
3842 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3844 CBlockIndex* pindex = item.second;
3845 // - This relationship will always be true even if pprev has multiple
3846 // children, because hashAnchor is technically a property of pprev,
3847 // not its children.
3848 // - This will miss chain tips; we handle the best tip below, and other
3849 // tips will be handled by ConnectTip during a re-org.
3850 if (pindex->pprev) {
3851 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3855 // Load pointer to end of best chain
3856 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3857 if (it == mapBlockIndex.end())
3859 chainActive.SetTip(it->second);
3860 // Set hashAnchorEnd for the end of best chain
3861 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3863 PruneBlockIndexCandidates();
3865 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3866 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3867 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3868 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3873 CVerifyDB::CVerifyDB()
3875 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3878 CVerifyDB::~CVerifyDB()
3880 uiInterface.ShowProgress("", 100);
3883 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3886 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3889 // Verify blocks in the best chain
3890 if (nCheckDepth <= 0)
3891 nCheckDepth = 1000000000; // suffices until the year 19000
3892 if (nCheckDepth > chainActive.Height())
3893 nCheckDepth = chainActive.Height();
3894 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3895 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3896 CCoinsViewCache coins(coinsview);
3897 CBlockIndex* pindexState = chainActive.Tip();
3898 CBlockIndex* pindexFailure = NULL;
3899 int nGoodTransactions = 0;
3900 CValidationState state;
3901 // No need to verify JoinSplits twice
3902 auto verifier = libzcash::ProofVerifier::Disabled();
3903 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3905 boost::this_thread::interruption_point();
3906 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3907 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3910 // check level 0: read from disk
3911 if (!ReadBlockFromDisk(block, pindex))
3912 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3913 // check level 1: verify block validity
3914 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier))
3915 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3916 // check level 2: verify undo validity
3917 if (nCheckLevel >= 2 && pindex) {
3919 CDiskBlockPos pos = pindex->GetUndoPos();
3920 if (!pos.IsNull()) {
3921 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3922 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3925 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3926 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3928 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3929 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3930 pindexState = pindex->pprev;
3932 nGoodTransactions = 0;
3933 pindexFailure = pindex;
3935 nGoodTransactions += block.vtx.size();
3937 if (ShutdownRequested())
3941 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3943 // check level 4: try reconnecting blocks
3944 if (nCheckLevel >= 4) {
3945 CBlockIndex *pindex = pindexState;
3946 while (pindex != chainActive.Tip()) {
3947 boost::this_thread::interruption_point();
3948 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3949 pindex = chainActive.Next(pindex);
3951 if (!ReadBlockFromDisk(block, pindex))
3952 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3953 if (!ConnectBlock(block, state, pindex, coins))
3954 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3958 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3963 void UnloadBlockIndex()
3966 setBlockIndexCandidates.clear();
3967 chainActive.SetTip(NULL);
3968 pindexBestInvalid = NULL;
3969 pindexBestHeader = NULL;
3971 mapOrphanTransactions.clear();
3972 mapOrphanTransactionsByPrev.clear();
3974 mapBlocksUnlinked.clear();
3975 vinfoBlockFile.clear();
3977 nBlockSequenceId = 1;
3978 mapBlockSource.clear();
3979 mapBlocksInFlight.clear();
3980 nQueuedValidatedHeaders = 0;
3981 nPreferredDownload = 0;
3982 setDirtyBlockIndex.clear();
3983 setDirtyFileInfo.clear();
3984 mapNodeState.clear();
3985 recentRejects.reset(NULL);
3987 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3988 delete entry.second;
3990 mapBlockIndex.clear();
3991 fHavePruned = false;
3994 bool LoadBlockIndex()
3996 extern int32_t KOMODO_LOADINGBLOCKS;
3997 // Load block index from databases
3998 KOMODO_LOADINGBLOCKS = 1;
3999 if (!fReindex && !LoadBlockIndexDB())
4001 KOMODO_LOADINGBLOCKS = 0;
4004 KOMODO_LOADINGBLOCKS = 0;
4005 fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL);
4010 bool InitBlockIndex() {
4011 const CChainParams& chainparams = Params();
4014 // Initialize global variables that cannot be constructed at startup.
4015 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4017 // Check whether we're already initialized
4018 if (chainActive.Genesis() != NULL)
4021 // Use the provided setting for -txindex in the new database
4022 fTxIndex = GetBoolArg("-txindex", true);
4023 pblocktree->WriteFlag("txindex", fTxIndex);
4024 LogPrintf("Initializing databases...\n");
4026 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4029 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4030 // Start new block file
4031 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4032 CDiskBlockPos blockPos;
4033 CValidationState state;
4034 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4035 return error("LoadBlockIndex(): FindBlockPos failed");
4036 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4037 return error("LoadBlockIndex(): writing genesis block to disk failed");
4038 CBlockIndex *pindex = AddToBlockIndex(block);
4039 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4040 return error("LoadBlockIndex(): genesis block not accepted");
4041 if (!ActivateBestChain(state, &block))
4042 return error("LoadBlockIndex(): genesis block cannot be activated");
4043 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4044 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4045 } catch (const std::runtime_error& e) {
4046 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4055 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4057 const CChainParams& chainparams = Params();
4058 // Map of disk positions for blocks with unknown parent (only used for reindex)
4059 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4060 int64_t nStart = GetTimeMillis();
4064 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4065 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4066 uint64_t nRewind = blkdat.GetPos();
4067 while (!blkdat.eof()) {
4068 boost::this_thread::interruption_point();
4070 blkdat.SetPos(nRewind);
4071 nRewind++; // start one byte further next time, in case of failure
4072 blkdat.SetLimit(); // remove former limit
4073 unsigned int nSize = 0;
4076 unsigned char buf[MESSAGE_START_SIZE];
4077 blkdat.FindByte(Params().MessageStart()[0]);
4078 nRewind = blkdat.GetPos()+1;
4079 blkdat >> FLATDATA(buf);
4080 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4084 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4086 } catch (const std::exception&) {
4087 // no valid block header found; don't complain
4092 uint64_t nBlockPos = blkdat.GetPos();
4094 dbp->nPos = nBlockPos;
4095 blkdat.SetLimit(nBlockPos + nSize);
4096 blkdat.SetPos(nBlockPos);
4099 nRewind = blkdat.GetPos();
4101 // detect out of order blocks, and store them for later
4102 uint256 hash = block.GetHash();
4103 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4104 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4105 block.hashPrevBlock.ToString());
4107 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4111 // process in case the block isn't known yet
4112 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4113 CValidationState state;
4114 if (ProcessNewBlock(0,state, NULL, &block, true, dbp))
4116 if (state.IsError())
4118 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4119 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4122 // Recursively process earlier encountered successors of this block
4123 deque<uint256> queue;
4124 queue.push_back(hash);
4125 while (!queue.empty()) {
4126 uint256 head = queue.front();
4128 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4129 while (range.first != range.second) {
4130 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4131 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
4133 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4135 CValidationState dummy;
4136 if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second))
4139 queue.push_back(block.GetHash());
4143 mapBlocksUnknownParent.erase(it);
4146 } catch (const std::exception& e) {
4147 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4150 } catch (const std::runtime_error& e) {
4151 AbortNode(std::string("System error: ") + e.what());
4154 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4158 void static CheckBlockIndex()
4160 const Consensus::Params& consensusParams = Params().GetConsensus();
4161 if (!fCheckBlockIndex) {
4167 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4168 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4169 // iterating the block tree require that chainActive has been initialized.)
4170 if (chainActive.Height() < 0) {
4171 assert(mapBlockIndex.size() <= 1);
4175 // Build forward-pointing map of the entire block tree.
4176 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4177 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4178 forward.insert(std::make_pair(it->second->pprev, it->second));
4181 assert(forward.size() == mapBlockIndex.size());
4183 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4184 CBlockIndex *pindex = rangeGenesis.first->second;
4185 rangeGenesis.first++;
4186 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4188 // Iterate over the entire block tree, using depth-first search.
4189 // Along the way, remember whether there are blocks on the path from genesis
4190 // block being explored which are the first to have certain properties.
4193 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4194 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4195 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4196 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4197 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4198 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4199 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4200 while (pindex != NULL) {
4202 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4203 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4204 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4205 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4206 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4207 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4208 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4210 // Begin: actual consistency checks.
4211 if (pindex->pprev == NULL) {
4212 // Genesis block checks.
4213 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4214 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4216 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4217 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4218 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4220 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4221 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4222 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4224 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4225 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4227 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4228 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4229 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4230 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4231 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4232 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4233 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.
4234 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4235 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4236 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4237 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4238 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4239 if (pindexFirstInvalid == NULL) {
4240 // Checks for not-invalid blocks.
4241 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4243 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4244 if (pindexFirstInvalid == NULL) {
4245 // If this block sorts at least as good as the current tip and
4246 // is valid and we have all data for its parents, it must be in
4247 // setBlockIndexCandidates. chainActive.Tip() must also be there
4248 // even if some data has been pruned.
4249 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4250 assert(setBlockIndexCandidates.count(pindex));
4252 // If some parent is missing, then it could be that this block was in
4253 // setBlockIndexCandidates but had to be removed because of the missing data.
4254 // In this case it must be in mapBlocksUnlinked -- see test below.
4256 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4257 assert(setBlockIndexCandidates.count(pindex) == 0);
4259 // Check whether this block is in mapBlocksUnlinked.
4260 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4261 bool foundInUnlinked = false;
4262 while (rangeUnlinked.first != rangeUnlinked.second) {
4263 assert(rangeUnlinked.first->first == pindex->pprev);
4264 if (rangeUnlinked.first->second == pindex) {
4265 foundInUnlinked = true;
4268 rangeUnlinked.first++;
4270 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4271 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4272 assert(foundInUnlinked);
4274 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4275 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4276 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4277 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4278 assert(fHavePruned); // We must have pruned.
4279 // This block may have entered mapBlocksUnlinked if:
4280 // - it has a descendant that at some point had more work than the
4282 // - we tried switching to that descendant but were missing
4283 // data for some intermediate block between chainActive and the
4285 // So if this block is itself better than chainActive.Tip() and it wasn't in
4286 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4287 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4288 if (pindexFirstInvalid == NULL) {
4289 assert(foundInUnlinked);
4293 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4294 // End: actual consistency checks.
4296 // Try descending into the first subnode.
4297 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4298 if (range.first != range.second) {
4299 // A subnode was found.
4300 pindex = range.first->second;
4304 // This is a leaf node.
4305 // Move upwards until we reach a node of which we have not yet visited the last child.
4307 // We are going to either move to a parent or a sibling of pindex.
4308 // If pindex was the first with a certain property, unset the corresponding variable.
4309 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4310 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4311 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4312 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4313 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4314 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4315 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4317 CBlockIndex* pindexPar = pindex->pprev;
4318 // Find which child we just visited.
4319 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4320 while (rangePar.first->second != pindex) {
4321 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4324 // Proceed to the next one.
4326 if (rangePar.first != rangePar.second) {
4327 // Move to the sibling.
4328 pindex = rangePar.first->second;
4339 // Check that we actually traversed the entire map.
4340 assert(nNodes == forward.size());
4343 //////////////////////////////////////////////////////////////////////////////
4348 std::string GetWarnings(const std::string& strFor)
4351 string strStatusBar;
4354 if (!CLIENT_VERSION_IS_RELEASE)
4355 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4357 if (GetBoolArg("-testsafemode", false))
4358 strStatusBar = strRPC = "testsafemode enabled";
4360 // Misc warnings like out of disk space and clock is wrong
4361 if (strMiscWarning != "")
4364 strStatusBar = strMiscWarning;
4367 if (fLargeWorkForkFound)
4370 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4372 else if (fLargeWorkInvalidChainFound)
4375 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.");
4381 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4383 const CAlert& alert = item.second;
4384 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4386 nPriority = alert.nPriority;
4387 strStatusBar = alert.strStatusBar;
4388 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4389 strRPC = alert.strRPCError;
4395 if (strFor == "statusbar")
4396 return strStatusBar;
4397 else if (strFor == "rpc")
4399 assert(!"GetWarnings(): invalid parameter");
4410 //////////////////////////////////////////////////////////////////////////////
4416 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4422 assert(recentRejects);
4423 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4425 // If the chain tip has changed previously rejected transactions
4426 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4427 // or a double-spend. Reset the rejects filter and give those
4428 // txs a second chance.
4429 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4430 recentRejects->reset();
4433 return recentRejects->contains(inv.hash) ||
4434 mempool.exists(inv.hash) ||
4435 mapOrphanTransactions.count(inv.hash) ||
4436 pcoinsTip->HaveCoins(inv.hash);
4439 return mapBlockIndex.count(inv.hash);
4441 // Don't know what it is, just say we already got one
4445 void static ProcessGetData(CNode* pfrom)
4447 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4449 vector<CInv> vNotFound;
4453 while (it != pfrom->vRecvGetData.end()) {
4454 // Don't bother if send buffer is too full to respond anyway
4455 if (pfrom->nSendSize >= SendBufferSize())
4458 const CInv &inv = *it;
4460 boost::this_thread::interruption_point();
4463 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4466 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4467 if (mi != mapBlockIndex.end())
4469 if (chainActive.Contains(mi->second)) {
4472 static const int nOneMonth = 30 * 24 * 60 * 60;
4473 // To prevent fingerprinting attacks, only send blocks outside of the active
4474 // chain if they are valid, and no more than a month older (both in time, and in
4475 // best equivalent proof of work) than the best header chain we know about.
4476 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4477 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4478 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4480 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4484 // Pruned nodes may have deleted the block, so check whether
4485 // it's available before trying to send.
4486 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4488 // Send block from disk
4490 if (!ReadBlockFromDisk(block, (*mi).second))
4492 assert(!"cannot load block from disk");
4496 if (inv.type == MSG_BLOCK)
4497 pfrom->PushMessage("block", block);
4498 else // MSG_FILTERED_BLOCK)
4500 LOCK(pfrom->cs_filter);
4503 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4504 pfrom->PushMessage("merkleblock", merkleBlock);
4505 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4506 // This avoids hurting performance by pointlessly requiring a round-trip
4507 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4508 // they must either disconnect and retry or request the full block.
4509 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4510 // however we MUST always provide at least what the remote peer needs
4511 typedef std::pair<unsigned int, uint256> PairType;
4512 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4513 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4514 pfrom->PushMessage("tx", block.vtx[pair.first]);
4520 // Trigger the peer node to send a getblocks request for the next batch of inventory
4521 if (inv.hash == pfrom->hashContinue)
4523 // Bypass PushInventory, this must send even if redundant,
4524 // and we want it right after the last block so they don't
4525 // wait for other stuff first.
4527 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4528 pfrom->PushMessage("inv", vInv);
4529 pfrom->hashContinue.SetNull();
4533 else if (inv.IsKnownType())
4535 // Send stream from relay memory
4536 bool pushed = false;
4539 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4540 if (mi != mapRelay.end()) {
4541 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4545 if (!pushed && inv.type == MSG_TX) {
4547 if (mempool.lookup(inv.hash, tx)) {
4548 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4551 pfrom->PushMessage("tx", ss);
4556 vNotFound.push_back(inv);
4560 // Track requests for our stuff.
4561 GetMainSignals().Inventory(inv.hash);
4563 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4568 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4570 if (!vNotFound.empty()) {
4571 // Let the peer know that we didn't find what it asked for, so it doesn't
4572 // have to wait around forever. Currently only SPV clients actually care
4573 // about this message: it's needed when they are recursively walking the
4574 // dependencies of relevant unconfirmed transactions. SPV clients want to
4575 // do that because they want to know about (and store and rebroadcast and
4576 // risk analyze) the dependencies of transactions relevant to them, without
4577 // having to download the entire memory pool.
4578 pfrom->PushMessage("notfound", vNotFound);
4582 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4584 const CChainParams& chainparams = Params();
4585 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4586 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4588 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4595 if (strCommand == "version")
4597 // Each connection can only send one version message
4598 if (pfrom->nVersion != 0)
4600 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4601 Misbehaving(pfrom->GetId(), 1);
4608 uint64_t nNonce = 1;
4609 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4610 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4612 // disconnect from peers older than this proto version
4613 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4614 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4615 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4616 pfrom->fDisconnect = true;
4620 if (pfrom->nVersion == 10300)
4621 pfrom->nVersion = 300;
4623 vRecv >> addrFrom >> nNonce;
4624 if (!vRecv.empty()) {
4625 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4626 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4629 vRecv >> pfrom->nStartingHeight;
4631 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4633 pfrom->fRelayTxes = true;
4635 // Disconnect if we connected to ourself
4636 if (nNonce == nLocalHostNonce && nNonce > 1)
4638 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4639 pfrom->fDisconnect = true;
4643 pfrom->addrLocal = addrMe;
4644 if (pfrom->fInbound && addrMe.IsRoutable())
4649 // Be shy and don't send version until we hear
4650 if (pfrom->fInbound)
4651 pfrom->PushVersion();
4653 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4655 // Potentially mark this peer as a preferred download peer.
4656 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4659 pfrom->PushMessage("verack");
4660 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4662 if (!pfrom->fInbound)
4664 // Advertise our address
4665 if (fListen && !IsInitialBlockDownload())
4667 CAddress addr = GetLocalAddress(&pfrom->addr);
4668 if (addr.IsRoutable())
4670 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4671 pfrom->PushAddress(addr);
4672 } else if (IsPeerAddrLocalGood(pfrom)) {
4673 addr.SetIP(pfrom->addrLocal);
4674 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4675 pfrom->PushAddress(addr);
4679 // Get recent addresses
4680 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4682 pfrom->PushMessage("getaddr");
4683 pfrom->fGetAddr = true;
4685 addrman.Good(pfrom->addr);
4687 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4689 addrman.Add(addrFrom, addrFrom);
4690 addrman.Good(addrFrom);
4697 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4698 item.second.RelayTo(pfrom);
4701 pfrom->fSuccessfullyConnected = true;
4705 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4707 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4708 pfrom->cleanSubVer, pfrom->nVersion,
4709 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4712 int64_t nTimeOffset = nTime - GetTime();
4713 pfrom->nTimeOffset = nTimeOffset;
4714 AddTimeData(pfrom->addr, nTimeOffset);
4718 else if (pfrom->nVersion == 0)
4720 // Must have a version message before anything else
4721 Misbehaving(pfrom->GetId(), 1);
4726 else if (strCommand == "verack")
4728 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4730 // Mark this node as currently connected, so we update its timestamp later.
4731 if (pfrom->fNetworkNode) {
4733 State(pfrom->GetId())->fCurrentlyConnected = true;
4738 else if (strCommand == "addr")
4740 vector<CAddress> vAddr;
4743 // Don't want addr from older versions unless seeding
4744 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4746 if (vAddr.size() > 1000)
4748 Misbehaving(pfrom->GetId(), 20);
4749 return error("message addr size() = %u", vAddr.size());
4752 // Store the new addresses
4753 vector<CAddress> vAddrOk;
4754 int64_t nNow = GetAdjustedTime();
4755 int64_t nSince = nNow - 10 * 60;
4756 BOOST_FOREACH(CAddress& addr, vAddr)
4758 boost::this_thread::interruption_point();
4760 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4761 addr.nTime = nNow - 5 * 24 * 60 * 60;
4762 pfrom->AddAddressKnown(addr);
4763 bool fReachable = IsReachable(addr);
4764 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4766 // Relay to a limited number of other nodes
4769 // Use deterministic randomness to send to the same nodes for 24 hours
4770 // at a time so the addrKnowns of the chosen nodes prevent repeats
4771 static uint256 hashSalt;
4772 if (hashSalt.IsNull())
4773 hashSalt = GetRandHash();
4774 uint64_t hashAddr = addr.GetHash();
4775 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4776 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4777 multimap<uint256, CNode*> mapMix;
4778 BOOST_FOREACH(CNode* pnode, vNodes)
4780 if (pnode->nVersion < CADDR_TIME_VERSION)
4782 unsigned int nPointer;
4783 memcpy(&nPointer, &pnode, sizeof(nPointer));
4784 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4785 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4786 mapMix.insert(make_pair(hashKey, pnode));
4788 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4789 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4790 ((*mi).second)->PushAddress(addr);
4793 // Do not store addresses outside our network
4795 vAddrOk.push_back(addr);
4797 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4798 if (vAddr.size() < 1000)
4799 pfrom->fGetAddr = false;
4800 if (pfrom->fOneShot)
4801 pfrom->fDisconnect = true;
4805 else if (strCommand == "inv")
4809 if (vInv.size() > MAX_INV_SZ)
4811 Misbehaving(pfrom->GetId(), 20);
4812 return error("message inv size() = %u", vInv.size());
4817 std::vector<CInv> vToFetch;
4819 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4821 const CInv &inv = vInv[nInv];
4823 boost::this_thread::interruption_point();
4824 pfrom->AddInventoryKnown(inv);
4826 bool fAlreadyHave = AlreadyHave(inv);
4827 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4829 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4832 if (inv.type == MSG_BLOCK) {
4833 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4834 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4835 // First request the headers preceding the announced block. In the normal fully-synced
4836 // case where a new block is announced that succeeds the current tip (no reorganization),
4837 // there are no such headers.
4838 // Secondly, and only when we are close to being synced, we request the announced block directly,
4839 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4840 // time the block arrives, the header chain leading up to it is already validated. Not
4841 // doing this will result in the received block being rejected as an orphan in case it is
4842 // not a direct successor.
4843 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4844 CNodeState *nodestate = State(pfrom->GetId());
4845 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4846 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4847 vToFetch.push_back(inv);
4848 // Mark block as in flight already, even though the actual "getdata" message only goes out
4849 // later (within the same cs_main lock, though).
4850 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4852 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4856 // Track requests for our stuff
4857 GetMainSignals().Inventory(inv.hash);
4859 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4860 Misbehaving(pfrom->GetId(), 50);
4861 return error("send buffer size() = %u", pfrom->nSendSize);
4865 if (!vToFetch.empty())
4866 pfrom->PushMessage("getdata", vToFetch);
4870 else if (strCommand == "getdata")
4874 if (vInv.size() > MAX_INV_SZ)
4876 Misbehaving(pfrom->GetId(), 20);
4877 return error("message getdata size() = %u", vInv.size());
4880 if (fDebug || (vInv.size() != 1))
4881 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4883 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4884 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4886 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4887 ProcessGetData(pfrom);
4891 else if (strCommand == "getblocks")
4893 CBlockLocator locator;
4895 vRecv >> locator >> hashStop;
4899 // Find the last block the caller has in the main chain
4900 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4902 // Send the rest of the chain
4904 pindex = chainActive.Next(pindex);
4906 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4907 for (; pindex; pindex = chainActive.Next(pindex))
4909 if (pindex->GetBlockHash() == hashStop)
4911 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4914 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4917 // When this block is requested, we'll send an inv that'll
4918 // trigger the peer to getblocks the next batch of inventory.
4919 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4920 pfrom->hashContinue = pindex->GetBlockHash();
4927 else if (strCommand == "getheaders")
4929 CBlockLocator locator;
4931 vRecv >> locator >> hashStop;
4935 if (IsInitialBlockDownload())
4938 CBlockIndex* pindex = NULL;
4939 if (locator.IsNull())
4941 // If locator is null, return the hashStop block
4942 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4943 if (mi == mapBlockIndex.end())
4945 pindex = (*mi).second;
4949 // Find the last block the caller has in the main chain
4950 pindex = FindForkInGlobalIndex(chainActive, locator);
4952 pindex = chainActive.Next(pindex);
4955 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4956 vector<CBlock> vHeaders;
4957 int nLimit = MAX_HEADERS_RESULTS;
4958 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4959 for (; pindex; pindex = chainActive.Next(pindex))
4961 vHeaders.push_back(pindex->GetBlockHeader());
4962 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4965 pfrom->PushMessage("headers", vHeaders);
4969 else if (strCommand == "tx")
4971 vector<uint256> vWorkQueue;
4972 vector<uint256> vEraseQueue;
4976 CInv inv(MSG_TX, tx.GetHash());
4977 pfrom->AddInventoryKnown(inv);
4981 bool fMissingInputs = false;
4982 CValidationState state;
4984 pfrom->setAskFor.erase(inv.hash);
4985 mapAlreadyAskedFor.erase(inv);
4987 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4989 mempool.check(pcoinsTip);
4990 RelayTransaction(tx);
4991 vWorkQueue.push_back(inv.hash);
4993 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4994 pfrom->id, pfrom->cleanSubVer,
4995 tx.GetHash().ToString(),
4996 mempool.mapTx.size());
4998 // Recursively process any orphan transactions that depended on this one
4999 set<NodeId> setMisbehaving;
5000 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5002 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5003 if (itByPrev == mapOrphanTransactionsByPrev.end())
5005 for (set<uint256>::iterator mi = itByPrev->second.begin();
5006 mi != itByPrev->second.end();
5009 const uint256& orphanHash = *mi;
5010 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5011 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5012 bool fMissingInputs2 = false;
5013 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5014 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5015 // anyone relaying LegitTxX banned)
5016 CValidationState stateDummy;
5019 if (setMisbehaving.count(fromPeer))
5021 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5023 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5024 RelayTransaction(orphanTx);
5025 vWorkQueue.push_back(orphanHash);
5026 vEraseQueue.push_back(orphanHash);
5028 else if (!fMissingInputs2)
5031 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5033 // Punish peer that gave us an invalid orphan tx
5034 Misbehaving(fromPeer, nDos);
5035 setMisbehaving.insert(fromPeer);
5036 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5038 // Has inputs but not accepted to mempool
5039 // Probably non-standard or insufficient fee/priority
5040 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5041 vEraseQueue.push_back(orphanHash);
5042 assert(recentRejects);
5043 recentRejects->insert(orphanHash);
5045 mempool.check(pcoinsTip);
5049 BOOST_FOREACH(uint256 hash, vEraseQueue)
5050 EraseOrphanTx(hash);
5052 // TODO: currently, prohibit joinsplits from entering mapOrphans
5053 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5055 AddOrphanTx(tx, pfrom->GetId());
5057 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5058 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5059 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5061 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5063 assert(recentRejects);
5064 recentRejects->insert(tx.GetHash());
5066 if (pfrom->fWhitelisted) {
5067 // Always relay transactions received from whitelisted peers, even
5068 // if they were already in the mempool or rejected from it due
5069 // to policy, allowing the node to function as a gateway for
5070 // nodes hidden behind it.
5072 // Never relay transactions that we would assign a non-zero DoS
5073 // score for, as we expect peers to do the same with us in that
5076 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5077 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5078 RelayTransaction(tx);
5080 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5081 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5086 if (state.IsInvalid(nDoS))
5088 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5089 pfrom->id, pfrom->cleanSubVer,
5090 state.GetRejectReason());
5091 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5092 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5094 Misbehaving(pfrom->GetId(), nDoS);
5099 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5101 std::vector<CBlockHeader> headers;
5103 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5104 unsigned int nCount = ReadCompactSize(vRecv);
5105 if (nCount > MAX_HEADERS_RESULTS) {
5106 Misbehaving(pfrom->GetId(), 20);
5107 return error("headers message size = %u", nCount);
5109 headers.resize(nCount);
5110 for (unsigned int n = 0; n < nCount; n++) {
5111 vRecv >> headers[n];
5112 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5118 // Nothing interesting. Stop asking this peers for more headers.
5122 CBlockIndex *pindexLast = NULL;
5123 BOOST_FOREACH(const CBlockHeader& header, headers) {
5124 CValidationState state;
5125 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5126 Misbehaving(pfrom->GetId(), 20);
5127 return error("non-continuous headers sequence");
5129 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5131 if (state.IsInvalid(nDoS)) {
5133 Misbehaving(pfrom->GetId(), nDoS/nDoS);
5134 return error("invalid header received");
5140 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5142 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5143 // Headers message had its maximum size; the peer may have more headers.
5144 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5145 // from there instead.
5146 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5147 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5153 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5158 CInv inv(MSG_BLOCK, block.GetHash());
5159 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5161 pfrom->AddInventoryKnown(inv);
5163 CValidationState state;
5164 // Process all blocks from whitelisted peers, even if not requested,
5165 // unless we're still syncing with the network.
5166 // Such an unrequested block may still be processed, subject to the
5167 // conditions in AcceptBlock().
5168 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5169 ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL);
5171 if (state.IsInvalid(nDoS)) {
5172 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5173 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5176 Misbehaving(pfrom->GetId(), nDoS);
5183 // This asymmetric behavior for inbound and outbound connections was introduced
5184 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5185 // to users' AddrMan and later request them by sending getaddr messages.
5186 // Making nodes which are behind NAT and can only make outgoing connections ignore
5187 // the getaddr message mitigates the attack.
5188 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5190 // Only send one GetAddr response per connection to reduce resource waste
5191 // and discourage addr stamping of INV announcements.
5192 if (pfrom->fSentAddr) {
5193 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5196 pfrom->fSentAddr = true;
5198 pfrom->vAddrToSend.clear();
5199 vector<CAddress> vAddr = addrman.GetAddr();
5200 BOOST_FOREACH(const CAddress &addr, vAddr)
5201 pfrom->PushAddress(addr);
5205 else if (strCommand == "mempool")
5207 LOCK2(cs_main, pfrom->cs_filter);
5209 std::vector<uint256> vtxid;
5210 mempool.queryHashes(vtxid);
5212 BOOST_FOREACH(uint256& hash, vtxid) {
5213 CInv inv(MSG_TX, hash);
5215 bool fInMemPool = mempool.lookup(hash, tx);
5216 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5217 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5219 vInv.push_back(inv);
5220 if (vInv.size() == MAX_INV_SZ) {
5221 pfrom->PushMessage("inv", vInv);
5225 if (vInv.size() > 0)
5226 pfrom->PushMessage("inv", vInv);
5230 else if (strCommand == "ping")
5232 if (pfrom->nVersion > BIP0031_VERSION)
5236 // Echo the message back with the nonce. This allows for two useful features:
5238 // 1) A remote node can quickly check if the connection is operational
5239 // 2) Remote nodes can measure the latency of the network thread. If this node
5240 // is overloaded it won't respond to pings quickly and the remote node can
5241 // avoid sending us more work, like chain download requests.
5243 // The nonce stops the remote getting confused between different pings: without
5244 // it, if the remote node sends a ping once per second and this node takes 5
5245 // seconds to respond to each, the 5th ping the remote sends would appear to
5246 // return very quickly.
5247 pfrom->PushMessage("pong", nonce);
5252 else if (strCommand == "pong")
5254 int64_t pingUsecEnd = nTimeReceived;
5256 size_t nAvail = vRecv.in_avail();
5257 bool bPingFinished = false;
5258 std::string sProblem;
5260 if (nAvail >= sizeof(nonce)) {
5263 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5264 if (pfrom->nPingNonceSent != 0) {
5265 if (nonce == pfrom->nPingNonceSent) {
5266 // Matching pong received, this ping is no longer outstanding
5267 bPingFinished = true;
5268 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5269 if (pingUsecTime > 0) {
5270 // Successful ping time measurement, replace previous
5271 pfrom->nPingUsecTime = pingUsecTime;
5272 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5274 // This should never happen
5275 sProblem = "Timing mishap";
5278 // Nonce mismatches are normal when pings are overlapping
5279 sProblem = "Nonce mismatch";
5281 // This is most likely a bug in another implementation somewhere; cancel this ping
5282 bPingFinished = true;
5283 sProblem = "Nonce zero";
5287 sProblem = "Unsolicited pong without ping";
5290 // This is most likely a bug in another implementation somewhere; cancel this ping
5291 bPingFinished = true;
5292 sProblem = "Short payload";
5295 if (!(sProblem.empty())) {
5296 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5300 pfrom->nPingNonceSent,
5304 if (bPingFinished) {
5305 pfrom->nPingNonceSent = 0;
5310 else if (fAlerts && strCommand == "alert")
5315 uint256 alertHash = alert.GetHash();
5316 if (pfrom->setKnown.count(alertHash) == 0)
5318 if (alert.ProcessAlert(Params().AlertKey()))
5321 pfrom->setKnown.insert(alertHash);
5324 BOOST_FOREACH(CNode* pnode, vNodes)
5325 alert.RelayTo(pnode);
5329 // Small DoS penalty so peers that send us lots of
5330 // duplicate/expired/invalid-signature/whatever alerts
5331 // eventually get banned.
5332 // This isn't a Misbehaving(100) (immediate ban) because the
5333 // peer might be an older or different implementation with
5334 // a different signature key, etc.
5335 Misbehaving(pfrom->GetId(), 10);
5341 else if (strCommand == "filterload")
5343 CBloomFilter filter;
5346 if (!filter.IsWithinSizeConstraints())
5347 // There is no excuse for sending a too-large filter
5348 Misbehaving(pfrom->GetId(), 100);
5351 LOCK(pfrom->cs_filter);
5352 delete pfrom->pfilter;
5353 pfrom->pfilter = new CBloomFilter(filter);
5354 pfrom->pfilter->UpdateEmptyFull();
5356 pfrom->fRelayTxes = true;
5360 else if (strCommand == "filteradd")
5362 vector<unsigned char> vData;
5365 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5366 // and thus, the maximum size any matched object can have) in a filteradd message
5367 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5369 Misbehaving(pfrom->GetId(), 100);
5371 LOCK(pfrom->cs_filter);
5373 pfrom->pfilter->insert(vData);
5375 Misbehaving(pfrom->GetId(), 100);
5380 else if (strCommand == "filterclear")
5382 LOCK(pfrom->cs_filter);
5383 delete pfrom->pfilter;
5384 pfrom->pfilter = new CBloomFilter();
5385 pfrom->fRelayTxes = true;
5389 else if (strCommand == "reject")
5393 string strMsg; unsigned char ccode; string strReason;
5394 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5397 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5399 if (strMsg == "block" || strMsg == "tx")
5403 ss << ": hash " << hash.ToString();
5405 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5406 } catch (const std::ios_base::failure&) {
5407 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5408 LogPrint("net", "Unparseable reject message received\n");
5412 else if (strCommand == "notfound") {
5413 // We do not care about the NOTFOUND message, but logging an Unknown Command
5414 // message would be undesirable as we transmit it ourselves.
5418 // Ignore unknown commands for extensibility
5419 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5427 // requires LOCK(cs_vRecvMsg)
5428 bool ProcessMessages(CNode* pfrom)
5431 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5435 // (4) message start
5443 if (!pfrom->vRecvGetData.empty())
5444 ProcessGetData(pfrom);
5446 // this maintains the order of responses
5447 if (!pfrom->vRecvGetData.empty()) return fOk;
5449 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5450 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5451 // Don't bother if send buffer is too full to respond anyway
5452 if (pfrom->nSendSize >= SendBufferSize())
5456 CNetMessage& msg = *it;
5459 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5460 // msg.hdr.nMessageSize, msg.vRecv.size(),
5461 // msg.complete() ? "Y" : "N");
5463 // end, if an incomplete message is found
5464 if (!msg.complete())
5467 // at this point, any failure means we can delete the current message
5470 // Scan for message start
5471 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5472 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5478 CMessageHeader& hdr = msg.hdr;
5479 if (!hdr.IsValid(Params().MessageStart()))
5481 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5484 string strCommand = hdr.GetCommand();
5487 unsigned int nMessageSize = hdr.nMessageSize;
5490 CDataStream& vRecv = msg.vRecv;
5491 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5492 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5493 if (nChecksum != hdr.nChecksum)
5495 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5496 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5504 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5505 boost::this_thread::interruption_point();
5507 catch (const std::ios_base::failure& e)
5509 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5510 if (strstr(e.what(), "end of data"))
5512 // Allow exceptions from under-length message on vRecv
5513 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());
5515 else if (strstr(e.what(), "size too large"))
5517 // Allow exceptions from over-long size
5518 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5522 //PrintExceptionContinue(&e, "ProcessMessages()");
5525 catch (const boost::thread_interrupted&) {
5528 catch (const std::exception& e) {
5529 PrintExceptionContinue(&e, "ProcessMessages()");
5531 PrintExceptionContinue(NULL, "ProcessMessages()");
5535 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5540 // In case the connection got shut down, its receive buffer was wiped
5541 if (!pfrom->fDisconnect)
5542 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5548 bool SendMessages(CNode* pto, bool fSendTrickle)
5550 const Consensus::Params& consensusParams = Params().GetConsensus();
5552 // Don't send anything until we get its version message
5553 if (pto->nVersion == 0)
5559 bool pingSend = false;
5560 if (pto->fPingQueued) {
5561 // RPC ping request by user
5564 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5565 // Ping automatically sent as a latency probe & keepalive.
5570 while (nonce == 0) {
5571 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5573 pto->fPingQueued = false;
5574 pto->nPingUsecStart = GetTimeMicros();
5575 if (pto->nVersion > BIP0031_VERSION) {
5576 pto->nPingNonceSent = nonce;
5577 pto->PushMessage("ping", nonce);
5579 // Peer is too old to support ping command with nonce, pong will never arrive.
5580 pto->nPingNonceSent = 0;
5581 pto->PushMessage("ping");
5585 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5589 // Address refresh broadcast
5590 static int64_t nLastRebroadcast;
5591 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5594 BOOST_FOREACH(CNode* pnode, vNodes)
5596 // Periodically clear addrKnown to allow refresh broadcasts
5597 if (nLastRebroadcast)
5598 pnode->addrKnown.reset();
5600 // Rebroadcast our address
5601 AdvertizeLocal(pnode);
5603 if (!vNodes.empty())
5604 nLastRebroadcast = GetTime();
5612 vector<CAddress> vAddr;
5613 vAddr.reserve(pto->vAddrToSend.size());
5614 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5616 if (!pto->addrKnown.contains(addr.GetKey()))
5618 pto->addrKnown.insert(addr.GetKey());
5619 vAddr.push_back(addr);
5620 // receiver rejects addr messages larger than 1000
5621 if (vAddr.size() >= 1000)
5623 pto->PushMessage("addr", vAddr);
5628 pto->vAddrToSend.clear();
5630 pto->PushMessage("addr", vAddr);
5633 CNodeState &state = *State(pto->GetId());
5634 if (state.fShouldBan) {
5635 if (pto->fWhitelisted)
5636 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5638 pto->fDisconnect = true;
5639 if (pto->addr.IsLocal())
5640 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5643 CNode::Ban(pto->addr);
5646 state.fShouldBan = false;
5649 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5650 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5651 state.rejects.clear();
5654 if (pindexBestHeader == NULL)
5655 pindexBestHeader = chainActive.Tip();
5656 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.
5657 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5658 // Only actively request headers from a single peer, unless we're close to today.
5659 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5660 state.fSyncStarted = true;
5662 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5663 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5664 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5668 // Resend wallet transactions that haven't gotten in a block yet
5669 // Except during reindex, importing and IBD, when old wallet
5670 // transactions become unconfirmed and spams other nodes.
5671 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5673 GetMainSignals().Broadcast(nTimeBestReceived);
5677 // Message: inventory
5680 vector<CInv> vInvWait;
5682 LOCK(pto->cs_inventory);
5683 vInv.reserve(pto->vInventoryToSend.size());
5684 vInvWait.reserve(pto->vInventoryToSend.size());
5685 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5687 if (pto->setInventoryKnown.count(inv))
5690 // trickle out tx inv to protect privacy
5691 if (inv.type == MSG_TX && !fSendTrickle)
5693 // 1/4 of tx invs blast to all immediately
5694 static uint256 hashSalt;
5695 if (hashSalt.IsNull())
5696 hashSalt = GetRandHash();
5697 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5698 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5699 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5703 vInvWait.push_back(inv);
5708 // returns true if wasn't already contained in the set
5709 if (pto->setInventoryKnown.insert(inv).second)
5711 vInv.push_back(inv);
5712 if (vInv.size() >= 1000)
5714 pto->PushMessage("inv", vInv);
5719 pto->vInventoryToSend = vInvWait;
5722 pto->PushMessage("inv", vInv);
5724 // Detect whether we're stalling
5725 int64_t nNow = GetTimeMicros();
5726 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5727 // Stalling only triggers when the block download window cannot move. During normal steady state,
5728 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5729 // should only happen during initial block download.
5730 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5731 pto->fDisconnect = true;
5733 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5734 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5735 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5736 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5737 // to unreasonably increase our timeout.
5738 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5739 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5740 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5741 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5742 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5743 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5744 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5745 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5746 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5747 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5748 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5750 if (queuedBlock.nTimeDisconnect < nNow) {
5751 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5752 pto->fDisconnect = true;
5757 // Message: getdata (blocks)
5759 vector<CInv> vGetData;
5760 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5761 vector<CBlockIndex*> vToDownload;
5762 NodeId staller = -1;
5763 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5764 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5765 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5766 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5767 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5768 pindex->nHeight, pto->id);
5770 if (state.nBlocksInFlight == 0 && staller != -1) {
5771 if (State(staller)->nStallingSince == 0) {
5772 State(staller)->nStallingSince = nNow;
5773 LogPrint("net", "Stall started peer=%d\n", staller);
5779 // Message: getdata (non-blocks)
5781 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5783 const CInv& inv = (*pto->mapAskFor.begin()).second;
5784 if (!AlreadyHave(inv))
5787 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5788 vGetData.push_back(inv);
5789 if (vGetData.size() >= 1000)
5791 pto->PushMessage("getdata", vGetData);
5795 //If we're not going to ask, don't expect a response.
5796 pto->setAskFor.erase(inv.hash);
5798 pto->mapAskFor.erase(pto->mapAskFor.begin());
5800 if (!vGetData.empty())
5801 pto->PushMessage("getdata", vGetData);
5807 std::string CBlockFileInfo::ToString() const {
5808 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));
5819 BlockMap::iterator it1 = mapBlockIndex.begin();
5820 for (; it1 != mapBlockIndex.end(); it1++)
5821 delete (*it1).second;
5822 mapBlockIndex.clear();
5824 // orphan transactions
5825 mapOrphanTransactions.clear();
5826 mapOrphanTransactionsByPrev.clear();
5828 } instance_of_cmaincleanup;
5830 extern "C" const char* getDataDir()
5832 return GetDataDir().string().c_str();