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;
52 extern uint8_t NOTARY_PUBKEY33[33];
54 BlockMap mapBlockIndex;
56 CBlockIndex *pindexBestHeader = NULL;
57 int64_t nTimeBestReceived = 0;
58 CWaitableCriticalSection csBestBlock;
59 CConditionVariable cvBlockChange;
60 int nScriptCheckThreads = 0;
61 bool fExperimentalMode = false;
62 bool fImporting = false;
63 bool fReindex = false;
64 bool fTxIndex = false;
65 bool fHavePruned = false;
66 bool fPruneMode = false;
67 bool fIsBareMultisigStd = true;
68 bool fCheckBlockIndex = false;
69 bool fCheckpointsEnabled = true;
70 bool fCoinbaseEnforcedProtectionEnabled = true;
71 size_t nCoinCacheUsage = 5000 * 300;
72 uint64_t nPruneTarget = 0;
73 bool fAlerts = DEFAULT_ALERTS;
75 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
76 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
78 CTxMemPool mempool(::minRelayTxFee);
84 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
85 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
86 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
89 * Returns true if there are nRequired or more blocks of minVersion or above
90 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
92 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
93 static void CheckBlockIndex();
95 /** Constant stuff for coinbase transactions we create: */
96 CScript COINBASE_FLAGS;
98 const string strMessageMagic = "Komodo Signed Message:\n";
103 struct CBlockIndexWorkComparator
105 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
106 // First sort by most total work, ...
107 if (pa->nChainWork > pb->nChainWork) return false;
108 if (pa->nChainWork < pb->nChainWork) return true;
110 // ... then by earliest time received, ...
111 if (pa->nSequenceId < pb->nSequenceId) return false;
112 if (pa->nSequenceId > pb->nSequenceId) return true;
114 // Use pointer address as tie breaker (should only happen with blocks
115 // loaded from disk, as those all have id 0).
116 if (pa < pb) return false;
117 if (pa > pb) return true;
124 CBlockIndex *pindexBestInvalid;
127 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
128 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
129 * missing the data for the block.
131 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
132 /** Number of nodes with fSyncStarted. */
133 int nSyncStarted = 0;
134 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
135 * Pruned nodes may have entries where B is missing data.
137 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
139 CCriticalSection cs_LastBlockFile;
140 std::vector<CBlockFileInfo> vinfoBlockFile;
141 int nLastBlockFile = 0;
142 /** Global flag to indicate we should check to see if there are
143 * block/undo files that should be deleted. Set on startup
144 * or if we allocate more file space when we're in prune mode
146 bool fCheckForPruning = false;
149 * Every received block is assigned a unique and increasing identifier, so we
150 * know which one to give priority in case of a fork.
152 CCriticalSection cs_nBlockSequenceId;
153 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
154 uint32_t nBlockSequenceId = 1;
157 * Sources of received blocks, saved to be able to send them reject
158 * messages or ban them when processing happens afterwards. Protected by
161 map<uint256, NodeId> mapBlockSource;
164 * Filter for transactions that were recently rejected by
165 * AcceptToMemoryPool. These are not rerequested until the chain tip
166 * changes, at which point the entire filter is reset. Protected by
169 * Without this filter we'd be re-requesting txs from each of our peers,
170 * increasing bandwidth consumption considerably. For instance, with 100
171 * peers, half of which relay a tx we don't accept, that might be a 50x
172 * bandwidth increase. A flooding attacker attempting to roll-over the
173 * filter using minimum-sized, 60byte, transactions might manage to send
174 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
175 * two minute window to send invs to us.
177 * Decreasing the false positive rate is fairly cheap, so we pick one in a
178 * million to make it highly unlikely for users to have issues with this
183 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
184 uint256 hashRecentRejectsChainTip;
186 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
189 CBlockIndex *pindex; //! Optional.
190 int64_t nTime; //! Time of "getdata" request in microseconds.
191 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
192 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
194 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
196 /** Number of blocks in flight with validated headers. */
197 int nQueuedValidatedHeaders = 0;
199 /** Number of preferable block download peers. */
200 int nPreferredDownload = 0;
202 /** Dirty block index entries. */
203 set<CBlockIndex*> setDirtyBlockIndex;
205 /** Dirty block file entries. */
206 set<int> setDirtyFileInfo;
209 //////////////////////////////////////////////////////////////////////////////
211 // Registration of network node signals.
216 struct CBlockReject {
217 unsigned char chRejectCode;
218 string strRejectReason;
223 * Maintain validation-specific state about nodes, protected by cs_main, instead
224 * by CNode's own locks. This simplifies asynchronous operation, where
225 * processing of incoming data is done after the ProcessMessage call returns,
226 * and we're no longer holding the node's locks.
229 //! The peer's address
231 //! Whether we have a fully established connection.
232 bool fCurrentlyConnected;
233 //! Accumulated misbehaviour score for this peer.
235 //! Whether this peer should be disconnected and banned (unless whitelisted).
237 //! String name of this peer (debugging/logging purposes).
239 //! List of asynchronously-determined block rejections to notify this peer about.
240 std::vector<CBlockReject> rejects;
241 //! The best known block we know this peer has announced.
242 CBlockIndex *pindexBestKnownBlock;
243 //! The hash of the last unknown block this peer has announced.
244 uint256 hashLastUnknownBlock;
245 //! The last full block we both have.
246 CBlockIndex *pindexLastCommonBlock;
247 //! Whether we've started headers synchronization with this peer.
249 //! Since when we're stalling block download progress (in microseconds), or 0.
250 int64_t nStallingSince;
251 list<QueuedBlock> vBlocksInFlight;
253 int nBlocksInFlightValidHeaders;
254 //! Whether we consider this a preferred download peer.
255 bool fPreferredDownload;
258 fCurrentlyConnected = false;
261 pindexBestKnownBlock = NULL;
262 hashLastUnknownBlock.SetNull();
263 pindexLastCommonBlock = NULL;
264 fSyncStarted = false;
267 nBlocksInFlightValidHeaders = 0;
268 fPreferredDownload = false;
272 /** Map maintaining per-node state. Requires cs_main. */
273 map<NodeId, CNodeState> mapNodeState;
276 CNodeState *State(NodeId pnode) {
277 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
278 if (it == mapNodeState.end())
286 return chainActive.Height();
289 void UpdatePreferredDownload(CNode* node, CNodeState* state)
291 nPreferredDownload -= state->fPreferredDownload;
293 // Whether this node should be marked as a preferred download node.
294 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
296 nPreferredDownload += state->fPreferredDownload;
299 // Returns time at which to timeout block request (nTime in microseconds)
300 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
302 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
305 void InitializeNode(NodeId nodeid, const CNode *pnode) {
307 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
308 state.name = pnode->addrName;
309 state.address = pnode->addr;
312 void FinalizeNode(NodeId nodeid) {
314 CNodeState *state = State(nodeid);
316 if (state->fSyncStarted)
319 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
320 AddressCurrentlyConnected(state->address);
323 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
324 mapBlocksInFlight.erase(entry.hash);
325 EraseOrphansFor(nodeid);
326 nPreferredDownload -= state->fPreferredDownload;
328 mapNodeState.erase(nodeid);
331 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)
333 /* int expired = pool.Expire(GetTime() - age);
335 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
337 std::vector<uint256> vNoSpendsRemaining;
338 pool.TrimToSize(limit, &vNoSpendsRemaining);
339 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
340 pcoinsTip->Uncache(removed);*/
344 // Returns a bool indicating whether we requested this block.
345 bool MarkBlockAsReceived(const uint256& hash) {
346 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
347 if (itInFlight != mapBlocksInFlight.end()) {
348 CNodeState *state = State(itInFlight->second.first);
349 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
350 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
351 state->vBlocksInFlight.erase(itInFlight->second.second);
352 state->nBlocksInFlight--;
353 state->nStallingSince = 0;
354 mapBlocksInFlight.erase(itInFlight);
361 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
362 CNodeState *state = State(nodeid);
363 assert(state != NULL);
365 // Make sure it's not listed somewhere already.
366 MarkBlockAsReceived(hash);
368 int64_t nNow = GetTimeMicros();
369 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
370 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
371 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
372 state->nBlocksInFlight++;
373 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
374 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
377 /** Check whether the last unknown block a peer advertized is not yet known. */
378 void ProcessBlockAvailability(NodeId nodeid) {
379 CNodeState *state = State(nodeid);
380 assert(state != NULL);
382 if (!state->hashLastUnknownBlock.IsNull()) {
383 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
384 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0)
386 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
387 state->pindexBestKnownBlock = itOld->second;
388 state->hashLastUnknownBlock.SetNull();
393 /** Update tracking information about which blocks a peer is assumed to have. */
394 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
395 CNodeState *state = State(nodeid);
396 assert(state != NULL);
398 /*ProcessBlockAvailability(nodeid);
400 BlockMap::iterator it = mapBlockIndex.find(hash);
401 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
402 // An actually better block was announced.
403 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
404 state->pindexBestKnownBlock = it->second;
407 // An unknown block was announced; just assume that the latest one is the best one.
408 state->hashLastUnknownBlock = hash;
412 /** Find the last common ancestor two blocks have.
413 * Both pa and pb must be non-NULL. */
414 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
415 if (pa->nHeight > pb->nHeight) {
416 pa = pa->GetAncestor(pb->nHeight);
417 } else if (pb->nHeight > pa->nHeight) {
418 pb = pb->GetAncestor(pa->nHeight);
421 while (pa != pb && pa && pb) {
426 // Eventually all chain branches meet at the genesis block.
431 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
432 * at most count entries. */
433 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
437 vBlocks.reserve(vBlocks.size() + count);
438 CNodeState *state = State(nodeid);
439 assert(state != NULL);
441 // Make sure pindexBestKnownBlock is up to date, we'll need it.
442 ProcessBlockAvailability(nodeid);
444 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
445 // This peer has nothing interesting.
449 if (state->pindexLastCommonBlock == NULL) {
450 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
451 // Guessing wrong in either direction is not a problem.
452 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
455 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
456 // of its current tip anymore. Go back enough to fix that.
457 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
458 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
461 std::vector<CBlockIndex*> vToFetch;
462 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
463 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
464 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
465 // download that next block if the window were 1 larger.
466 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
467 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
468 NodeId waitingfor = -1;
469 while (pindexWalk->nHeight < nMaxHeight) {
470 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
471 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
472 // as iterating over ~100 CBlockIndex* entries anyway.
473 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
474 vToFetch.resize(nToFetch);
475 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
476 vToFetch[nToFetch - 1] = pindexWalk;
477 for (unsigned int i = nToFetch - 1; i > 0; i--) {
478 vToFetch[i - 1] = vToFetch[i]->pprev;
481 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
482 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
483 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
484 // already part of our chain (and therefore don't need it even if pruned).
485 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
486 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
487 // We consider the chain that this peer is on invalid.
490 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
491 if (pindex->nChainTx)
492 state->pindexLastCommonBlock = pindex;
493 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
494 // The block is not already downloaded, and not yet in flight.
495 if (pindex->nHeight > nWindowEnd) {
496 // We reached the end of the window.
497 if (vBlocks.size() == 0 && waitingfor != nodeid) {
498 // We aren't able to fetch anything, but we would be if the download window was one larger.
499 nodeStaller = waitingfor;
503 vBlocks.push_back(pindex);
504 if (vBlocks.size() == count) {
507 } else if (waitingfor == -1) {
508 // This is the first already-in-flight block.
509 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
517 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
519 CNodeState *state = State(nodeid);
522 stats.nMisbehavior = state->nMisbehavior;
523 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
524 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
525 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
527 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
532 void RegisterNodeSignals(CNodeSignals& nodeSignals)
534 nodeSignals.GetHeight.connect(&GetHeight);
535 nodeSignals.ProcessMessages.connect(&ProcessMessages);
536 nodeSignals.SendMessages.connect(&SendMessages);
537 nodeSignals.InitializeNode.connect(&InitializeNode);
538 nodeSignals.FinalizeNode.connect(&FinalizeNode);
541 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
543 nodeSignals.GetHeight.disconnect(&GetHeight);
544 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
545 nodeSignals.SendMessages.disconnect(&SendMessages);
546 nodeSignals.InitializeNode.disconnect(&InitializeNode);
547 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
550 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
552 // Find the first block the caller has in the main chain
553 BOOST_FOREACH(const uint256& hash, locator.vHave) {
554 BlockMap::iterator mi = mapBlockIndex.find(hash);
555 if (mi != mapBlockIndex.end())
557 CBlockIndex* pindex = (*mi).second;
558 if (pindex != 0 && chain.Contains(pindex))
562 return chain.Genesis();
565 CCoinsViewCache *pcoinsTip = NULL;
566 CBlockTreeDB *pblocktree = NULL;
573 //////////////////////////////////////////////////////////////////////////////
575 // mapOrphanTransactions
578 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
580 uint256 hash = tx.GetHash();
581 if (mapOrphanTransactions.count(hash))
584 // Ignore big transactions, to avoid a
585 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
586 // large transaction with a missing parent then we assume
587 // it will rebroadcast it later, after the parent transaction(s)
588 // have been mined or received.
589 // 10,000 orphans, each of which is at most 5,000 bytes big is
590 // at most 500 megabytes of orphans:
591 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
594 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
598 mapOrphanTransactions[hash].tx = tx;
599 mapOrphanTransactions[hash].fromPeer = peer;
600 BOOST_FOREACH(const CTxIn& txin, tx.vin)
601 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
603 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
604 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
608 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
610 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
611 if (it == mapOrphanTransactions.end())
613 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
615 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
616 if (itPrev == mapOrphanTransactionsByPrev.end())
618 itPrev->second.erase(hash);
619 if (itPrev->second.empty())
620 mapOrphanTransactionsByPrev.erase(itPrev);
622 mapOrphanTransactions.erase(it);
625 void EraseOrphansFor(NodeId peer)
628 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
629 while (iter != mapOrphanTransactions.end())
631 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
632 if (maybeErase->second.fromPeer == peer)
634 EraseOrphanTx(maybeErase->second.tx.GetHash());
638 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
642 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
644 unsigned int nEvicted = 0;
645 while (mapOrphanTransactions.size() > nMaxOrphans)
647 // Evict a random orphan:
648 uint256 randomhash = GetRandHash();
649 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
650 if (it == mapOrphanTransactions.end())
651 it = mapOrphanTransactions.begin();
652 EraseOrphanTx(it->first);
664 bool IsStandardTx(const CTransaction& tx, string& reason)
666 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
671 BOOST_FOREACH(const CTxIn& txin, tx.vin)
673 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
674 // keys. (remember the 520 byte limit on redeemScript size) That works
675 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
676 // bytes of scriptSig, which we round off to 1650 bytes for some minor
677 // future-proofing. That's also enough to spend a 20-of-20
678 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
679 // considered standard)
680 if (txin.scriptSig.size() > 1650) {
681 reason = "scriptsig-size";
684 if (!txin.scriptSig.IsPushOnly()) {
685 reason = "scriptsig-not-pushonly";
690 unsigned int v=0,nDataOut = 0;
691 txnouttype whichType;
692 BOOST_FOREACH(const CTxOut& txout, tx.vout)
694 if (!::IsStandard(txout.scriptPubKey, whichType))
696 reason = "scriptpubkey";
697 fprintf(stderr,">>>>>>>>>>>>>>> vout.%d nDataout.%d\n",v,nDataOut);
701 if (whichType == TX_NULL_DATA)
704 //fprintf(stderr,"is OP_RETURN\n");
706 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
707 reason = "bare-multisig";
709 } else if (txout.IsDust(::minRelayTxFee)) {
716 // only one OP_RETURN txout is permitted
718 reason = "multi-op-return";
725 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
728 if (tx.nLockTime == 0)
730 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
732 BOOST_FOREACH(const CTxIn& txin, tx.vin)
734 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)) )
738 else if (!txin.IsFinal())
740 printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime);
747 bool CheckFinalTx(const CTransaction &tx, int flags)
749 AssertLockHeld(cs_main);
751 // By convention a negative value for flags indicates that the
752 // current network-enforced consensus rules should be used. In
753 // a future soft-fork scenario that would mean checking which
754 // rules would be enforced for the next block and setting the
755 // appropriate flags. At the present time no soft-forks are
756 // scheduled, so no flags are set.
757 flags = std::max(flags, 0);
759 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
760 // nLockTime because when IsFinalTx() is called within
761 // CBlock::AcceptBlock(), the height of the block *being*
762 // evaluated is what is used. Thus if we want to know if a
763 // transaction can be part of the *next* block, we need to call
764 // IsFinalTx() with one more than chainActive.Height().
765 const int nBlockHeight = chainActive.Height() + 1;
767 // Timestamps on the other hand don't get any special treatment,
768 // because we can't know what timestamp the next block will have,
769 // and there aren't timestamp applications where it matters.
770 // However this changes once median past time-locks are enforced:
771 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
772 ? chainActive.Tip()->GetMedianTimePast()
775 return IsFinalTx(tx, nBlockHeight, nBlockTime);
779 * Check transaction inputs to mitigate two
780 * potential denial-of-service attacks:
782 * 1. scriptSigs with extra data stuffed into them,
783 * not consumed by scriptPubKey (or P2SH script)
784 * 2. P2SH scripts with a crazy number of expensive
785 * CHECKSIG/CHECKMULTISIG operations
787 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
790 return true; // Coinbases don't use vin normally
792 for (unsigned int i = 0; i < tx.vin.size(); i++)
794 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
796 vector<vector<unsigned char> > vSolutions;
797 txnouttype whichType;
798 // get the scriptPubKey corresponding to this input:
799 const CScript& prevScript = prev.scriptPubKey;
800 if (!Solver(prevScript, whichType, vSolutions))
802 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
803 if (nArgsExpected < 0)
806 // Transactions with extra stuff in their scriptSigs are
807 // non-standard. Note that this EvalScript() call will
808 // be quick, because if there are any operations
809 // beside "push data" in the scriptSig
810 // IsStandardTx() will have already returned false
811 // and this method isn't called.
812 vector<vector<unsigned char> > stack;
813 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
816 if (whichType == TX_SCRIPTHASH)
820 CScript subscript(stack.back().begin(), stack.back().end());
821 vector<vector<unsigned char> > vSolutions2;
822 txnouttype whichType2;
823 if (Solver(subscript, whichType2, vSolutions2))
825 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
828 nArgsExpected += tmpExpected;
832 // Any other Script with less than 15 sigops OK:
833 unsigned int sigops = subscript.GetSigOpCount(true);
834 // ... extra data left on the stack after execution is OK, too:
835 return (sigops <= MAX_P2SH_SIGOPS);
839 if (stack.size() != (unsigned int)nArgsExpected)
846 unsigned int GetLegacySigOpCount(const CTransaction& tx)
848 unsigned int nSigOps = 0;
849 BOOST_FOREACH(const CTxIn& txin, tx.vin)
851 nSigOps += txin.scriptSig.GetSigOpCount(false);
853 BOOST_FOREACH(const CTxOut& txout, tx.vout)
855 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
860 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
865 unsigned int nSigOps = 0;
866 for (unsigned int i = 0; i < tx.vin.size(); i++)
868 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
869 if (prevout.scriptPubKey.IsPayToScriptHash())
870 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
875 bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash::ProofVerifier& verifier)
877 static uint256 array[64]; static int32_t numbanned,indallvouts; int32_t j,k,n;
878 if ( *(int32_t *)&array[0] == 0 )
879 numbanned = komodo_bannedset(&indallvouts,array,(int32_t)(sizeof(array)/sizeof(*array)));
883 for (k=0; k<numbanned; k++)
885 if ( tx.vin[j].prevout.hash == array[k] && (tx.vin[j].prevout.n == 1 || k >= indallvouts) )
887 static uint32_t counter;
888 if ( counter++ < 100 )
889 printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->nHeight,j);
894 // Don't count coinbase transactions because mining skews the count
895 if (!tx.IsCoinBase()) {
896 transactionsValidated.increment();
899 if (!CheckTransactionWithoutProofVerification(tx, state)) {
902 // Ensure that zk-SNARKs verify
903 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
904 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
905 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
906 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
913 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
915 // Basic checks that don't depend on any context
917 // Check transaction version
918 if (tx.nVersion < MIN_TX_VERSION) {
919 return state.DoS(100, error("CheckTransaction(): version too low"),
920 REJECT_INVALID, "bad-txns-version-too-low");
923 // Transactions can contain empty `vin` and `vout` so long as
924 // `vjoinsplit` is non-empty.
925 if (tx.vin.empty() && tx.vjoinsplit.empty())
926 return state.DoS(10, error("CheckTransaction(): vin empty"),
927 REJECT_INVALID, "bad-txns-vin-empty");
928 if (tx.vout.empty() && tx.vjoinsplit.empty())
929 return state.DoS(10, error("CheckTransaction(): vout empty"),
930 REJECT_INVALID, "bad-txns-vout-empty");
933 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
934 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
935 return state.DoS(100, error("CheckTransaction(): size limits failed"),
936 REJECT_INVALID, "bad-txns-oversize");
938 // Check for negative or overflow output values
939 CAmount nValueOut = 0;
940 BOOST_FOREACH(const CTxOut& txout, tx.vout)
942 if (txout.nValue < 0)
943 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
944 REJECT_INVALID, "bad-txns-vout-negative");
945 if (txout.nValue > MAX_MONEY)
947 fprintf(stderr,"%.8f > max %.8f\n",(double)txout.nValue/COIN,(double)MAX_MONEY/COIN);
948 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),REJECT_INVALID, "bad-txns-vout-toolarge");
950 nValueOut += txout.nValue;
951 if (!MoneyRange(nValueOut))
952 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
953 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
956 // Ensure that joinsplit values are well-formed
957 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
959 if (joinsplit.vpub_old < 0) {
960 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
961 REJECT_INVALID, "bad-txns-vpub_old-negative");
964 if (joinsplit.vpub_new < 0) {
965 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
966 REJECT_INVALID, "bad-txns-vpub_new-negative");
969 if (joinsplit.vpub_old > MAX_MONEY) {
970 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
971 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
974 if (joinsplit.vpub_new > MAX_MONEY) {
975 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
976 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
979 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
980 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
981 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
984 nValueOut += joinsplit.vpub_old;
985 if (!MoneyRange(nValueOut)) {
986 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
987 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
991 // Ensure input values do not exceed MAX_MONEY
992 // We have not resolved the txin values at this stage,
993 // but we do know what the joinsplits claim to add
994 // to the value pool.
996 CAmount nValueIn = 0;
997 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
999 nValueIn += it->vpub_new;
1001 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1002 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1003 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1009 // Check for duplicate inputs
1010 set<COutPoint> vInOutPoints;
1011 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1013 if (vInOutPoints.count(txin.prevout))
1014 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1015 REJECT_INVALID, "bad-txns-inputs-duplicate");
1016 vInOutPoints.insert(txin.prevout);
1019 // Check for duplicate joinsplit nullifiers in this transaction
1020 set<uint256> vJoinSplitNullifiers;
1021 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1023 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1025 if (vJoinSplitNullifiers.count(nf))
1026 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1027 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1029 vJoinSplitNullifiers.insert(nf);
1033 if (tx.IsCoinBase())
1035 // There should be no joinsplits in a coinbase transaction
1036 if (tx.vjoinsplit.size() > 0)
1037 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1038 REJECT_INVALID, "bad-cb-has-joinsplits");
1040 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1041 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1042 REJECT_INVALID, "bad-cb-length");
1046 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1047 if (txin.prevout.IsNull())
1048 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1049 REJECT_INVALID, "bad-txns-prevout-null");
1051 if (tx.vjoinsplit.size() > 0) {
1052 // Empty output script.
1054 uint256 dataToBeSigned;
1056 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1057 } catch (std::logic_error ex) {
1058 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1059 REJECT_INVALID, "error-computing-signature-hash");
1062 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1064 // We rely on libsodium to check that the signature is canonical.
1065 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1066 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1067 dataToBeSigned.begin(), 32,
1068 tx.joinSplitPubKey.begin()
1070 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1071 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1079 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1081 extern int32_t KOMODO_ON_DEMAND;
1084 uint256 hash = tx.GetHash();
1085 double dPriorityDelta = 0;
1086 CAmount nFeeDelta = 0;
1087 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1088 if (dPriorityDelta > 0 || nFeeDelta > 0)
1092 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1096 // There is a free transaction area in blocks created by most miners,
1097 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1098 // to be considered to fall into this category. We don't want to encourage sending
1099 // multiple transactions instead of one big transaction to avoid fees.
1100 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1104 if (!MoneyRange(nMinFee))
1105 nMinFee = MAX_MONEY;
1110 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
1112 AssertLockHeld(cs_main);
1113 if (pfMissingInputs)
1114 *pfMissingInputs = false;
1115 auto verifier = libzcash::ProofVerifier::Strict();
1116 if ( komodo_validate_interest(tx,chainActive.Tip()->nHeight+1,chainActive.Tip()->GetMedianTimePast() + 777,0) < 0 )
1118 //fprintf(stderr,"AcceptToMemoryPool komodo_validate_interest failure\n");
1119 return error("AcceptToMemoryPool: komodo_validate_interest failed");
1121 if (!CheckTransaction(tx, state, verifier))
1123 fprintf(stderr,"accept failure.0\n");
1124 return error("AcceptToMemoryPool: CheckTransaction failed");
1126 // Coinbase is only valid in a block, not as a loose transaction
1127 if (tx.IsCoinBase())
1129 fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
1130 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
1132 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1134 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1136 fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str());
1137 return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
1139 // Only accept nLockTime-using transactions that can be mined in the next
1140 // block; we don't want our mempool filled up with transactions that can't
1142 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1144 //fprintf(stderr,"AcceptToMemoryPool reject non-final\n");
1145 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1147 // is it already in the memory pool?
1148 uint256 hash = tx.GetHash();
1149 if (pool.exists(hash))
1151 fprintf(stderr,"already in mempool\n");
1155 // Check for conflicts with in-memory transactions
1157 LOCK(pool.cs); // protect pool.mapNextTx
1158 for (unsigned int i = 0; i < tx.vin.size(); i++)
1160 COutPoint outpoint = tx.vin[i].prevout;
1161 if (pool.mapNextTx.count(outpoint))
1163 static uint32_t counter;
1164 // Disable replacement feature for now
1165 //if ( counter++ < 100 )
1166 fprintf(stderr,"Disable replacement feature for now\n");
1170 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1171 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1172 if (pool.mapNullifiers.count(nf))
1174 fprintf(stderr,"pool.mapNullifiers.count\n");
1183 CCoinsViewCache view(&dummy);
1185 CAmount nValueIn = 0;
1188 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1189 view.SetBackend(viewMemPool);
1191 // do we already have it?
1192 if (view.HaveCoins(hash))
1194 fprintf(stderr,"view.HaveCoins(hash) error\n");
1198 // do all inputs exist?
1199 // Note that this does not check for the presence of actual outputs (see the next check for that),
1200 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1201 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1202 if (!view.HaveCoins(txin.prevout.hash)) {
1203 if (pfMissingInputs)
1204 *pfMissingInputs = true;
1205 //fprintf(stderr,"missing inputs\n");
1210 // are the actual inputs available?
1211 if (!view.HaveInputs(tx))
1213 //fprintf(stderr,"accept failure.1\n");
1214 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent");
1216 // are the joinsplit's requirements met?
1217 if (!view.HaveJoinSplitRequirements(tx))
1219 fprintf(stderr,"accept failure.2\n");
1220 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1223 // Bring the best block into scope
1224 view.GetBestBlock();
1226 nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
1227 if ( 0 && interest != 0 )
1228 fprintf(stderr,"add interest %.8f\n",(double)interest/COIN);
1229 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1230 view.SetBackend(dummy);
1233 // Check for non-standard pay-to-script-hash in inputs
1234 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1236 fprintf(stderr,"accept failure.3\n");
1237 return error("AcceptToMemoryPool: nonstandard transaction input");
1240 // Check that the transaction doesn't have an excessive number of
1241 // sigops, making it impossible to mine. Since the coinbase transaction
1242 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1243 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1244 // merely non-standard transaction.
1245 unsigned int nSigOps = GetLegacySigOpCount(tx);
1246 nSigOps += GetP2SHSigOpCount(tx, view);
1247 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1249 fprintf(stderr,"accept failure.4\n");
1250 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");
1253 CAmount nValueOut = tx.GetValueOut();
1254 CAmount nFees = nValueIn-nValueOut;
1255 double dPriority = view.GetPriority(tx, chainActive.Height());
1257 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1258 unsigned int nSize = entry.GetTxSize();
1260 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1261 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1262 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1264 // Don't accept it if it can't get into a block
1265 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1266 if (fLimitFree && nFees < txMinFee)
1268 fprintf(stderr,"accept failure.5\n");
1269 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee");
1273 // Require that free transactions have sufficient priority to be mined in the next block.
1274 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1275 fprintf(stderr,"accept failure.6\n");
1276 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1279 // Continuously rate-limit free (really, very-low-fee) transactions
1280 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1281 // be annoying or make others' transactions take longer to confirm.
1282 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1284 static CCriticalSection csFreeLimiter;
1285 static double dFreeCount;
1286 static int64_t nLastTime;
1287 int64_t nNow = GetTime();
1289 LOCK(csFreeLimiter);
1291 // Use an exponentially decaying ~10-minute window:
1292 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1294 // -limitfreerelay unit is thousand-bytes-per-minute
1295 // At default rate it would take over a month to fill 1GB
1296 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1298 fprintf(stderr,"accept failure.7\n");
1299 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1301 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1302 dFreeCount += nSize;
1305 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000 && nFees > nValueOut/19 )
1307 fprintf(stderr,"accept failure.8\n");
1308 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1311 // Check against previous transactions
1312 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1313 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1315 fprintf(stderr,"accept failure.9\n");
1316 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1319 // Check again against just the consensus-critical mandatory script
1320 // verification flags, in case of bugs in the standard flags that cause
1321 // transactions to pass as valid when they're actually invalid. For
1322 // instance the STRICTENC flag was incorrectly allowing certain
1323 // CHECKSIG NOT scripts to pass, even though they were invalid.
1325 // There is a similar check in CreateNewBlock() to prevent creating
1326 // invalid blocks, however allowing such transactions into the mempool
1327 // can be exploited as a DoS attack.
1328 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1330 fprintf(stderr,"accept failure.10\n");
1331 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1334 // Store transaction in memory
1335 if ( komodo_is_notarytx(tx) == 0 )
1337 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1340 SyncWithWallets(tx, NULL);
1345 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1346 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1348 CBlockIndex *pindexSlow = NULL;
1352 if (mempool.lookup(hash, txOut))
1359 if (pblocktree->ReadTxIndex(hash, postx)) {
1360 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1362 return error("%s: OpenBlockFile failed", __func__);
1363 CBlockHeader header;
1366 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1368 } catch (const std::exception& e) {
1369 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1371 hashBlock = header.GetHash();
1372 if (txOut.GetHash() != hash)
1373 return error("%s: txid mismatch", __func__);
1378 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1381 CCoinsViewCache &view = *pcoinsTip;
1382 const CCoins* coins = view.AccessCoins(hash);
1384 nHeight = coins->nHeight;
1387 pindexSlow = chainActive[nHeight];
1392 if (ReadBlockFromDisk(block, pindexSlow)) {
1393 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1394 if (tx.GetHash() == hash) {
1396 hashBlock = pindexSlow->GetBlockHash();
1406 /*char *komodo_getspendscript(uint256 hash,int32_t n)
1408 CTransaction tx; uint256 hashBlock;
1409 if ( !GetTransaction(hash,tx,hashBlock,true) )
1411 printf("null GetTransaction\n");
1414 if ( n >= 0 && n < tx.vout.size() )
1415 return((char *)tx.vout[n].scriptPubKey.ToString().c_str());
1416 else printf("getspendscript illegal n.%d\n",n);
1421 //////////////////////////////////////////////////////////////////////////////
1423 // CBlock and CBlockIndex
1426 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1428 // Open history file to append
1429 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1430 if (fileout.IsNull())
1431 return error("WriteBlockToDisk: OpenBlockFile failed");
1433 // Write index header
1434 unsigned int nSize = fileout.GetSerializeSize(block);
1435 fileout << FLATDATA(messageStart) << nSize;
1438 long fileOutPos = ftell(fileout.Get());
1440 return error("WriteBlockToDisk: ftell failed");
1441 pos.nPos = (unsigned int)fileOutPos;
1447 bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos)
1449 uint8_t pubkey33[33];
1452 // Open history file to read
1453 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1454 if (filein.IsNull())
1456 //fprintf(stderr,"readblockfromdisk err A\n");
1457 return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1464 catch (const std::exception& e) {
1465 fprintf(stderr,"readblockfromdisk err B\n");
1466 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1469 komodo_block2pubkey33(pubkey33,block);
1470 if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus())))
1472 int32_t i; for (i=0; i<33; i++)
1473 printf("%02x",pubkey33[i]);
1474 fprintf(stderr," warning unexpected diff at ht.%d\n",height);
1476 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1481 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1485 if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos()))
1487 if (block.GetHash() != pindex->GetBlockHash())
1488 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1489 pindex->ToString(), pindex->GetBlockPos().ToString());
1493 uint64_t komodo_moneysupply(int32_t height);
1494 extern char ASSETCHAINS_SYMBOL[16];
1495 extern uint32_t ASSETCHAINS_MAGIC;
1496 extern uint64_t ASSETCHAINS_SUPPLY;
1498 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1500 CAmount nSubsidy = 3 * COIN;
1501 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1504 return(100000000 * COIN); // ICO allocation
1505 else if ( komodo_moneysupply(nHeight) < MAX_MONEY )
1512 return(ASSETCHAINS_SUPPLY * COIN + (ASSETCHAINS_MAGIC & 0xffffff));
1516 // Mining slow start
1517 // The subsidy is ramped up linearly, skipping the middle payout of
1518 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1519 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1520 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1521 nSubsidy *= nHeight;
1523 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1524 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1525 nSubsidy *= (nHeight+1);
1529 assert(nHeight > consensusParams.SubsidySlowStartShift());
1530 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/
1531 // Force block reward to zero when right shift is undefined.
1532 //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1533 //if (halvings >= 64)
1536 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1537 //nSubsidy >>= halvings;
1541 bool IsInitialBlockDownload()
1543 const CChainParams& chainParams = Params();
1545 if (fImporting || fReindex)
1547 //fprintf(stderr,"IsInitialBlockDownload: fImporting %d || %d fReindex\n",(int32_t)fImporting,(int32_t)fReindex);
1550 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1552 //fprintf(stderr,"IsInitialBlockDownload: checkpoint -> initialdownload\n");
1555 static bool lockIBDState = false;
1558 //fprintf(stderr,"lockIBDState true %d < %d\n",chainActive.Height(),pindexBestHeader->nHeight - 10);
1561 bool state; CBlockIndex *ptr = chainActive.Tip();
1563 ptr = pindexBestHeader;
1564 else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight )
1565 ptr = pindexBestHeader;
1566 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1567 state = ((chainActive.Height() < ptr->nHeight - 24*60) ||
1568 ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge()));
1569 else state = (chainActive.Height() < ptr->nHeight - 10);
1570 //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()));
1573 lockIBDState = true;
1578 bool fLargeWorkForkFound = false;
1579 bool fLargeWorkInvalidChainFound = false;
1580 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1582 void CheckForkWarningConditions()
1584 AssertLockHeld(cs_main);
1585 // Before we get past initial download, we cannot reliably alert about forks
1586 // (we assume we don't get stuck on a fork before the last checkpoint)
1587 if (IsInitialBlockDownload())
1590 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1591 // of our head, drop it
1592 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1593 pindexBestForkTip = NULL;
1595 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1597 if (!fLargeWorkForkFound && pindexBestForkBase)
1599 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1600 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1601 CAlert::Notify(warning, true);
1603 if (pindexBestForkTip && pindexBestForkBase)
1605 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__,
1606 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1607 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1608 fLargeWorkForkFound = true;
1612 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1613 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1614 CAlert::Notify(warning, true);
1615 fLargeWorkInvalidChainFound = true;
1620 fLargeWorkForkFound = false;
1621 fLargeWorkInvalidChainFound = false;
1625 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1627 AssertLockHeld(cs_main);
1628 // If we are on a fork that is sufficiently large, set a warning flag
1629 CBlockIndex* pfork = pindexNewForkTip;
1630 CBlockIndex* plonger = chainActive.Tip();
1631 while (pfork && pfork != plonger)
1633 while (plonger && plonger->nHeight > pfork->nHeight)
1634 plonger = plonger->pprev;
1635 if (pfork == plonger)
1637 pfork = pfork->pprev;
1640 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1641 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1642 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1643 // hash rate operating on the fork.
1644 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1645 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1646 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1647 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1648 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1649 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1651 pindexBestForkTip = pindexNewForkTip;
1652 pindexBestForkBase = pfork;
1655 CheckForkWarningConditions();
1658 // Requires cs_main.
1659 void Misbehaving(NodeId pnode, int howmuch)
1664 CNodeState *state = State(pnode);
1668 state->nMisbehavior += howmuch;
1669 int banscore = GetArg("-banscore", 100);
1670 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1672 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1673 state->fShouldBan = true;
1675 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1678 void static InvalidChainFound(CBlockIndex* pindexNew)
1680 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1681 pindexBestInvalid = pindexNew;
1683 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1684 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1685 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1686 pindexNew->GetBlockTime()));
1687 CBlockIndex *tip = chainActive.Tip();
1689 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1690 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1691 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1692 CheckForkWarningConditions();
1695 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1697 if (state.IsInvalid(nDoS)) {
1698 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1699 if (it != mapBlockSource.end() && State(it->second)) {
1700 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1701 State(it->second)->rejects.push_back(reject);
1703 Misbehaving(it->second, nDoS);
1706 if (!state.CorruptionPossible()) {
1707 pindex->nStatus |= BLOCK_FAILED_VALID;
1708 setDirtyBlockIndex.insert(pindex);
1709 setBlockIndexCandidates.erase(pindex);
1710 InvalidChainFound(pindex);
1714 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1716 if (!tx.IsCoinBase()) // mark inputs spent
1718 txundo.vprevout.reserve(tx.vin.size());
1719 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1720 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1721 unsigned nPos = txin.prevout.n;
1723 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1725 // mark an outpoint spent, and construct undo information
1726 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1728 if (coins->vout.size() == 0) {
1729 CTxInUndo& undo = txundo.vprevout.back();
1730 undo.nHeight = coins->nHeight;
1731 undo.fCoinBase = coins->fCoinBase;
1732 undo.nVersion = coins->nVersion;
1736 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { // spend nullifiers
1737 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1738 inputs.SetNullifier(nf, true);
1741 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); // add outputs
1744 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1747 UpdateCoins(tx, state, inputs, txundo, nHeight);
1750 bool CScriptCheck::operator()() {
1751 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1752 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1753 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1758 int GetSpendHeight(const CCoinsViewCache& inputs)
1761 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1762 return pindexPrev->nHeight + 1;
1765 namespace Consensus {
1766 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1768 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1769 // for an attacker to attempt to split the network.
1770 if (!inputs.HaveInputs(tx))
1771 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1773 // are the JoinSplit's requirements met?
1774 if (!inputs.HaveJoinSplitRequirements(tx))
1775 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1777 CAmount nValueIn = 0;
1779 for (unsigned int i = 0; i < tx.vin.size(); i++)
1781 const COutPoint &prevout = tx.vin[i].prevout;
1782 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1785 if (coins->IsCoinBase()) {
1786 // Ensure that coinbases are matured
1787 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1788 return state.Invalid(
1789 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1790 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1793 // Ensure that coinbases cannot be spent to transparent outputs
1794 // Disabled on regtest
1795 if (fCoinbaseEnforcedProtectionEnabled &&
1796 consensusParams.fCoinbaseMustBeProtected &&
1798 return state.Invalid(
1799 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1800 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1804 // Check for negative or overflow input values
1805 nValueIn += coins->vout[prevout.n].nValue;
1806 #ifdef KOMODO_ENABLE_INTEREST
1807 if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 )
1809 if ( coins->vout[prevout.n].nValue >= 10*COIN )
1811 int64_t interest; int32_t txheight; uint32_t locktime;
1812 if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue)) != 0 )
1814 //fprintf(stderr,"checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime);
1815 nValueIn += interest;
1820 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1821 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1822 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1826 nValueIn += tx.GetJoinSplitValueIn();
1827 if (!MoneyRange(nValueIn))
1828 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1829 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1831 if (nValueIn < tx.GetValueOut())
1832 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f",
1833 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout");
1835 // Tally transaction fees
1836 CAmount nTxFee = nValueIn - tx.GetValueOut();
1838 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1839 REJECT_INVALID, "bad-txns-fee-negative");
1841 if (!MoneyRange(nFees))
1842 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1843 REJECT_INVALID, "bad-txns-fee-outofrange");
1846 }// namespace Consensus
1848 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1850 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams))
1853 if (!tx.IsCoinBase())
1856 pvChecks->reserve(tx.vin.size());
1858 // The first loop above does all the inexpensive checks.
1859 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1860 // Helps prevent CPU exhaustion attacks.
1862 // Skip ECDSA signature verification when connecting blocks
1863 // before the last block chain checkpoint. This is safe because block merkle hashes are
1864 // still computed and checked, and any change will be caught at the next checkpoint.
1865 if (fScriptChecks) {
1866 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1867 const COutPoint &prevout = tx.vin[i].prevout;
1868 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1872 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1874 pvChecks->push_back(CScriptCheck());
1875 check.swap(pvChecks->back());
1876 } else if (!check()) {
1877 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1878 // Check whether the failure was caused by a
1879 // non-mandatory script verification check, such as
1880 // non-standard DER encodings or non-null dummy
1881 // arguments; if so, don't trigger DoS protection to
1882 // avoid splitting the network between upgraded and
1883 // non-upgraded nodes.
1884 CScriptCheck check(*coins, tx, i,
1885 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1887 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1889 // Failures of other flags indicate a transaction that is
1890 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1891 // such nodes as they are not following the protocol. That
1892 // said during an upgrade careful thought should be taken
1893 // as to the correct behavior - we may want to continue
1894 // peering with non-upgraded nodes even after a soft-fork
1895 // super-majority vote has passed.
1896 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1906 /*bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1908 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1909 fprintf(stderr,"ContextualCheckInputs failure.0\n");
1913 if (!tx.IsCoinBase())
1915 // While checking, GetBestBlock() refers to the parent block.
1916 // This is also true for mempool checks.
1917 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1918 int nSpendHeight = pindexPrev->nHeight + 1;
1919 for (unsigned int i = 0; i < tx.vin.size(); i++)
1921 const COutPoint &prevout = tx.vin[i].prevout;
1922 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1923 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1927 // If prev is coinbase, check that it's matured
1928 if (coins->IsCoinBase()) {
1929 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1930 COINBASE_MATURITY = _COINBASE_MATURITY;
1931 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1932 fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size());
1934 return state.Invalid(
1935 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1946 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1948 // Open history file to append
1949 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1950 if (fileout.IsNull())
1951 return error("%s: OpenUndoFile failed", __func__);
1953 // Write index header
1954 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1955 fileout << FLATDATA(messageStart) << nSize;
1958 long fileOutPos = ftell(fileout.Get());
1960 return error("%s: ftell failed", __func__);
1961 pos.nPos = (unsigned int)fileOutPos;
1962 fileout << blockundo;
1964 // calculate & write checksum
1965 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1966 hasher << hashBlock;
1967 hasher << blockundo;
1968 fileout << hasher.GetHash();
1973 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1975 // Open history file to read
1976 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1977 if (filein.IsNull())
1978 return error("%s: OpenBlockFile failed", __func__);
1981 uint256 hashChecksum;
1983 filein >> blockundo;
1984 filein >> hashChecksum;
1986 catch (const std::exception& e) {
1987 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1991 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1992 hasher << hashBlock;
1993 hasher << blockundo;
1994 if (hashChecksum != hasher.GetHash())
1995 return error("%s: Checksum mismatch", __func__);
2000 /** Abort with a message */
2001 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2003 strMiscWarning = strMessage;
2004 LogPrintf("*** %s\n", strMessage);
2005 uiInterface.ThreadSafeMessageBox(
2006 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2007 "", CClientUIInterface::MSG_ERROR);
2012 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2014 AbortNode(strMessage, userMessage);
2015 return state.Error(strMessage);
2021 * Apply the undo operation of a CTxInUndo to the given chain state.
2022 * @param undo The undo object.
2023 * @param view The coins view to which to apply the changes.
2024 * @param out The out point that corresponds to the tx input.
2025 * @return True on success.
2027 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2031 CCoinsModifier coins = view.ModifyCoins(out.hash);
2032 if (undo.nHeight != 0) {
2033 // undo data contains height: this is the last output of the prevout tx being spent
2034 if (!coins->IsPruned())
2035 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2037 coins->fCoinBase = undo.fCoinBase;
2038 coins->nHeight = undo.nHeight;
2039 coins->nVersion = undo.nVersion;
2041 if (coins->IsPruned())
2042 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2044 if (coins->IsAvailable(out.n))
2045 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2046 if (coins->vout.size() < out.n+1)
2047 coins->vout.resize(out.n+1);
2048 coins->vout[out.n] = undo.txout;
2053 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2055 assert(pindex->GetBlockHash() == view.GetBestBlock());
2061 komodo_disconnect(pindex,block);
2062 CBlockUndo blockUndo;
2063 CDiskBlockPos pos = pindex->GetUndoPos();
2065 return error("DisconnectBlock(): no undo data available");
2066 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2067 return error("DisconnectBlock(): failure reading undo data");
2069 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2070 return error("DisconnectBlock(): block and undo data inconsistent");
2072 // undo transactions in reverse order
2073 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2074 const CTransaction &tx = block.vtx[i];
2075 uint256 hash = tx.GetHash();
2077 // Check that all outputs are available and match the outputs in the block itself
2080 CCoinsModifier outs = view.ModifyCoins(hash);
2081 outs->ClearUnspendable();
2083 CCoins outsBlock(tx, pindex->nHeight);
2084 // The CCoins serialization does not serialize negative numbers.
2085 // No network rules currently depend on the version here, so an inconsistency is harmless
2086 // but it must be corrected before txout nversion ever influences a network rule.
2087 if (outsBlock.nVersion < 0)
2088 outs->nVersion = outsBlock.nVersion;
2089 if (*outs != outsBlock)
2090 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2096 // unspend nullifiers
2097 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2098 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2099 view.SetNullifier(nf, false);
2104 if (i > 0) { // not coinbases
2105 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2106 if (txundo.vprevout.size() != tx.vin.size())
2107 return error("DisconnectBlock(): transaction and undo data inconsistent");
2108 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2109 const COutPoint &out = tx.vin[j].prevout;
2110 const CTxInUndo &undo = txundo.vprevout[j];
2111 if (!ApplyTxInUndo(undo, view, out))
2117 // set the old best anchor back
2118 view.PopAnchor(blockUndo.old_tree_root);
2120 // move best block pointer to prevout block
2121 view.SetBestBlock(pindex->pprev->GetBlockHash());
2131 void static FlushBlockFile(bool fFinalize = false)
2133 LOCK(cs_LastBlockFile);
2135 CDiskBlockPos posOld(nLastBlockFile, 0);
2137 FILE *fileOld = OpenBlockFile(posOld);
2140 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2141 FileCommit(fileOld);
2145 fileOld = OpenUndoFile(posOld);
2148 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2149 FileCommit(fileOld);
2154 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2156 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2158 void ThreadScriptCheck() {
2159 RenameThread("zcash-scriptch");
2160 scriptcheckqueue.Thread();
2164 // Called periodically asynchronously; alerts if it smells like
2165 // we're being fed a bad chain (blocks being generated much
2166 // too slowly or too quickly).
2168 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2169 int64_t nPowTargetSpacing)
2171 if (bestHeader == NULL || initialDownloadCheck()) return;
2173 static int64_t lastAlertTime = 0;
2174 int64_t now = GetAdjustedTime();
2175 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2177 const int SPAN_HOURS=4;
2178 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2179 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2181 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2183 std::string strWarning;
2184 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2187 const CBlockIndex* i = bestHeader;
2189 while (i->GetBlockTime() >= startTime) {
2192 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2195 // How likely is it to find that many by chance?
2196 double p = boost::math::pdf(poisson, nBlocks);
2198 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2199 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2201 // Aim for one false-positive about every fifty years of normal running:
2202 const int FIFTY_YEARS = 50*365*24*60*60;
2203 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2205 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2207 // Many fewer blocks than expected: alert!
2208 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2209 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2211 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2213 // Many more blocks than expected: alert!
2214 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2215 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2217 if (!strWarning.empty())
2219 strMiscWarning = strWarning;
2220 CAlert::Notify(strWarning, true);
2221 lastAlertTime = now;
2225 static int64_t nTimeVerify = 0;
2226 static int64_t nTimeConnect = 0;
2227 static int64_t nTimeIndex = 0;
2228 static int64_t nTimeCallbacks = 0;
2229 static int64_t nTimeTotal = 0;
2231 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2233 const CChainParams& chainparams = Params();
2234 //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight);
2235 AssertLockHeld(cs_main);
2237 // Check it again in case a previous version let a bad block in
2238 bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2241 bool fExpensiveChecks = true;
2242 if (fCheckpointsEnabled) {
2243 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2244 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2245 // This block is an ancestor of a checkpoint: disable script checks
2246 fExpensiveChecks = false;
2249 //>>>>>>> zcash/master
2250 auto verifier = libzcash::ProofVerifier::Strict();
2251 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2253 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2254 if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2257 // verify that the view's current state corresponds to the previous block
2258 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2259 assert(hashPrevBlock == view.GetBestBlock());
2261 // Special case for the genesis block, skipping connection of its transactions
2262 // (its coinbase is unspendable)
2263 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2265 view.SetBestBlock(pindex->GetBlockHash());
2266 // Before the genesis block, there was an empty tree
2267 ZCIncrementalMerkleTree tree;
2268 pindex->hashAnchor = tree.root();
2269 // The genesis block contained no JoinSplits
2270 pindex->hashAnchorEnd = pindex->hashAnchor;
2275 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2276 //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet"
2278 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2279 // unless those are already completely spent.
2280 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2281 const CCoins* coins = view.AccessCoins(tx.GetHash());
2282 if (coins && !coins->IsPruned())
2283 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2284 REJECT_INVALID, "bad-txns-BIP30");
2287 unsigned int flags = SCRIPT_VERIFY_P2SH;
2289 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2290 // when 75% of the network has upgraded:
2291 if (block.nVersion >= 3) {
2292 flags |= SCRIPT_VERIFY_DERSIG;
2295 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2296 // blocks, when 75% of the network has upgraded:
2297 if (block.nVersion >= 4) {
2298 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2301 CBlockUndo blockundo;
2303 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2305 int64_t nTimeStart = GetTimeMicros();
2308 int64_t interest,sum = 0;
2309 unsigned int nSigOps = 0;
2310 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2311 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2312 vPos.reserve(block.vtx.size());
2313 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2315 // Construct the incremental merkle tree at the current
2317 auto old_tree_root = view.GetBestAnchor();
2318 // saving the top anchor in the block index as we go.
2320 pindex->hashAnchor = old_tree_root;
2322 ZCIncrementalMerkleTree tree;
2323 // This should never fail: we should always be able to get the root
2324 // that is on the tip of our chain
2325 assert(view.GetAnchorAt(old_tree_root, tree));
2328 // Consistency check: the root of the tree we're given should
2329 // match what we asked for.
2330 assert(tree.root() == old_tree_root);
2333 for (unsigned int i = 0; i < block.vtx.size(); i++)
2335 const CTransaction &tx = block.vtx[i];
2336 nInputs += tx.vin.size();
2337 nSigOps += GetLegacySigOpCount(tx);
2338 if (nSigOps > MAX_BLOCK_SIGOPS)
2339 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2340 REJECT_INVALID, "bad-blk-sigops");
2341 //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
2342 if (!tx.IsCoinBase())
2344 if (!view.HaveInputs(tx))
2345 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2346 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2348 // are the JoinSplit's requirements met?
2349 if (!view.HaveJoinSplitRequirements(tx))
2350 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2351 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2353 // Add in sigops done by pay-to-script-hash inputs;
2354 // this is to prevent a "rogue miner" from creating
2355 // an incredibly-expensive-to-validate block.
2356 nSigOps += GetP2SHSigOpCount(tx, view);
2357 if (nSigOps > MAX_BLOCK_SIGOPS)
2358 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2359 REJECT_INVALID, "bad-blk-sigops");
2361 nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
2363 std::vector<CScriptCheck> vChecks;
2364 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2366 control.Add(vChecks);
2368 if ( ASSETCHAINS_SYMBOL[0] == 0 )
2369 komodo_earned_interest(pindex->nHeight,sum);
2372 blockundo.vtxundo.push_back(CTxUndo());
2374 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2376 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2377 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2378 // Insert the note commitments into our temporary tree.
2380 tree.append(note_commitment);
2384 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2385 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2388 view.PushAnchor(tree);
2390 pindex->hashAnchorEnd = tree.root();
2392 blockundo.old_tree_root = old_tree_root;
2394 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2395 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);
2397 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2398 if (block.vtx[0].vout[0].nValue > blockReward)
2399 //if (block.vtx[0].GetValueOut() > blockReward)
2400 return state.DoS(100,
2401 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2402 block.vtx[0].GetValueOut(), blockReward),
2403 REJECT_INVALID, "bad-cb-amount");
2405 if (!control.Wait())
2406 return state.DoS(100, false);
2407 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2408 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);
2413 // Write undo information to disk
2414 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2416 if (pindex->GetUndoPos().IsNull()) {
2418 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2419 return error("ConnectBlock(): FindUndoPos failed");
2420 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2421 return AbortNode(state, "Failed to write undo data");
2423 // update nUndoPos in block index
2424 pindex->nUndoPos = pos.nPos;
2425 pindex->nStatus |= BLOCK_HAVE_UNDO;
2428 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2429 setDirtyBlockIndex.insert(pindex);
2433 if (!pblocktree->WriteTxIndex(vPos))
2434 return AbortNode(state, "Failed to write transaction index");
2436 // add this block to the view's block chain
2437 view.SetBestBlock(pindex->GetBlockHash());
2439 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2440 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2442 // Watch for changes to the previous coinbase transaction.
2443 static uint256 hashPrevBestCoinBase;
2444 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2445 hashPrevBestCoinBase = block.vtx[0].GetHash();
2447 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2448 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2450 //FlushStateToDisk();
2451 komodo_connectblock(pindex,*(CBlock *)&block);
2455 enum FlushStateMode {
2457 FLUSH_STATE_IF_NEEDED,
2458 FLUSH_STATE_PERIODIC,
2463 * Update the on-disk chain state.
2464 * The caches and indexes are flushed depending on the mode we're called with
2465 * if they're too large, if it's been a while since the last write,
2466 * or always and in all cases if we're in prune mode and are deleting files.
2468 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2469 LOCK2(cs_main, cs_LastBlockFile);
2470 static int64_t nLastWrite = 0;
2471 static int64_t nLastFlush = 0;
2472 static int64_t nLastSetChain = 0;
2473 std::set<int> setFilesToPrune;
2474 bool fFlushForPrune = false;
2476 if (fPruneMode && fCheckForPruning && !fReindex) {
2477 FindFilesToPrune(setFilesToPrune);
2478 fCheckForPruning = false;
2479 if (!setFilesToPrune.empty()) {
2480 fFlushForPrune = true;
2482 pblocktree->WriteFlag("prunedblockfiles", true);
2487 int64_t nNow = GetTimeMicros();
2488 // Avoid writing/flushing immediately after startup.
2489 if (nLastWrite == 0) {
2492 if (nLastFlush == 0) {
2495 if (nLastSetChain == 0) {
2496 nLastSetChain = nNow;
2498 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2499 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2500 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2501 // The cache is over the limit, we have to write now.
2502 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2503 // 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.
2504 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2505 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2506 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2507 // Combine all conditions that result in a full cache flush.
2508 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2509 // Write blocks and block index to disk.
2510 if (fDoFullFlush || fPeriodicWrite) {
2511 // Depend on nMinDiskSpace to ensure we can write block index
2512 if (!CheckDiskSpace(0))
2513 return state.Error("out of disk space");
2514 // First make sure all block and undo data is flushed to disk.
2516 // Then update all block file information (which may refer to block and undo files).
2518 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2519 vFiles.reserve(setDirtyFileInfo.size());
2520 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2521 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2522 setDirtyFileInfo.erase(it++);
2524 std::vector<const CBlockIndex*> vBlocks;
2525 vBlocks.reserve(setDirtyBlockIndex.size());
2526 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2527 vBlocks.push_back(*it);
2528 setDirtyBlockIndex.erase(it++);
2530 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2531 return AbortNode(state, "Files to write to block index database");
2534 // Finally remove any pruned files
2536 UnlinkPrunedFiles(setFilesToPrune);
2539 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2541 // Typical CCoins structures on disk are around 128 bytes in size.
2542 // Pushing a new one to the database can cause it to be written
2543 // twice (once in the log, and once in the tables). This is already
2544 // an overestimation, as most will delete an existing entry or
2545 // overwrite one. Still, use a conservative safety factor of 2.
2546 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2547 return state.Error("out of disk space");
2548 // Flush the chainstate (which may refer to block index entries).
2549 if (!pcoinsTip->Flush())
2550 return AbortNode(state, "Failed to write to coin database");
2553 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2554 // Update best block in wallet (so we can detect restored wallets).
2555 GetMainSignals().SetBestChain(chainActive.GetLocator());
2556 nLastSetChain = nNow;
2558 } catch (const std::runtime_error& e) {
2559 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2564 void FlushStateToDisk() {
2565 CValidationState state;
2566 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2569 void PruneAndFlush() {
2570 CValidationState state;
2571 fCheckForPruning = true;
2572 FlushStateToDisk(state, FLUSH_STATE_NONE);
2575 /** Update chainActive and related internal data structures. */
2576 void static UpdateTip(CBlockIndex *pindexNew) {
2577 const CChainParams& chainParams = Params();
2578 chainActive.SetTip(pindexNew);
2581 nTimeBestReceived = GetTime();
2582 mempool.AddTransactionsUpdated(1);
2584 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2585 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2586 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2587 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2589 cvBlockChange.notify_all();
2591 // Check the version of the last 100 blocks to see if we need to upgrade:
2592 static bool fWarned = false;
2593 if (!IsInitialBlockDownload() && !fWarned)
2596 const CBlockIndex* pindex = chainActive.Tip();
2597 for (int i = 0; i < 100 && pindex != NULL; i++)
2599 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2601 pindex = pindex->pprev;
2604 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2605 if (nUpgraded > 100/2)
2607 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2608 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2609 CAlert::Notify(strMiscWarning, true);
2615 /** Disconnect chainActive's tip. */
2616 bool static DisconnectTip(CValidationState &state) {
2617 CBlockIndex *pindexDelete = chainActive.Tip();
2618 assert(pindexDelete);
2619 mempool.check(pcoinsTip);
2620 // Read block from disk.
2622 if (!ReadBlockFromDisk(block, pindexDelete))
2623 return AbortNode(state, "Failed to read block");
2624 // Apply the block atomically to the chain state.
2625 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2626 int64_t nStart = GetTimeMicros();
2628 CCoinsViewCache view(pcoinsTip);
2629 if (!DisconnectBlock(block, state, pindexDelete, view))
2630 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2631 assert(view.Flush());
2633 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2634 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2635 // Write the chain state to disk, if necessary.
2636 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2638 // Resurrect mempool transactions from the disconnected block.
2639 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2640 // ignore validation errors in resurrected transactions
2641 list<CTransaction> removed;
2642 CValidationState stateDummy;
2643 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2644 mempool.remove(tx, removed, true);
2646 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2647 // The anchor may not change between block disconnects,
2648 // in which case we don't want to evict from the mempool yet!
2649 mempool.removeWithAnchor(anchorBeforeDisconnect);
2651 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2652 mempool.check(pcoinsTip);
2653 // Update chainActive and related variables.
2654 UpdateTip(pindexDelete->pprev);
2655 // Get the current commitment tree
2656 ZCIncrementalMerkleTree newTree;
2657 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2658 // Let wallets know transactions went from 1-confirmed to
2659 // 0-confirmed or conflicted:
2660 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2661 SyncWithWallets(tx, NULL);
2663 // Update cached incremental witnesses
2664 //fprintf(stderr,"chaintip false\n");
2665 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2669 static int64_t nTimeReadFromDisk = 0;
2670 static int64_t nTimeConnectTotal = 0;
2671 static int64_t nTimeFlush = 0;
2672 static int64_t nTimeChainState = 0;
2673 static int64_t nTimePostConnect = 0;
2676 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2677 * corresponding to pindexNew, to bypass loading it again from disk.
2679 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2681 assert(pindexNew->pprev == chainActive.Tip());
2682 mempool.check(pcoinsTip);
2683 // Read block from disk.
2684 int64_t nTime1 = GetTimeMicros();
2687 if (!ReadBlockFromDisk(block, pindexNew))
2688 return AbortNode(state, "Failed to read block");
2691 // Get the current commitment tree
2692 ZCIncrementalMerkleTree oldTree;
2693 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2694 // Apply the block atomically to the chain state.
2695 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2697 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2699 CCoinsViewCache view(pcoinsTip);
2700 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2701 GetMainSignals().BlockChecked(*pblock, state);
2703 if (state.IsInvalid())
2704 InvalidBlockFound(pindexNew, state);
2705 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2707 mapBlockSource.erase(pindexNew->GetBlockHash());
2708 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2709 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2710 assert(view.Flush());
2712 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2713 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2714 // Write the chain state to disk, if necessary.
2715 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2717 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2718 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2719 // Remove conflicting transactions from the mempool.
2720 list<CTransaction> txConflicted;
2721 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2722 mempool.check(pcoinsTip);
2723 // Update chainActive & related variables.
2724 UpdateTip(pindexNew);
2725 // Tell wallet about transactions that went from mempool
2727 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2728 SyncWithWallets(tx, NULL);
2730 // ... and about transactions that got confirmed:
2731 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2732 SyncWithWallets(tx, pblock);
2734 // Update cached incremental witnesses
2735 //fprintf(stderr,"chaintip true\n");
2736 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2738 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2739 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2740 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2745 * Return the tip of the chain with the most work in it, that isn't
2746 * known to be invalid (it's however far from certain to be valid).
2748 static CBlockIndex* FindMostWorkChain() {
2750 CBlockIndex *pindexNew = NULL;
2752 // Find the best candidate header.
2754 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2755 if (it == setBlockIndexCandidates.rend())
2760 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2761 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2762 CBlockIndex *pindexTest = pindexNew;
2763 bool fInvalidAncestor = false;
2764 while (pindexTest && !chainActive.Contains(pindexTest)) {
2765 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2767 // Pruned nodes may have entries in setBlockIndexCandidates for
2768 // which block files have been deleted. Remove those as candidates
2769 // for the most work chain if we come across them; we can't switch
2770 // to a chain unless we have all the non-active-chain parent blocks.
2771 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2772 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2773 if (fFailedChain || fMissingData) {
2774 // Candidate chain is not usable (either invalid or missing data)
2775 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2776 pindexBestInvalid = pindexNew;
2777 CBlockIndex *pindexFailed = pindexNew;
2778 // Remove the entire chain from the set.
2779 while (pindexTest != pindexFailed) {
2781 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2782 } else if (fMissingData) {
2783 // If we're missing data, then add back to mapBlocksUnlinked,
2784 // so that if the block arrives in the future we can try adding
2785 // to setBlockIndexCandidates again.
2786 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2788 setBlockIndexCandidates.erase(pindexFailed);
2789 pindexFailed = pindexFailed->pprev;
2791 setBlockIndexCandidates.erase(pindexTest);
2792 fInvalidAncestor = true;
2795 pindexTest = pindexTest->pprev;
2797 if (!fInvalidAncestor)
2802 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2803 static void PruneBlockIndexCandidates() {
2804 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2805 // reorganization to a better block fails.
2806 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2807 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2808 setBlockIndexCandidates.erase(it++);
2810 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2811 assert(!setBlockIndexCandidates.empty());
2815 * Try to make some progress towards making pindexMostWork the active block.
2816 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2818 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2819 AssertLockHeld(cs_main);
2820 bool fInvalidFound = false;
2821 const CBlockIndex *pindexOldTip = chainActive.Tip();
2822 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2824 // Disconnect active blocks which are no longer in the best chain.
2825 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2826 if (!DisconnectTip(state))
2829 if ( KOMODO_REWIND != 0 )
2831 fprintf(stderr,"rewind start ht.%d\n",chainActive.Tip()->nHeight);
2832 while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND )
2834 if ( !DisconnectTip(state) )
2836 InvalidateBlock(state,chainActive.Tip());
2840 fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli stop\n",KOMODO_REWIND);
2845 // Build list of new blocks to connect.
2846 std::vector<CBlockIndex*> vpindexToConnect;
2847 bool fContinue = true;
2848 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2849 while (fContinue && nHeight != pindexMostWork->nHeight) {
2850 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2851 // a few blocks along the way.
2852 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2853 vpindexToConnect.clear();
2854 vpindexToConnect.reserve(nTargetHeight - nHeight);
2855 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2856 while (pindexIter && pindexIter->nHeight != nHeight) {
2857 vpindexToConnect.push_back(pindexIter);
2858 pindexIter = pindexIter->pprev;
2860 nHeight = nTargetHeight;
2862 // Connect new blocks.
2863 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2864 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2865 if (state.IsInvalid()) {
2866 // The block violates a consensus rule.
2867 if (!state.CorruptionPossible())
2868 InvalidChainFound(vpindexToConnect.back());
2869 state = CValidationState();
2870 fInvalidFound = true;
2874 // A system error occurred (disk space, database error, ...).
2878 PruneBlockIndexCandidates();
2879 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2880 // We're in a better position than we were. Return temporarily to release the lock.
2888 // Callbacks/notifications for a new best chain.
2890 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2892 CheckForkWarningConditions();
2898 * Make the best chain active, in multiple steps. The result is either failure
2899 * or an activated best chain. pblock is either NULL or a pointer to a block
2900 * that is already loaded (to avoid loading it again from disk).
2902 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2903 CBlockIndex *pindexNewTip = NULL;
2904 CBlockIndex *pindexMostWork = NULL;
2905 const CChainParams& chainParams = Params();
2907 boost::this_thread::interruption_point();
2909 bool fInitialDownload;
2912 pindexMostWork = FindMostWorkChain();
2914 // Whether we have anything to do at all.
2915 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2918 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2920 pindexNewTip = chainActive.Tip();
2921 fInitialDownload = IsInitialBlockDownload();
2923 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2925 // Notifications/callbacks that can run without cs_main
2926 if (!fInitialDownload) {
2927 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2928 // Relay inventory, but don't relay old inventory during initial block download.
2929 int nBlockEstimate = 0;
2930 if (fCheckpointsEnabled)
2931 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2932 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2933 // in a stalled download if the block file is pruned before the request.
2934 if (nLocalServices & NODE_NETWORK) {
2936 BOOST_FOREACH(CNode* pnode, vNodes)
2937 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2938 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2940 // Notify external listeners about the new tip.
2941 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2942 uiInterface.NotifyBlockTip(hashNewTip);
2943 } //else fprintf(stderr,"initial download skips propagation\n");
2944 } while(pindexMostWork != chainActive.Tip());
2947 // Write changes periodically to disk, after relay.
2948 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2955 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2956 AssertLockHeld(cs_main);
2958 // Mark the block itself as invalid.
2959 pindex->nStatus |= BLOCK_FAILED_VALID;
2960 setDirtyBlockIndex.insert(pindex);
2961 setBlockIndexCandidates.erase(pindex);
2963 while (chainActive.Contains(pindex)) {
2964 CBlockIndex *pindexWalk = chainActive.Tip();
2965 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2966 setDirtyBlockIndex.insert(pindexWalk);
2967 setBlockIndexCandidates.erase(pindexWalk);
2968 // ActivateBestChain considers blocks already in chainActive
2969 // unconditionally valid already, so force disconnect away from it.
2970 if (!DisconnectTip(state)) {
2974 //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2976 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2978 BlockMap::iterator it = mapBlockIndex.begin();
2979 while (it != mapBlockIndex.end() && it->second != 0 ) {
2980 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2981 setBlockIndexCandidates.insert(it->second);
2986 InvalidChainFound(pindex);
2990 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2991 AssertLockHeld(cs_main);
2993 int nHeight = pindex->nHeight;
2995 // Remove the invalidity flag from this block and all its descendants.
2996 BlockMap::iterator it = mapBlockIndex.begin();
2997 while (it != mapBlockIndex.end()) {
2998 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2999 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3000 setDirtyBlockIndex.insert(it->second);
3001 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3002 setBlockIndexCandidates.insert(it->second);
3004 if (it->second == pindexBestInvalid) {
3005 // Reset invalid block marker if it was pointing to one of those.
3006 pindexBestInvalid = NULL;
3012 // Remove the invalidity flag from all ancestors too.
3013 while (pindex != NULL) {
3014 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3015 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3016 setDirtyBlockIndex.insert(pindex);
3018 pindex = pindex->pprev;
3023 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3025 // Check for duplicate
3026 uint256 hash = block.GetHash();
3027 BlockMap::iterator it = mapBlockIndex.find(hash);
3028 if (it != mapBlockIndex.end())
3031 // Construct new block index object
3032 CBlockIndex* pindexNew = new CBlockIndex(block);
3034 // We assign the sequence id to blocks only when the full data is available,
3035 // to avoid miners withholding blocks but broadcasting headers, to get a
3036 // competitive advantage.
3037 pindexNew->nSequenceId = 0;
3038 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3039 pindexNew->phashBlock = &((*mi).first);
3040 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3041 if (miPrev != mapBlockIndex.end())
3043 pindexNew->pprev = (*miPrev).second;
3044 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3045 pindexNew->BuildSkip();
3047 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3048 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3049 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3050 pindexBestHeader = pindexNew;
3052 setDirtyBlockIndex.insert(pindexNew);
3057 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3058 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3060 pindexNew->nTx = block.vtx.size();
3061 pindexNew->nChainTx = 0;
3062 pindexNew->nFile = pos.nFile;
3063 pindexNew->nDataPos = pos.nPos;
3064 pindexNew->nUndoPos = 0;
3065 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3066 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3067 setDirtyBlockIndex.insert(pindexNew);
3069 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3070 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3071 deque<CBlockIndex*> queue;
3072 queue.push_back(pindexNew);
3074 // Recursively process any descendant blocks that now may be eligible to be connected.
3075 while (!queue.empty()) {
3076 CBlockIndex *pindex = queue.front();
3078 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3080 LOCK(cs_nBlockSequenceId);
3081 pindex->nSequenceId = nBlockSequenceId++;
3083 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3084 setBlockIndexCandidates.insert(pindex);
3086 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3087 while (range.first != range.second) {
3088 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3089 queue.push_back(it->second);
3091 mapBlocksUnlinked.erase(it);
3095 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3096 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3103 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3105 LOCK(cs_LastBlockFile);
3107 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3108 if (vinfoBlockFile.size() <= nFile) {
3109 vinfoBlockFile.resize(nFile + 1);
3113 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3115 if (vinfoBlockFile.size() <= nFile) {
3116 vinfoBlockFile.resize(nFile + 1);
3120 pos.nPos = vinfoBlockFile[nFile].nSize;
3123 if (nFile != nLastBlockFile) {
3125 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3127 FlushBlockFile(!fKnown);
3128 nLastBlockFile = nFile;
3131 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3133 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3135 vinfoBlockFile[nFile].nSize += nAddSize;
3138 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3139 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3140 if (nNewChunks > nOldChunks) {
3142 fCheckForPruning = true;
3143 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3144 FILE *file = OpenBlockFile(pos);
3146 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3147 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3152 return state.Error("out of disk space");
3156 setDirtyFileInfo.insert(nFile);
3160 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3164 LOCK(cs_LastBlockFile);
3166 unsigned int nNewSize;
3167 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3168 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3169 setDirtyFileInfo.insert(nFile);
3171 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3172 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3173 if (nNewChunks > nOldChunks) {
3175 fCheckForPruning = true;
3176 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3177 FILE *file = OpenUndoFile(pos);
3179 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3180 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3185 return state.Error("out of disk space");
3191 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3193 uint8_t pubkey33[33];
3197 uint256 hash; int32_t i;
3198 hash = blockhdr.GetHash();
3199 for (i=31; i>=0; i--)
3200 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3201 fprintf(stderr," <- CheckBlockHeader\n");
3202 if ( chainActive.Tip() != 0 )
3204 hash = chainActive.Tip()->GetBlockHash();
3205 for (i=31; i>=0; i--)
3206 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3207 fprintf(stderr," <- chainTip\n");
3210 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3211 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3212 // Check block version
3213 //if (block.nVersion < MIN_BLOCK_VERSION)
3214 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3216 // Check Equihash solution is valid
3217 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3218 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3220 // Check proof of work matches claimed amount
3221 komodo_index2pubkey33(pubkey33,pindex,height);
3222 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3223 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3227 int32_t komodo_check_deposit(int32_t height,const CBlock& block);
3228 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
3229 libzcash::ProofVerifier& verifier,
3230 bool fCheckPOW, bool fCheckMerkleRoot)
3232 // These are checks that are independent of context.
3234 // Check that the header is valid (particularly PoW). This is mostly
3235 // redundant with the call in AcceptBlockHeader.
3236 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3239 // Check the merkle root.
3240 if (fCheckMerkleRoot) {
3242 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3243 if (block.hashMerkleRoot != hashMerkleRoot2)
3244 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3245 REJECT_INVALID, "bad-txnmrklroot", true);
3247 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3248 // of transactions in a block without affecting the merkle root of a block,
3249 // while still invalidating it.
3251 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3252 REJECT_INVALID, "bad-txns-duplicate", true);
3255 // All potential-corruption validation must be done before we do any
3256 // transaction validation, as otherwise we may mark the header as invalid
3257 // because we receive the wrong transactions for it.
3260 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3261 return state.DoS(100, error("CheckBlock(): size limits failed"),
3262 REJECT_INVALID, "bad-blk-length");
3264 // First transaction must be coinbase, the rest must not be
3265 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3266 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3267 REJECT_INVALID, "bad-cb-missing");
3268 for (unsigned int i = 1; i < block.vtx.size(); i++)
3269 if (block.vtx[i].IsCoinBase())
3270 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3271 REJECT_INVALID, "bad-cb-multiple");
3273 // Check transactions
3274 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3276 if ( komodo_validate_interest(tx,komodo_block2height((CBlock *)&block),block.nTime,1) < 0 )
3277 return error("CheckBlock: komodo_validate_interest failed");
3278 if (!CheckTransaction(tx, state, verifier))
3279 return error("CheckBlock(): CheckTransaction failed");
3281 unsigned int nSigOps = 0;
3282 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3284 nSigOps += GetLegacySigOpCount(tx);
3286 if (nSigOps > MAX_BLOCK_SIGOPS)
3287 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3288 REJECT_INVALID, "bad-blk-sigops", true);
3289 if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block) < 0 )
3291 static uint32_t counter;
3292 if ( counter++ < 100 )
3293 fprintf(stderr,"check deposit rejection\n");
3299 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3301 const CChainParams& chainParams = Params();
3302 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3303 uint256 hash = block.GetHash();
3304 if (hash == consensusParams.hashGenesisBlock)
3309 int nHeight = pindexPrev->nHeight+1;
3311 // Check proof of work
3312 if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3314 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3315 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3316 REJECT_INVALID, "bad-diffbits");
3319 // Check timestamp against prev
3320 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3321 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3322 REJECT_INVALID, "time-too-old");
3324 if (fCheckpointsEnabled)
3326 // Check that the block chain matches the known block chain up to a checkpoint
3327 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3328 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3330 // Don't accept any forks from the main chain prior to last checkpoint
3331 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3332 int32_t notarized_height;
3333 if (pcheckpoint && (nHeight < pcheckpoint->nHeight || nHeight == 1 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight > 1) )
3334 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3335 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3336 return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3338 // Reject block.nVersion < 4 blocks
3339 if (block.nVersion < 4)
3340 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3341 REJECT_OBSOLETE, "bad-version");
3346 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3348 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3349 const Consensus::Params& consensusParams = Params().GetConsensus();
3351 // Check that all transactions are finalized
3352 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3353 int nLockTimeFlags = 0;
3354 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3355 ? pindexPrev->GetMedianTimePast()
3356 : block.GetBlockTime();
3357 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3358 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3362 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3363 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3364 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3365 // This rule is not applied to the genesis block, which didn't include the height
3369 CScript expect = CScript() << nHeight;
3370 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3371 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3372 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3379 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3381 const CChainParams& chainparams = Params();
3382 AssertLockHeld(cs_main);
3383 // Check for duplicate
3384 uint256 hash = block.GetHash();
3385 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3386 CBlockIndex *pindex = NULL;
3387 if (miSelf != mapBlockIndex.end()) {
3388 // Block header is already known.
3389 pindex = miSelf->second;
3392 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3393 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3397 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3400 // Get prev block index
3401 CBlockIndex* pindexPrev = NULL;
3402 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3403 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3404 if (mi == mapBlockIndex.end())
3405 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3406 pindexPrev = (*mi).second;
3407 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3408 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3410 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3413 pindex = AddToBlockIndex(block);
3419 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3421 const CChainParams& chainparams = Params();
3422 AssertLockHeld(cs_main);
3424 CBlockIndex *&pindex = *ppindex;
3425 if (!AcceptBlockHeader(block, state, &pindex))
3429 fprintf(stderr,"AcceptBlock error null pindex\n");
3432 // Try to process all requested blocks that we don't have, but only
3433 // process an unrequested block if it's new and has enough work to
3434 // advance our tip, and isn't too many blocks ahead.
3435 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3436 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3437 // Blocks that are too out-of-order needlessly limit the effectiveness of
3438 // pruning, because pruning will not delete block files that contain any
3439 // blocks which are too close in height to the tip. Apply this test
3440 // regardless of whether pruning is enabled; it should generally be safe to
3441 // not process unrequested blocks.
3442 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3444 // TODO: deal better with return value and error conditions for duplicate
3445 // and unrequested blocks.
3446 if (fAlreadyHave) return true;
3447 if (!fRequested) { // If we didn't ask for it:
3448 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3449 if (!fHasMoreWork) return true; // Don't process less-work chains
3450 if (fTooFarAhead) return true; // Block height is too high
3453 // See method docstring for why this is always disabled
3454 auto verifier = libzcash::ProofVerifier::Disabled();
3455 if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3456 if (state.IsInvalid() && !state.CorruptionPossible()) {
3457 pindex->nStatus |= BLOCK_FAILED_VALID;
3458 setDirtyBlockIndex.insert(pindex);
3463 int nHeight = pindex->nHeight;
3465 // Write block to history file
3467 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3468 CDiskBlockPos blockPos;
3471 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3472 return error("AcceptBlock(): FindBlockPos failed");
3474 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3475 AbortNode(state, "Failed to write block");
3476 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3477 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3478 } catch (const std::runtime_error& e) {
3479 return AbortNode(state, std::string("System error: ") + e.what());
3482 if (fCheckForPruning)
3483 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3488 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3490 unsigned int nFound = 0;
3491 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3493 if (pstart->nVersion >= minVersion)
3495 pstart = pstart->pprev;
3497 return (nFound >= nRequired);
3500 void komodo_currentheight_set(int32_t height);
3502 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3504 // Preliminary checks
3506 auto verifier = libzcash::ProofVerifier::Disabled();
3507 if ( chainActive.Tip() != 0 )
3508 komodo_currentheight_set(chainActive.Tip()->nHeight);
3509 if ( ASSETCHAINS_SYMBOL[0] == 0 )
3510 checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3511 else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3514 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3515 fRequested |= fForceProcessing;
3518 Misbehaving(pfrom->GetId(), 1);
3519 return error("%s: CheckBlock FAILED", __func__);
3523 CBlockIndex *pindex = NULL;
3524 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3525 if (pindex && pfrom) {
3526 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3530 return error("%s: AcceptBlock FAILED", __func__);
3533 if (!ActivateBestChain(state, pblock))
3534 return error("%s: ActivateBestChain failed", __func__);
3539 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3541 AssertLockHeld(cs_main);
3542 assert(pindexPrev == chainActive.Tip());
3544 CCoinsViewCache viewNew(pcoinsTip);
3545 CBlockIndex indexDummy(block);
3546 indexDummy.pprev = pindexPrev;
3547 indexDummy.nHeight = pindexPrev->nHeight + 1;
3548 // JoinSplit proofs are verified in ConnectBlock
3549 auto verifier = libzcash::ProofVerifier::Disabled();
3551 // NOTE: CheckBlockHeader is called by CheckBlock
3552 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3554 fprintf(stderr,"TestBlockValidity failure A\n");
3557 if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3559 //fprintf(stderr,"TestBlockValidity failure B\n");
3562 if (!ContextualCheckBlock(block, state, pindexPrev))
3564 fprintf(stderr,"TestBlockValidity failure C\n");
3567 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3569 fprintf(stderr,"TestBlockValidity failure D\n");
3572 assert(state.IsValid());
3578 * BLOCK PRUNING CODE
3581 /* Calculate the amount of disk space the block & undo files currently use */
3582 uint64_t CalculateCurrentUsage()
3584 uint64_t retval = 0;
3585 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3586 retval += file.nSize + file.nUndoSize;
3591 /* Prune a block file (modify associated database entries)*/
3592 void PruneOneBlockFile(const int fileNumber)
3594 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3595 CBlockIndex* pindex = it->second;
3596 if (pindex->nFile == fileNumber) {
3597 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3598 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3600 pindex->nDataPos = 0;
3601 pindex->nUndoPos = 0;
3602 setDirtyBlockIndex.insert(pindex);
3604 // Prune from mapBlocksUnlinked -- any block we prune would have
3605 // to be downloaded again in order to consider its chain, at which
3606 // point it would be considered as a candidate for
3607 // mapBlocksUnlinked or setBlockIndexCandidates.
3608 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3609 while (range.first != range.second) {
3610 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3612 if (it->second == pindex) {
3613 mapBlocksUnlinked.erase(it);
3619 vinfoBlockFile[fileNumber].SetNull();
3620 setDirtyFileInfo.insert(fileNumber);
3624 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3626 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3627 CDiskBlockPos pos(*it, 0);
3628 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3629 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3630 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3634 /* Calculate the block/rev files that should be deleted to remain under target*/
3635 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3637 LOCK2(cs_main, cs_LastBlockFile);
3638 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3641 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3645 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3646 uint64_t nCurrentUsage = CalculateCurrentUsage();
3647 // We don't check to prune until after we've allocated new space for files
3648 // So we should leave a buffer under our target to account for another allocation
3649 // before the next pruning.
3650 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3651 uint64_t nBytesToPrune;
3654 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3655 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3656 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3658 if (vinfoBlockFile[fileNumber].nSize == 0)
3661 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3664 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3665 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3668 PruneOneBlockFile(fileNumber);
3669 // Queue up the files for removal
3670 setFilesToPrune.insert(fileNumber);
3671 nCurrentUsage -= nBytesToPrune;
3676 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3677 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3678 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3679 nLastBlockWeCanPrune, count);
3682 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3684 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3686 // Check for nMinDiskSpace bytes (currently 50MB)
3687 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3688 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3693 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3697 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3698 boost::filesystem::create_directories(path.parent_path());
3699 FILE* file = fopen(path.string().c_str(), "rb+");
3700 if (!file && !fReadOnly)
3701 file = fopen(path.string().c_str(), "wb+");
3703 LogPrintf("Unable to open file %s\n", path.string());
3707 if (fseek(file, pos.nPos, SEEK_SET)) {
3708 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3716 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3717 return OpenDiskFile(pos, "blk", fReadOnly);
3720 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3721 return OpenDiskFile(pos, "rev", fReadOnly);
3724 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3726 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3729 CBlockIndex * InsertBlockIndex(uint256 hash)
3735 BlockMap::iterator mi = mapBlockIndex.find(hash);
3736 if (mi != mapBlockIndex.end())
3737 return (*mi).second;
3740 CBlockIndex* pindexNew = new CBlockIndex();
3742 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3743 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3744 pindexNew->phashBlock = &((*mi).first);
3749 bool static LoadBlockIndexDB()
3751 const CChainParams& chainparams = Params();
3752 if (!pblocktree->LoadBlockIndexGuts())
3755 boost::this_thread::interruption_point();
3757 // Calculate nChainWork
3758 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3759 vSortedByHeight.reserve(mapBlockIndex.size());
3760 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3762 CBlockIndex* pindex = item.second;
3763 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3765 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3766 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3768 CBlockIndex* pindex = item.second;
3769 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3770 // We can link the chain of blocks for which we've received transactions at some point.
3771 // Pruned nodes may have deleted the block.
3772 if (pindex->nTx > 0) {
3773 if (pindex->pprev) {
3774 if (pindex->pprev->nChainTx) {
3775 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3777 pindex->nChainTx = 0;
3778 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3781 pindex->nChainTx = pindex->nTx;
3784 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3785 setBlockIndexCandidates.insert(pindex);
3786 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3787 pindexBestInvalid = pindex;
3789 pindex->BuildSkip();
3790 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3791 pindexBestHeader = pindex;
3794 // Load block file info
3795 pblocktree->ReadLastBlockFile(nLastBlockFile);
3796 vinfoBlockFile.resize(nLastBlockFile + 1);
3797 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3798 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3799 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3801 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3802 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3803 CBlockFileInfo info;
3804 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3805 vinfoBlockFile.push_back(info);
3811 // Check presence of blk files
3812 LogPrintf("Checking all blk files are present...\n");
3813 set<int> setBlkDataFiles;
3814 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3816 CBlockIndex* pindex = item.second;
3817 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3818 setBlkDataFiles.insert(pindex->nFile);
3821 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3823 CDiskBlockPos pos(*it, 0);
3824 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3829 // Check whether we have ever pruned block & undo files
3830 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3832 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3834 // Check whether we need to continue reindexing
3835 bool fReindexing = false;
3836 pblocktree->ReadReindexing(fReindexing);
3837 fReindex |= fReindexing;
3839 // Check whether we have a transaction index
3840 pblocktree->ReadFlag("txindex", fTxIndex);
3841 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3843 // Fill in-memory data
3844 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3846 CBlockIndex* pindex = item.second;
3847 // - This relationship will always be true even if pprev has multiple
3848 // children, because hashAnchor is technically a property of pprev,
3849 // not its children.
3850 // - This will miss chain tips; we handle the best tip below, and other
3851 // tips will be handled by ConnectTip during a re-org.
3852 if (pindex->pprev) {
3853 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3857 // Load pointer to end of best chain
3858 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3859 if (it == mapBlockIndex.end())
3861 chainActive.SetTip(it->second);
3862 // Set hashAnchorEnd for the end of best chain
3863 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3865 PruneBlockIndexCandidates();
3867 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3868 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3869 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3870 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3875 CVerifyDB::CVerifyDB()
3877 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3880 CVerifyDB::~CVerifyDB()
3882 uiInterface.ShowProgress("", 100);
3885 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3888 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3891 // Verify blocks in the best chain
3892 if (nCheckDepth <= 0)
3893 nCheckDepth = 1000000000; // suffices until the year 19000
3894 if (nCheckDepth > chainActive.Height())
3895 nCheckDepth = chainActive.Height();
3896 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3897 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3898 CCoinsViewCache coins(coinsview);
3899 CBlockIndex* pindexState = chainActive.Tip();
3900 CBlockIndex* pindexFailure = NULL;
3901 int nGoodTransactions = 0;
3902 CValidationState state;
3903 // No need to verify JoinSplits twice
3904 auto verifier = libzcash::ProofVerifier::Disabled();
3905 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3907 boost::this_thread::interruption_point();
3908 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3909 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3912 // check level 0: read from disk
3913 if (!ReadBlockFromDisk(block, pindex))
3914 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3915 // check level 1: verify block validity
3916 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier))
3917 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3918 // check level 2: verify undo validity
3919 if (nCheckLevel >= 2 && pindex) {
3921 CDiskBlockPos pos = pindex->GetUndoPos();
3922 if (!pos.IsNull()) {
3923 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3924 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3927 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3928 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3930 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3931 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3932 pindexState = pindex->pprev;
3934 nGoodTransactions = 0;
3935 pindexFailure = pindex;
3937 nGoodTransactions += block.vtx.size();
3939 if (ShutdownRequested())
3943 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3945 // check level 4: try reconnecting blocks
3946 if (nCheckLevel >= 4) {
3947 CBlockIndex *pindex = pindexState;
3948 while (pindex != chainActive.Tip()) {
3949 boost::this_thread::interruption_point();
3950 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3951 pindex = chainActive.Next(pindex);
3953 if (!ReadBlockFromDisk(block, pindex))
3954 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3955 if (!ConnectBlock(block, state, pindex, coins))
3956 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3960 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3965 void UnloadBlockIndex()
3968 setBlockIndexCandidates.clear();
3969 chainActive.SetTip(NULL);
3970 pindexBestInvalid = NULL;
3971 pindexBestHeader = NULL;
3973 mapOrphanTransactions.clear();
3974 mapOrphanTransactionsByPrev.clear();
3976 mapBlocksUnlinked.clear();
3977 vinfoBlockFile.clear();
3979 nBlockSequenceId = 1;
3980 mapBlockSource.clear();
3981 mapBlocksInFlight.clear();
3982 nQueuedValidatedHeaders = 0;
3983 nPreferredDownload = 0;
3984 setDirtyBlockIndex.clear();
3985 setDirtyFileInfo.clear();
3986 mapNodeState.clear();
3987 recentRejects.reset(NULL);
3989 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3990 delete entry.second;
3992 mapBlockIndex.clear();
3993 fHavePruned = false;
3996 bool LoadBlockIndex()
3998 extern int32_t KOMODO_LOADINGBLOCKS;
3999 // Load block index from databases
4000 KOMODO_LOADINGBLOCKS = 1;
4001 if (!fReindex && !LoadBlockIndexDB())
4003 KOMODO_LOADINGBLOCKS = 0;
4006 KOMODO_LOADINGBLOCKS = 0;
4007 fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL);
4012 bool InitBlockIndex() {
4013 const CChainParams& chainparams = Params();
4016 // Initialize global variables that cannot be constructed at startup.
4017 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4019 // Check whether we're already initialized
4020 if (chainActive.Genesis() != NULL)
4023 // Use the provided setting for -txindex in the new database
4024 fTxIndex = GetBoolArg("-txindex", true);
4025 pblocktree->WriteFlag("txindex", fTxIndex);
4026 LogPrintf("Initializing databases...\n");
4028 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4031 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4032 // Start new block file
4033 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4034 CDiskBlockPos blockPos;
4035 CValidationState state;
4036 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4037 return error("LoadBlockIndex(): FindBlockPos failed");
4038 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4039 return error("LoadBlockIndex(): writing genesis block to disk failed");
4040 CBlockIndex *pindex = AddToBlockIndex(block);
4041 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4042 return error("LoadBlockIndex(): genesis block not accepted");
4043 if (!ActivateBestChain(state, &block))
4044 return error("LoadBlockIndex(): genesis block cannot be activated");
4045 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4046 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4047 } catch (const std::runtime_error& e) {
4048 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4057 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4059 const CChainParams& chainparams = Params();
4060 // Map of disk positions for blocks with unknown parent (only used for reindex)
4061 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4062 int64_t nStart = GetTimeMillis();
4066 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4067 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4068 uint64_t nRewind = blkdat.GetPos();
4069 while (!blkdat.eof()) {
4070 boost::this_thread::interruption_point();
4072 blkdat.SetPos(nRewind);
4073 nRewind++; // start one byte further next time, in case of failure
4074 blkdat.SetLimit(); // remove former limit
4075 unsigned int nSize = 0;
4078 unsigned char buf[MESSAGE_START_SIZE];
4079 blkdat.FindByte(Params().MessageStart()[0]);
4080 nRewind = blkdat.GetPos()+1;
4081 blkdat >> FLATDATA(buf);
4082 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4086 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4088 } catch (const std::exception&) {
4089 // no valid block header found; don't complain
4094 uint64_t nBlockPos = blkdat.GetPos();
4096 dbp->nPos = nBlockPos;
4097 blkdat.SetLimit(nBlockPos + nSize);
4098 blkdat.SetPos(nBlockPos);
4101 nRewind = blkdat.GetPos();
4103 // detect out of order blocks, and store them for later
4104 uint256 hash = block.GetHash();
4105 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4106 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4107 block.hashPrevBlock.ToString());
4109 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4113 // process in case the block isn't known yet
4114 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4115 CValidationState state;
4116 if (ProcessNewBlock(0,state, NULL, &block, true, dbp))
4118 if (state.IsError())
4120 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4121 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4124 // Recursively process earlier encountered successors of this block
4125 deque<uint256> queue;
4126 queue.push_back(hash);
4127 while (!queue.empty()) {
4128 uint256 head = queue.front();
4130 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4131 while (range.first != range.second) {
4132 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4133 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
4135 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4137 CValidationState dummy;
4138 if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second))
4141 queue.push_back(block.GetHash());
4145 mapBlocksUnknownParent.erase(it);
4148 } catch (const std::exception& e) {
4149 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4152 } catch (const std::runtime_error& e) {
4153 AbortNode(std::string("System error: ") + e.what());
4156 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4160 void static CheckBlockIndex()
4162 const Consensus::Params& consensusParams = Params().GetConsensus();
4163 if (!fCheckBlockIndex) {
4169 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4170 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4171 // iterating the block tree require that chainActive has been initialized.)
4172 if (chainActive.Height() < 0) {
4173 assert(mapBlockIndex.size() <= 1);
4177 // Build forward-pointing map of the entire block tree.
4178 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4179 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4180 forward.insert(std::make_pair(it->second->pprev, it->second));
4183 assert(forward.size() == mapBlockIndex.size());
4185 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4186 CBlockIndex *pindex = rangeGenesis.first->second;
4187 rangeGenesis.first++;
4188 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4190 // Iterate over the entire block tree, using depth-first search.
4191 // Along the way, remember whether there are blocks on the path from genesis
4192 // block being explored which are the first to have certain properties.
4195 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4196 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4197 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4198 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4199 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4200 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4201 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4202 while (pindex != NULL) {
4204 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4205 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4206 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4207 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4208 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4209 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4210 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4212 // Begin: actual consistency checks.
4213 if (pindex->pprev == NULL) {
4214 // Genesis block checks.
4215 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4216 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4218 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4219 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4220 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4222 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4223 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4224 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4226 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4227 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4229 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4230 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4231 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4232 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4233 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4234 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4235 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.
4236 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4237 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4238 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4239 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4240 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4241 if (pindexFirstInvalid == NULL) {
4242 // Checks for not-invalid blocks.
4243 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4245 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4246 if (pindexFirstInvalid == NULL) {
4247 // If this block sorts at least as good as the current tip and
4248 // is valid and we have all data for its parents, it must be in
4249 // setBlockIndexCandidates. chainActive.Tip() must also be there
4250 // even if some data has been pruned.
4251 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4252 assert(setBlockIndexCandidates.count(pindex));
4254 // If some parent is missing, then it could be that this block was in
4255 // setBlockIndexCandidates but had to be removed because of the missing data.
4256 // In this case it must be in mapBlocksUnlinked -- see test below.
4258 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4259 assert(setBlockIndexCandidates.count(pindex) == 0);
4261 // Check whether this block is in mapBlocksUnlinked.
4262 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4263 bool foundInUnlinked = false;
4264 while (rangeUnlinked.first != rangeUnlinked.second) {
4265 assert(rangeUnlinked.first->first == pindex->pprev);
4266 if (rangeUnlinked.first->second == pindex) {
4267 foundInUnlinked = true;
4270 rangeUnlinked.first++;
4272 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4273 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4274 assert(foundInUnlinked);
4276 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4277 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4278 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4279 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4280 assert(fHavePruned); // We must have pruned.
4281 // This block may have entered mapBlocksUnlinked if:
4282 // - it has a descendant that at some point had more work than the
4284 // - we tried switching to that descendant but were missing
4285 // data for some intermediate block between chainActive and the
4287 // So if this block is itself better than chainActive.Tip() and it wasn't in
4288 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4289 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4290 if (pindexFirstInvalid == NULL) {
4291 assert(foundInUnlinked);
4295 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4296 // End: actual consistency checks.
4298 // Try descending into the first subnode.
4299 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4300 if (range.first != range.second) {
4301 // A subnode was found.
4302 pindex = range.first->second;
4306 // This is a leaf node.
4307 // Move upwards until we reach a node of which we have not yet visited the last child.
4309 // We are going to either move to a parent or a sibling of pindex.
4310 // If pindex was the first with a certain property, unset the corresponding variable.
4311 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4312 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4313 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4314 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4315 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4316 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4317 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4319 CBlockIndex* pindexPar = pindex->pprev;
4320 // Find which child we just visited.
4321 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4322 while (rangePar.first->second != pindex) {
4323 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4326 // Proceed to the next one.
4328 if (rangePar.first != rangePar.second) {
4329 // Move to the sibling.
4330 pindex = rangePar.first->second;
4341 // Check that we actually traversed the entire map.
4342 assert(nNodes == forward.size());
4345 //////////////////////////////////////////////////////////////////////////////
4350 std::string GetWarnings(const std::string& strFor)
4353 string strStatusBar;
4356 if (!CLIENT_VERSION_IS_RELEASE)
4357 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4359 if (GetBoolArg("-testsafemode", false))
4360 strStatusBar = strRPC = "testsafemode enabled";
4362 // Misc warnings like out of disk space and clock is wrong
4363 if (strMiscWarning != "")
4366 strStatusBar = strMiscWarning;
4369 if (fLargeWorkForkFound)
4372 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4374 else if (fLargeWorkInvalidChainFound)
4377 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.");
4383 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4385 const CAlert& alert = item.second;
4386 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4388 nPriority = alert.nPriority;
4389 strStatusBar = alert.strStatusBar;
4390 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4391 strRPC = alert.strRPCError;
4397 if (strFor == "statusbar")
4398 return strStatusBar;
4399 else if (strFor == "rpc")
4401 assert(!"GetWarnings(): invalid parameter");
4412 //////////////////////////////////////////////////////////////////////////////
4418 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4424 assert(recentRejects);
4425 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4427 // If the chain tip has changed previously rejected transactions
4428 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4429 // or a double-spend. Reset the rejects filter and give those
4430 // txs a second chance.
4431 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4432 recentRejects->reset();
4435 return recentRejects->contains(inv.hash) ||
4436 mempool.exists(inv.hash) ||
4437 mapOrphanTransactions.count(inv.hash) ||
4438 pcoinsTip->HaveCoins(inv.hash);
4441 return mapBlockIndex.count(inv.hash);
4443 // Don't know what it is, just say we already got one
4447 void static ProcessGetData(CNode* pfrom)
4449 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4451 vector<CInv> vNotFound;
4455 while (it != pfrom->vRecvGetData.end()) {
4456 // Don't bother if send buffer is too full to respond anyway
4457 if (pfrom->nSendSize >= SendBufferSize())
4460 const CInv &inv = *it;
4462 boost::this_thread::interruption_point();
4465 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4468 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4469 if (mi != mapBlockIndex.end())
4471 if (chainActive.Contains(mi->second)) {
4474 static const int nOneMonth = 30 * 24 * 60 * 60;
4475 // To prevent fingerprinting attacks, only send blocks outside of the active
4476 // chain if they are valid, and no more than a month older (both in time, and in
4477 // best equivalent proof of work) than the best header chain we know about.
4478 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4479 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4480 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4482 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4486 // Pruned nodes may have deleted the block, so check whether
4487 // it's available before trying to send.
4488 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4490 // Send block from disk
4492 if (!ReadBlockFromDisk(block, (*mi).second))
4494 assert(!"cannot load block from disk");
4498 if (inv.type == MSG_BLOCK)
4500 //uint256 hash; int32_t z;
4501 //hash = block.GetHash();
4502 //for (z=31; z>=0; z--)
4503 // fprintf(stderr,"%02x",((uint8_t *)&hash)[z]);
4504 //fprintf(stderr," send block %d\n",komodo_block2height(&block));
4505 pfrom->PushMessage("block", block);
4507 else // MSG_FILTERED_BLOCK)
4509 LOCK(pfrom->cs_filter);
4512 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4513 pfrom->PushMessage("merkleblock", merkleBlock);
4514 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4515 // This avoids hurting performance by pointlessly requiring a round-trip
4516 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4517 // they must either disconnect and retry or request the full block.
4518 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4519 // however we MUST always provide at least what the remote peer needs
4520 typedef std::pair<unsigned int, uint256> PairType;
4521 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4522 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4523 pfrom->PushMessage("tx", block.vtx[pair.first]);
4529 // Trigger the peer node to send a getblocks request for the next batch of inventory
4530 if (inv.hash == pfrom->hashContinue)
4532 // Bypass PushInventory, this must send even if redundant,
4533 // and we want it right after the last block so they don't
4534 // wait for other stuff first.
4536 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4537 pfrom->PushMessage("inv", vInv);
4538 pfrom->hashContinue.SetNull();
4542 else if (inv.IsKnownType())
4544 // Send stream from relay memory
4545 bool pushed = false;
4548 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4549 if (mi != mapRelay.end()) {
4550 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4554 if (!pushed && inv.type == MSG_TX) {
4556 if (mempool.lookup(inv.hash, tx)) {
4557 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4560 pfrom->PushMessage("tx", ss);
4565 vNotFound.push_back(inv);
4569 // Track requests for our stuff.
4570 GetMainSignals().Inventory(inv.hash);
4572 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4577 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4579 if (!vNotFound.empty()) {
4580 // Let the peer know that we didn't find what it asked for, so it doesn't
4581 // have to wait around forever. Currently only SPV clients actually care
4582 // about this message: it's needed when they are recursively walking the
4583 // dependencies of relevant unconfirmed transactions. SPV clients want to
4584 // do that because they want to know about (and store and rebroadcast and
4585 // risk analyze) the dependencies of transactions relevant to them, without
4586 // having to download the entire memory pool.
4587 pfrom->PushMessage("notfound", vNotFound);
4591 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4593 const CChainParams& chainparams = Params();
4594 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4595 //fprintf(stderr, "recv: %s peer=%d\n", SanitizeString(strCommand).c_str(), (int32_t)pfrom->GetId());
4596 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4598 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4605 if (strCommand == "version")
4607 // Each connection can only send one version message
4608 if (pfrom->nVersion != 0)
4610 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4611 Misbehaving(pfrom->GetId(), 1);
4618 uint64_t nNonce = 1;
4619 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4620 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4622 // disconnect from peers older than this proto version
4623 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4624 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4625 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4626 pfrom->fDisconnect = true;
4630 if (pfrom->nVersion == 10300)
4631 pfrom->nVersion = 300;
4633 vRecv >> addrFrom >> nNonce;
4634 if (!vRecv.empty()) {
4635 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4636 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4639 vRecv >> pfrom->nStartingHeight;
4641 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4643 pfrom->fRelayTxes = true;
4645 // Disconnect if we connected to ourself
4646 if (nNonce == nLocalHostNonce && nNonce > 1)
4648 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4649 pfrom->fDisconnect = true;
4653 pfrom->addrLocal = addrMe;
4654 if (pfrom->fInbound && addrMe.IsRoutable())
4659 // Be shy and don't send version until we hear
4660 if (pfrom->fInbound)
4661 pfrom->PushVersion();
4663 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4665 // Potentially mark this peer as a preferred download peer.
4666 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4669 pfrom->PushMessage("verack");
4670 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4672 if (!pfrom->fInbound)
4674 // Advertise our address
4675 if (fListen && !IsInitialBlockDownload())
4677 CAddress addr = GetLocalAddress(&pfrom->addr);
4678 if (addr.IsRoutable())
4680 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4681 pfrom->PushAddress(addr);
4682 } else if (IsPeerAddrLocalGood(pfrom)) {
4683 addr.SetIP(pfrom->addrLocal);
4684 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4685 pfrom->PushAddress(addr);
4689 // Get recent addresses
4690 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4692 pfrom->PushMessage("getaddr");
4693 pfrom->fGetAddr = true;
4695 addrman.Good(pfrom->addr);
4697 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4699 addrman.Add(addrFrom, addrFrom);
4700 addrman.Good(addrFrom);
4707 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4708 item.second.RelayTo(pfrom);
4711 pfrom->fSuccessfullyConnected = true;
4715 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4717 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4718 pfrom->cleanSubVer, pfrom->nVersion,
4719 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4722 int64_t nTimeOffset = nTime - GetTime();
4723 pfrom->nTimeOffset = nTimeOffset;
4724 AddTimeData(pfrom->addr, nTimeOffset);
4728 else if (pfrom->nVersion == 0)
4730 // Must have a version message before anything else
4731 Misbehaving(pfrom->GetId(), 1);
4736 else if (strCommand == "verack")
4738 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4740 // Mark this node as currently connected, so we update its timestamp later.
4741 if (pfrom->fNetworkNode) {
4743 State(pfrom->GetId())->fCurrentlyConnected = true;
4748 else if (strCommand == "addr")
4750 vector<CAddress> vAddr;
4753 // Don't want addr from older versions unless seeding
4754 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4756 if (vAddr.size() > 1000)
4758 Misbehaving(pfrom->GetId(), 20);
4759 return error("message addr size() = %u", vAddr.size());
4762 // Store the new addresses
4763 vector<CAddress> vAddrOk;
4764 int64_t nNow = GetAdjustedTime();
4765 int64_t nSince = nNow - 10 * 60;
4766 BOOST_FOREACH(CAddress& addr, vAddr)
4768 boost::this_thread::interruption_point();
4770 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4771 addr.nTime = nNow - 5 * 24 * 60 * 60;
4772 pfrom->AddAddressKnown(addr);
4773 bool fReachable = IsReachable(addr);
4774 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4776 // Relay to a limited number of other nodes
4779 // Use deterministic randomness to send to the same nodes for 24 hours
4780 // at a time so the addrKnowns of the chosen nodes prevent repeats
4781 static uint256 hashSalt;
4782 if (hashSalt.IsNull())
4783 hashSalt = GetRandHash();
4784 uint64_t hashAddr = addr.GetHash();
4785 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4786 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4787 multimap<uint256, CNode*> mapMix;
4788 BOOST_FOREACH(CNode* pnode, vNodes)
4790 if (pnode->nVersion < CADDR_TIME_VERSION)
4792 unsigned int nPointer;
4793 memcpy(&nPointer, &pnode, sizeof(nPointer));
4794 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4795 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4796 mapMix.insert(make_pair(hashKey, pnode));
4798 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4799 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4800 ((*mi).second)->PushAddress(addr);
4803 // Do not store addresses outside our network
4805 vAddrOk.push_back(addr);
4807 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4808 if (vAddr.size() < 1000)
4809 pfrom->fGetAddr = false;
4810 if (pfrom->fOneShot)
4811 pfrom->fDisconnect = true;
4815 else if (strCommand == "inv")
4819 if (vInv.size() > MAX_INV_SZ)
4821 Misbehaving(pfrom->GetId(), 20);
4822 return error("message inv size() = %u", vInv.size());
4827 std::vector<CInv> vToFetch;
4829 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4831 const CInv &inv = vInv[nInv];
4833 boost::this_thread::interruption_point();
4834 pfrom->AddInventoryKnown(inv);
4836 bool fAlreadyHave = AlreadyHave(inv);
4837 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4839 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4842 if (inv.type == MSG_BLOCK) {
4843 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4844 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4845 // First request the headers preceding the announced block. In the normal fully-synced
4846 // case where a new block is announced that succeeds the current tip (no reorganization),
4847 // there are no such headers.
4848 // Secondly, and only when we are close to being synced, we request the announced block directly,
4849 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4850 // time the block arrives, the header chain leading up to it is already validated. Not
4851 // doing this will result in the received block being rejected as an orphan in case it is
4852 // not a direct successor.
4853 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4854 CNodeState *nodestate = State(pfrom->GetId());
4855 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4856 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4857 vToFetch.push_back(inv);
4858 // Mark block as in flight already, even though the actual "getdata" message only goes out
4859 // later (within the same cs_main lock, though).
4860 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4862 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4866 // Track requests for our stuff
4867 GetMainSignals().Inventory(inv.hash);
4869 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4870 Misbehaving(pfrom->GetId(), 50);
4871 return error("send buffer size() = %u", pfrom->nSendSize);
4875 if (!vToFetch.empty())
4876 pfrom->PushMessage("getdata", vToFetch);
4880 else if (strCommand == "getdata")
4884 if (vInv.size() > MAX_INV_SZ)
4886 Misbehaving(pfrom->GetId(), 20);
4887 return error("message getdata size() = %u", vInv.size());
4890 if (fDebug || (vInv.size() != 1))
4891 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4893 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4894 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4896 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4897 ProcessGetData(pfrom);
4901 else if (strCommand == "getblocks")
4903 CBlockLocator locator;
4905 vRecv >> locator >> hashStop;
4909 // Find the last block the caller has in the main chain
4910 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4912 // Send the rest of the chain
4914 pindex = chainActive.Next(pindex);
4916 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4917 for (; pindex; pindex = chainActive.Next(pindex))
4919 if (pindex->GetBlockHash() == hashStop)
4921 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4924 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4927 // When this block is requested, we'll send an inv that'll
4928 // trigger the peer to getblocks the next batch of inventory.
4929 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4930 pfrom->hashContinue = pindex->GetBlockHash();
4937 else if (strCommand == "getheaders")
4939 CBlockLocator locator;
4941 vRecv >> locator >> hashStop;
4945 if (IsInitialBlockDownload())
4948 CBlockIndex* pindex = NULL;
4949 if (locator.IsNull())
4951 // If locator is null, return the hashStop block
4952 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4953 if (mi == mapBlockIndex.end())
4955 pindex = (*mi).second;
4959 // Find the last block the caller has in the main chain
4960 pindex = FindForkInGlobalIndex(chainActive, locator);
4962 pindex = chainActive.Next(pindex);
4965 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4966 vector<CBlock> vHeaders;
4967 int nLimit = MAX_HEADERS_RESULTS;
4968 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4969 if ( pfrom->lasthdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pfrom->lasthdrsreq != (int32_t)(pindex ? pindex->nHeight : -1) )
4971 pfrom->lasthdrsreq = (int32_t)(pindex ? pindex->nHeight : -1);
4972 for (; pindex; pindex = chainActive.Next(pindex))
4974 vHeaders.push_back(pindex->GetBlockHeader());
4975 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4978 pfrom->PushMessage("headers", vHeaders);
4980 else if ( NOTARY_PUBKEY33[0] != 0 )
4982 static uint32_t counter;
4983 if ( counter++ < 3 )
4984 fprintf(stderr,"you can ignore redundant getheaders from peer.%d %d prev.%d\n",(int32_t)pfrom->id,(int32_t)(pindex ? pindex->nHeight : -1),pfrom->lasthdrsreq);
4989 else if (strCommand == "tx")
4991 vector<uint256> vWorkQueue;
4992 vector<uint256> vEraseQueue;
4996 CInv inv(MSG_TX, tx.GetHash());
4997 pfrom->AddInventoryKnown(inv);
5001 bool fMissingInputs = false;
5002 CValidationState state;
5004 pfrom->setAskFor.erase(inv.hash);
5005 mapAlreadyAskedFor.erase(inv);
5007 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5009 mempool.check(pcoinsTip);
5010 RelayTransaction(tx);
5011 vWorkQueue.push_back(inv.hash);
5013 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5014 pfrom->id, pfrom->cleanSubVer,
5015 tx.GetHash().ToString(),
5016 mempool.mapTx.size());
5018 // Recursively process any orphan transactions that depended on this one
5019 set<NodeId> setMisbehaving;
5020 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5022 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5023 if (itByPrev == mapOrphanTransactionsByPrev.end())
5025 for (set<uint256>::iterator mi = itByPrev->second.begin();
5026 mi != itByPrev->second.end();
5029 const uint256& orphanHash = *mi;
5030 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5031 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5032 bool fMissingInputs2 = false;
5033 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5034 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5035 // anyone relaying LegitTxX banned)
5036 CValidationState stateDummy;
5039 if (setMisbehaving.count(fromPeer))
5041 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5043 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5044 RelayTransaction(orphanTx);
5045 vWorkQueue.push_back(orphanHash);
5046 vEraseQueue.push_back(orphanHash);
5048 else if (!fMissingInputs2)
5051 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5053 // Punish peer that gave us an invalid orphan tx
5054 Misbehaving(fromPeer, nDos);
5055 setMisbehaving.insert(fromPeer);
5056 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5058 // Has inputs but not accepted to mempool
5059 // Probably non-standard or insufficient fee/priority
5060 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5061 vEraseQueue.push_back(orphanHash);
5062 assert(recentRejects);
5063 recentRejects->insert(orphanHash);
5065 mempool.check(pcoinsTip);
5069 BOOST_FOREACH(uint256 hash, vEraseQueue)
5070 EraseOrphanTx(hash);
5072 // TODO: currently, prohibit joinsplits from entering mapOrphans
5073 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5075 AddOrphanTx(tx, pfrom->GetId());
5077 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5078 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5079 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5081 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5083 assert(recentRejects);
5084 recentRejects->insert(tx.GetHash());
5086 if (pfrom->fWhitelisted) {
5087 // Always relay transactions received from whitelisted peers, even
5088 // if they were already in the mempool or rejected from it due
5089 // to policy, allowing the node to function as a gateway for
5090 // nodes hidden behind it.
5092 // Never relay transactions that we would assign a non-zero DoS
5093 // score for, as we expect peers to do the same with us in that
5096 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5097 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5098 RelayTransaction(tx);
5100 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5101 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5106 if (state.IsInvalid(nDoS))
5108 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5109 pfrom->id, pfrom->cleanSubVer,
5110 state.GetRejectReason());
5111 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5112 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5114 Misbehaving(pfrom->GetId(), nDoS);
5119 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5121 std::vector<CBlockHeader> headers;
5123 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5124 unsigned int nCount = ReadCompactSize(vRecv);
5125 if (nCount > MAX_HEADERS_RESULTS) {
5126 Misbehaving(pfrom->GetId(), 20);
5127 return error("headers message size = %u", nCount);
5129 headers.resize(nCount);
5130 for (unsigned int n = 0; n < nCount; n++) {
5131 vRecv >> headers[n];
5132 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5138 // Nothing interesting. Stop asking this peers for more headers.
5142 CBlockIndex *pindexLast = NULL;
5143 BOOST_FOREACH(const CBlockHeader& header, headers) {
5144 CValidationState state;
5145 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5146 Misbehaving(pfrom->GetId(), 20);
5147 return error("non-continuous headers sequence");
5149 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5151 if (state.IsInvalid(nDoS)) {
5153 Misbehaving(pfrom->GetId(), nDoS/nDoS);
5154 return error("invalid header received");
5160 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5162 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5163 // Headers message had its maximum size; the peer may have more headers.
5164 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5165 // from there instead.
5166 if ( pfrom->sendhdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pindexLast->nHeight != pfrom->sendhdrsreq )
5168 pfrom->sendhdrsreq = (int32_t)pindexLast->nHeight;
5169 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5170 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5177 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5182 CInv inv(MSG_BLOCK, block.GetHash());
5183 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5185 pfrom->AddInventoryKnown(inv);
5187 CValidationState state;
5188 // Process all blocks from whitelisted peers, even if not requested,
5189 // unless we're still syncing with the network.
5190 // Such an unrequested block may still be processed, subject to the
5191 // conditions in AcceptBlock().
5192 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5193 ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL);
5195 if (state.IsInvalid(nDoS)) {
5196 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5197 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5200 Misbehaving(pfrom->GetId(), nDoS);
5207 // This asymmetric behavior for inbound and outbound connections was introduced
5208 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5209 // to users' AddrMan and later request them by sending getaddr messages.
5210 // Making nodes which are behind NAT and can only make outgoing connections ignore
5211 // the getaddr message mitigates the attack.
5212 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5214 // Only send one GetAddr response per connection to reduce resource waste
5215 // and discourage addr stamping of INV announcements.
5216 if (pfrom->fSentAddr) {
5217 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5220 pfrom->fSentAddr = true;
5222 pfrom->vAddrToSend.clear();
5223 vector<CAddress> vAddr = addrman.GetAddr();
5224 BOOST_FOREACH(const CAddress &addr, vAddr)
5225 pfrom->PushAddress(addr);
5229 else if (strCommand == "mempool")
5231 LOCK2(cs_main, pfrom->cs_filter);
5233 std::vector<uint256> vtxid;
5234 mempool.queryHashes(vtxid);
5236 BOOST_FOREACH(uint256& hash, vtxid) {
5237 CInv inv(MSG_TX, hash);
5239 bool fInMemPool = mempool.lookup(hash, tx);
5240 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5241 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5243 vInv.push_back(inv);
5244 if (vInv.size() == MAX_INV_SZ) {
5245 pfrom->PushMessage("inv", vInv);
5249 if (vInv.size() > 0)
5250 pfrom->PushMessage("inv", vInv);
5254 else if (strCommand == "ping")
5256 if (pfrom->nVersion > BIP0031_VERSION)
5260 // Echo the message back with the nonce. This allows for two useful features:
5262 // 1) A remote node can quickly check if the connection is operational
5263 // 2) Remote nodes can measure the latency of the network thread. If this node
5264 // is overloaded it won't respond to pings quickly and the remote node can
5265 // avoid sending us more work, like chain download requests.
5267 // The nonce stops the remote getting confused between different pings: without
5268 // it, if the remote node sends a ping once per second and this node takes 5
5269 // seconds to respond to each, the 5th ping the remote sends would appear to
5270 // return very quickly.
5271 pfrom->PushMessage("pong", nonce);
5276 else if (strCommand == "pong")
5278 int64_t pingUsecEnd = nTimeReceived;
5280 size_t nAvail = vRecv.in_avail();
5281 bool bPingFinished = false;
5282 std::string sProblem;
5284 if (nAvail >= sizeof(nonce)) {
5287 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5288 if (pfrom->nPingNonceSent != 0) {
5289 if (nonce == pfrom->nPingNonceSent) {
5290 // Matching pong received, this ping is no longer outstanding
5291 bPingFinished = true;
5292 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5293 if (pingUsecTime > 0) {
5294 // Successful ping time measurement, replace previous
5295 pfrom->nPingUsecTime = pingUsecTime;
5296 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5298 // This should never happen
5299 sProblem = "Timing mishap";
5302 // Nonce mismatches are normal when pings are overlapping
5303 sProblem = "Nonce mismatch";
5305 // This is most likely a bug in another implementation somewhere; cancel this ping
5306 bPingFinished = true;
5307 sProblem = "Nonce zero";
5311 sProblem = "Unsolicited pong without ping";
5314 // This is most likely a bug in another implementation somewhere; cancel this ping
5315 bPingFinished = true;
5316 sProblem = "Short payload";
5319 if (!(sProblem.empty())) {
5320 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5324 pfrom->nPingNonceSent,
5328 if (bPingFinished) {
5329 pfrom->nPingNonceSent = 0;
5334 else if (fAlerts && strCommand == "alert")
5339 uint256 alertHash = alert.GetHash();
5340 if (pfrom->setKnown.count(alertHash) == 0)
5342 if (alert.ProcessAlert(Params().AlertKey()))
5345 pfrom->setKnown.insert(alertHash);
5348 BOOST_FOREACH(CNode* pnode, vNodes)
5349 alert.RelayTo(pnode);
5353 // Small DoS penalty so peers that send us lots of
5354 // duplicate/expired/invalid-signature/whatever alerts
5355 // eventually get banned.
5356 // This isn't a Misbehaving(100) (immediate ban) because the
5357 // peer might be an older or different implementation with
5358 // a different signature key, etc.
5359 Misbehaving(pfrom->GetId(), 10);
5365 else if (strCommand == "filterload")
5367 CBloomFilter filter;
5370 if (!filter.IsWithinSizeConstraints())
5371 // There is no excuse for sending a too-large filter
5372 Misbehaving(pfrom->GetId(), 100);
5375 LOCK(pfrom->cs_filter);
5376 delete pfrom->pfilter;
5377 pfrom->pfilter = new CBloomFilter(filter);
5378 pfrom->pfilter->UpdateEmptyFull();
5380 pfrom->fRelayTxes = true;
5384 else if (strCommand == "filteradd")
5386 vector<unsigned char> vData;
5389 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5390 // and thus, the maximum size any matched object can have) in a filteradd message
5391 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5393 Misbehaving(pfrom->GetId(), 100);
5395 LOCK(pfrom->cs_filter);
5397 pfrom->pfilter->insert(vData);
5399 Misbehaving(pfrom->GetId(), 100);
5404 else if (strCommand == "filterclear")
5406 LOCK(pfrom->cs_filter);
5407 delete pfrom->pfilter;
5408 pfrom->pfilter = new CBloomFilter();
5409 pfrom->fRelayTxes = true;
5413 else if (strCommand == "reject")
5417 string strMsg; unsigned char ccode; string strReason;
5418 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5421 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5423 if (strMsg == "block" || strMsg == "tx")
5427 ss << ": hash " << hash.ToString();
5429 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5430 } catch (const std::ios_base::failure&) {
5431 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5432 LogPrint("net", "Unparseable reject message received\n");
5436 else if (strCommand == "notfound") {
5437 // We do not care about the NOTFOUND message, but logging an Unknown Command
5438 // message would be undesirable as we transmit it ourselves.
5442 // Ignore unknown commands for extensibility
5443 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5451 // requires LOCK(cs_vRecvMsg)
5452 bool ProcessMessages(CNode* pfrom)
5455 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5459 // (4) message start
5467 if (!pfrom->vRecvGetData.empty())
5468 ProcessGetData(pfrom);
5470 // this maintains the order of responses
5471 if (!pfrom->vRecvGetData.empty()) return fOk;
5473 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5474 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5475 // Don't bother if send buffer is too full to respond anyway
5476 if (pfrom->nSendSize >= SendBufferSize())
5480 CNetMessage& msg = *it;
5483 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5484 // msg.hdr.nMessageSize, msg.vRecv.size(),
5485 // msg.complete() ? "Y" : "N");
5487 // end, if an incomplete message is found
5488 if (!msg.complete())
5491 // at this point, any failure means we can delete the current message
5494 // Scan for message start
5495 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5496 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5502 CMessageHeader& hdr = msg.hdr;
5503 if (!hdr.IsValid(Params().MessageStart()))
5505 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5508 string strCommand = hdr.GetCommand();
5511 unsigned int nMessageSize = hdr.nMessageSize;
5514 CDataStream& vRecv = msg.vRecv;
5515 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5516 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5517 if (nChecksum != hdr.nChecksum)
5519 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5520 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5528 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5529 boost::this_thread::interruption_point();
5531 catch (const std::ios_base::failure& e)
5533 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5534 if (strstr(e.what(), "end of data"))
5536 // Allow exceptions from under-length message on vRecv
5537 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());
5539 else if (strstr(e.what(), "size too large"))
5541 // Allow exceptions from over-long size
5542 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5546 //PrintExceptionContinue(&e, "ProcessMessages()");
5549 catch (const boost::thread_interrupted&) {
5552 catch (const std::exception& e) {
5553 PrintExceptionContinue(&e, "ProcessMessages()");
5555 PrintExceptionContinue(NULL, "ProcessMessages()");
5559 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5564 // In case the connection got shut down, its receive buffer was wiped
5565 if (!pfrom->fDisconnect)
5566 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5572 bool SendMessages(CNode* pto, bool fSendTrickle)
5574 const Consensus::Params& consensusParams = Params().GetConsensus();
5576 // Don't send anything until we get its version message
5577 if (pto->nVersion == 0)
5583 bool pingSend = false;
5584 if (pto->fPingQueued) {
5585 // RPC ping request by user
5588 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5589 // Ping automatically sent as a latency probe & keepalive.
5594 while (nonce == 0) {
5595 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5597 pto->fPingQueued = false;
5598 pto->nPingUsecStart = GetTimeMicros();
5599 if (pto->nVersion > BIP0031_VERSION) {
5600 pto->nPingNonceSent = nonce;
5601 pto->PushMessage("ping", nonce);
5603 // Peer is too old to support ping command with nonce, pong will never arrive.
5604 pto->nPingNonceSent = 0;
5605 pto->PushMessage("ping");
5609 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5613 // Address refresh broadcast
5614 static int64_t nLastRebroadcast;
5615 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5618 BOOST_FOREACH(CNode* pnode, vNodes)
5620 // Periodically clear addrKnown to allow refresh broadcasts
5621 if (nLastRebroadcast)
5622 pnode->addrKnown.reset();
5624 // Rebroadcast our address
5625 AdvertizeLocal(pnode);
5627 if (!vNodes.empty())
5628 nLastRebroadcast = GetTime();
5636 vector<CAddress> vAddr;
5637 vAddr.reserve(pto->vAddrToSend.size());
5638 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5640 if (!pto->addrKnown.contains(addr.GetKey()))
5642 pto->addrKnown.insert(addr.GetKey());
5643 vAddr.push_back(addr);
5644 // receiver rejects addr messages larger than 1000
5645 if (vAddr.size() >= 1000)
5647 pto->PushMessage("addr", vAddr);
5652 pto->vAddrToSend.clear();
5654 pto->PushMessage("addr", vAddr);
5657 CNodeState &state = *State(pto->GetId());
5658 if (state.fShouldBan) {
5659 if (pto->fWhitelisted)
5660 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5662 pto->fDisconnect = true;
5663 if (pto->addr.IsLocal())
5664 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5667 CNode::Ban(pto->addr);
5670 state.fShouldBan = false;
5673 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5674 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5675 state.rejects.clear();
5678 if (pindexBestHeader == NULL)
5679 pindexBestHeader = chainActive.Tip();
5680 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.
5681 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5682 // Only actively request headers from a single peer, unless we're close to today.
5683 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5684 state.fSyncStarted = true;
5686 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5687 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5688 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5692 // Resend wallet transactions that haven't gotten in a block yet
5693 // Except during reindex, importing and IBD, when old wallet
5694 // transactions become unconfirmed and spams other nodes.
5695 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5697 GetMainSignals().Broadcast(nTimeBestReceived);
5701 // Message: inventory
5704 vector<CInv> vInvWait;
5706 LOCK(pto->cs_inventory);
5707 vInv.reserve(pto->vInventoryToSend.size());
5708 vInvWait.reserve(pto->vInventoryToSend.size());
5709 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5711 if (pto->setInventoryKnown.count(inv))
5714 // trickle out tx inv to protect privacy
5715 if (inv.type == MSG_TX && !fSendTrickle)
5717 // 1/4 of tx invs blast to all immediately
5718 static uint256 hashSalt;
5719 if (hashSalt.IsNull())
5720 hashSalt = GetRandHash();
5721 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5722 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5723 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5727 vInvWait.push_back(inv);
5732 // returns true if wasn't already contained in the set
5733 if (pto->setInventoryKnown.insert(inv).second)
5735 vInv.push_back(inv);
5736 if (vInv.size() >= 1000)
5738 pto->PushMessage("inv", vInv);
5743 pto->vInventoryToSend = vInvWait;
5746 pto->PushMessage("inv", vInv);
5748 // Detect whether we're stalling
5749 int64_t nNow = GetTimeMicros();
5750 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5751 // Stalling only triggers when the block download window cannot move. During normal steady state,
5752 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5753 // should only happen during initial block download.
5754 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5755 pto->fDisconnect = true;
5757 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5758 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5759 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5760 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5761 // to unreasonably increase our timeout.
5762 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5763 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5764 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5765 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5766 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5767 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5768 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5769 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5770 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5771 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5772 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5774 if (queuedBlock.nTimeDisconnect < nNow) {
5775 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5776 pto->fDisconnect = true;
5781 // Message: getdata (blocks)
5783 vector<CInv> vGetData;
5784 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5785 vector<CBlockIndex*> vToDownload;
5786 NodeId staller = -1;
5787 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5788 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5789 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5790 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5791 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5792 pindex->nHeight, pto->id);
5794 if (state.nBlocksInFlight == 0 && staller != -1) {
5795 if (State(staller)->nStallingSince == 0) {
5796 State(staller)->nStallingSince = nNow;
5797 LogPrint("net", "Stall started peer=%d\n", staller);
5803 // Message: getdata (non-blocks)
5805 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5807 const CInv& inv = (*pto->mapAskFor.begin()).second;
5808 if (!AlreadyHave(inv))
5811 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5812 vGetData.push_back(inv);
5813 if (vGetData.size() >= 1000)
5815 pto->PushMessage("getdata", vGetData);
5819 //If we're not going to ask, don't expect a response.
5820 pto->setAskFor.erase(inv.hash);
5822 pto->mapAskFor.erase(pto->mapAskFor.begin());
5824 if (!vGetData.empty())
5825 pto->PushMessage("getdata", vGetData);
5831 std::string CBlockFileInfo::ToString() const {
5832 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));
5843 BlockMap::iterator it1 = mapBlockIndex.begin();
5844 for (; it1 != mapBlockIndex.end(); it1++)
5845 delete (*it1).second;
5846 mapBlockIndex.clear();
5848 // orphan transactions
5849 mapOrphanTransactions.clear();
5850 mapOrphanTransactionsByPrev.clear();
5852 } instance_of_cmaincleanup;
5854 extern "C" const char* getDataDir()
5856 return GetDataDir().string().c_str();