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/upgrades.h"
17 #include "consensus/validation.h"
18 #include "deprecation.h"
20 #include "merkleblock.h"
25 #include "txmempool.h"
26 #include "ui_interface.h"
29 #include "utilmoneystr.h"
30 #include "validationinterface.h"
31 #include "wallet/asyncrpcoperation_sendmany.h"
32 #include "wallet/asyncrpcoperation_shieldcoinbase.h"
36 #include <boost/algorithm/string/replace.hpp>
37 #include <boost/filesystem.hpp>
38 #include <boost/filesystem/fstream.hpp>
39 #include <boost/math/distributions/poisson.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/static_assert.hpp>
46 # error "Zcash cannot be compiled without assertions."
54 CCriticalSection cs_main;
55 extern uint8_t NOTARY_PUBKEY33[33];
56 extern int32_t KOMODO_LOADINGBLOCKS;
58 BlockMap mapBlockIndex;
60 CBlockIndex *pindexBestHeader = NULL;
61 int64_t nTimeBestReceived = 0;
62 CWaitableCriticalSection csBestBlock;
63 CConditionVariable cvBlockChange;
64 int nScriptCheckThreads = 0;
65 bool fExperimentalMode = false;
66 bool fImporting = false;
67 bool fReindex = false;
68 bool fTxIndex = false;
69 bool fHavePruned = false;
70 bool fPruneMode = false;
71 bool fIsBareMultisigStd = true;
72 bool fCheckBlockIndex = false;
73 bool fCheckpointsEnabled = true;
74 bool fCoinbaseEnforcedProtectionEnabled = true;
75 size_t nCoinCacheUsage = 5000 * 300;
76 uint64_t nPruneTarget = 0;
77 bool fAlerts = DEFAULT_ALERTS;
79 unsigned int expiryDelta = DEFAULT_TX_EXPIRY_DELTA;
81 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
82 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
84 CTxMemPool mempool(::minRelayTxFee);
90 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
91 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
92 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
95 * Returns true if there are nRequired or more blocks of minVersion or above
96 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
98 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
99 static void CheckBlockIndex();
101 /** Constant stuff for coinbase transactions we create: */
102 CScript COINBASE_FLAGS;
104 const string strMessageMagic = "Komodo Signed Message:\n";
109 struct CBlockIndexWorkComparator
111 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
112 // First sort by most total work, ...
113 if (pa->nChainWork > pb->nChainWork) return false;
114 if (pa->nChainWork < pb->nChainWork) return true;
116 // ... then by earliest time received, ...
117 if (pa->nSequenceId < pb->nSequenceId) return false;
118 if (pa->nSequenceId > pb->nSequenceId) return true;
120 // Use pointer address as tie breaker (should only happen with blocks
121 // loaded from disk, as those all have id 0).
122 if (pa < pb) return false;
123 if (pa > pb) return true;
130 CBlockIndex *pindexBestInvalid;
133 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
134 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
135 * missing the data for the block.
137 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
138 /** Number of nodes with fSyncStarted. */
139 int nSyncStarted = 0;
140 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
141 * Pruned nodes may have entries where B is missing data.
143 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
145 CCriticalSection cs_LastBlockFile;
146 std::vector<CBlockFileInfo> vinfoBlockFile;
147 int nLastBlockFile = 0;
148 /** Global flag to indicate we should check to see if there are
149 * block/undo files that should be deleted. Set on startup
150 * or if we allocate more file space when we're in prune mode
152 bool fCheckForPruning = false;
155 * Every received block is assigned a unique and increasing identifier, so we
156 * know which one to give priority in case of a fork.
158 CCriticalSection cs_nBlockSequenceId;
159 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
160 uint32_t nBlockSequenceId = 1;
163 * Sources of received blocks, saved to be able to send them reject
164 * messages or ban them when processing happens afterwards. Protected by
167 map<uint256, NodeId> mapBlockSource;
170 * Filter for transactions that were recently rejected by
171 * AcceptToMemoryPool. These are not rerequested until the chain tip
172 * changes, at which point the entire filter is reset. Protected by
175 * Without this filter we'd be re-requesting txs from each of our peers,
176 * increasing bandwidth consumption considerably. For instance, with 100
177 * peers, half of which relay a tx we don't accept, that might be a 50x
178 * bandwidth increase. A flooding attacker attempting to roll-over the
179 * filter using minimum-sized, 60byte, transactions might manage to send
180 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
181 * two minute window to send invs to us.
183 * Decreasing the false positive rate is fairly cheap, so we pick one in a
184 * million to make it highly unlikely for users to have issues with this
189 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
190 uint256 hashRecentRejectsChainTip;
192 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
195 CBlockIndex *pindex; //! Optional.
196 int64_t nTime; //! Time of "getdata" request in microseconds.
197 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
198 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
200 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
202 /** Number of blocks in flight with validated headers. */
203 int nQueuedValidatedHeaders = 0;
205 /** Number of preferable block download peers. */
206 int nPreferredDownload = 0;
208 /** Dirty block index entries. */
209 set<CBlockIndex*> setDirtyBlockIndex;
211 /** Dirty block file entries. */
212 set<int> setDirtyFileInfo;
215 //////////////////////////////////////////////////////////////////////////////
217 // Registration of network node signals.
222 struct CBlockReject {
223 unsigned char chRejectCode;
224 string strRejectReason;
229 * Maintain validation-specific state about nodes, protected by cs_main, instead
230 * by CNode's own locks. This simplifies asynchronous operation, where
231 * processing of incoming data is done after the ProcessMessage call returns,
232 * and we're no longer holding the node's locks.
235 //! The peer's address
237 //! Whether we have a fully established connection.
238 bool fCurrentlyConnected;
239 //! Accumulated misbehaviour score for this peer.
241 //! Whether this peer should be disconnected and banned (unless whitelisted).
243 //! String name of this peer (debugging/logging purposes).
245 //! List of asynchronously-determined block rejections to notify this peer about.
246 std::vector<CBlockReject> rejects;
247 //! The best known block we know this peer has announced.
248 CBlockIndex *pindexBestKnownBlock;
249 //! The hash of the last unknown block this peer has announced.
250 uint256 hashLastUnknownBlock;
251 //! The last full block we both have.
252 CBlockIndex *pindexLastCommonBlock;
253 //! Whether we've started headers synchronization with this peer.
255 //! Since when we're stalling block download progress (in microseconds), or 0.
256 int64_t nStallingSince;
257 list<QueuedBlock> vBlocksInFlight;
259 int nBlocksInFlightValidHeaders;
260 //! Whether we consider this a preferred download peer.
261 bool fPreferredDownload;
264 fCurrentlyConnected = false;
267 pindexBestKnownBlock = NULL;
268 hashLastUnknownBlock.SetNull();
269 pindexLastCommonBlock = NULL;
270 fSyncStarted = false;
273 nBlocksInFlightValidHeaders = 0;
274 fPreferredDownload = false;
278 /** Map maintaining per-node state. Requires cs_main. */
279 map<NodeId, CNodeState> mapNodeState;
282 CNodeState *State(NodeId pnode) {
283 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
284 if (it == mapNodeState.end())
292 return chainActive.Height();
295 void UpdatePreferredDownload(CNode* node, CNodeState* state)
297 nPreferredDownload -= state->fPreferredDownload;
299 // Whether this node should be marked as a preferred download node.
300 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
302 nPreferredDownload += state->fPreferredDownload;
305 // Returns time at which to timeout block request (nTime in microseconds)
306 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
308 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
311 void InitializeNode(NodeId nodeid, const CNode *pnode) {
313 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
314 state.name = pnode->addrName;
315 state.address = pnode->addr;
318 void FinalizeNode(NodeId nodeid) {
320 CNodeState *state = State(nodeid);
322 if (state->fSyncStarted)
325 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
326 AddressCurrentlyConnected(state->address);
329 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
330 mapBlocksInFlight.erase(entry.hash);
331 EraseOrphansFor(nodeid);
332 nPreferredDownload -= state->fPreferredDownload;
334 mapNodeState.erase(nodeid);
337 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)
339 /* int expired = pool.Expire(GetTime() - age);
341 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
343 std::vector<uint256> vNoSpendsRemaining;
344 pool.TrimToSize(limit, &vNoSpendsRemaining);
345 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
346 pcoinsTip->Uncache(removed);*/
350 // Returns a bool indicating whether we requested this block.
351 bool MarkBlockAsReceived(const uint256& hash) {
352 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
353 if (itInFlight != mapBlocksInFlight.end()) {
354 CNodeState *state = State(itInFlight->second.first);
355 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
356 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
357 state->vBlocksInFlight.erase(itInFlight->second.second);
358 state->nBlocksInFlight--;
359 state->nStallingSince = 0;
360 mapBlocksInFlight.erase(itInFlight);
367 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
368 CNodeState *state = State(nodeid);
369 assert(state != NULL);
371 // Make sure it's not listed somewhere already.
372 MarkBlockAsReceived(hash);
374 int64_t nNow = GetTimeMicros();
375 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
376 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
377 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
378 state->nBlocksInFlight++;
379 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
380 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
383 /** Check whether the last unknown block a peer advertized is not yet known. */
384 void ProcessBlockAvailability(NodeId nodeid) {
385 CNodeState *state = State(nodeid);
386 assert(state != NULL);
388 if (!state->hashLastUnknownBlock.IsNull()) {
389 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
390 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0)
392 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
393 state->pindexBestKnownBlock = itOld->second;
394 state->hashLastUnknownBlock.SetNull();
399 /** Update tracking information about which blocks a peer is assumed to have. */
400 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
401 CNodeState *state = State(nodeid);
402 assert(state != NULL);
404 /*ProcessBlockAvailability(nodeid);
406 BlockMap::iterator it = mapBlockIndex.find(hash);
407 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
408 // An actually better block was announced.
409 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
410 state->pindexBestKnownBlock = it->second;
413 // An unknown block was announced; just assume that the latest one is the best one.
414 state->hashLastUnknownBlock = hash;
418 /** Find the last common ancestor two blocks have.
419 * Both pa and pb must be non-NULL. */
420 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
421 if (pa->nHeight > pb->nHeight) {
422 pa = pa->GetAncestor(pb->nHeight);
423 } else if (pb->nHeight > pa->nHeight) {
424 pb = pb->GetAncestor(pa->nHeight);
427 while (pa != pb && pa && pb) {
432 // Eventually all chain branches meet at the genesis block.
437 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
438 * at most count entries. */
439 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
443 vBlocks.reserve(vBlocks.size() + count);
444 CNodeState *state = State(nodeid);
445 assert(state != NULL);
447 // Make sure pindexBestKnownBlock is up to date, we'll need it.
448 ProcessBlockAvailability(nodeid);
450 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
451 // This peer has nothing interesting.
455 if (state->pindexLastCommonBlock == NULL) {
456 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
457 // Guessing wrong in either direction is not a problem.
458 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
461 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
462 // of its current tip anymore. Go back enough to fix that.
463 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
464 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
467 std::vector<CBlockIndex*> vToFetch;
468 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
469 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
470 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
471 // download that next block if the window were 1 larger.
472 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
473 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
474 NodeId waitingfor = -1;
475 while (pindexWalk->nHeight < nMaxHeight) {
476 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
477 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
478 // as iterating over ~100 CBlockIndex* entries anyway.
479 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
480 vToFetch.resize(nToFetch);
481 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
482 vToFetch[nToFetch - 1] = pindexWalk;
483 for (unsigned int i = nToFetch - 1; i > 0; i--) {
484 vToFetch[i - 1] = vToFetch[i]->pprev;
487 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
488 // are not yet downloaded and not in flight to vBlocks. In the meantime, update
489 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
490 // already part of our chain (and therefore don't need it even if pruned).
491 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
492 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
493 // We consider the chain that this peer is on invalid.
496 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
497 if (pindex->nChainTx)
498 state->pindexLastCommonBlock = pindex;
499 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
500 // The block is not already downloaded, and not yet in flight.
501 if (pindex->nHeight > nWindowEnd) {
502 // We reached the end of the window.
503 if (vBlocks.size() == 0 && waitingfor != nodeid) {
504 // We aren't able to fetch anything, but we would be if the download window was one larger.
505 nodeStaller = waitingfor;
509 vBlocks.push_back(pindex);
510 if (vBlocks.size() == count) {
513 } else if (waitingfor == -1) {
514 // This is the first already-in-flight block.
515 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
523 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
525 CNodeState *state = State(nodeid);
528 stats.nMisbehavior = state->nMisbehavior;
529 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
530 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
531 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
533 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
538 void RegisterNodeSignals(CNodeSignals& nodeSignals)
540 nodeSignals.GetHeight.connect(&GetHeight);
541 nodeSignals.ProcessMessages.connect(&ProcessMessages);
542 nodeSignals.SendMessages.connect(&SendMessages);
543 nodeSignals.InitializeNode.connect(&InitializeNode);
544 nodeSignals.FinalizeNode.connect(&FinalizeNode);
547 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
549 nodeSignals.GetHeight.disconnect(&GetHeight);
550 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
551 nodeSignals.SendMessages.disconnect(&SendMessages);
552 nodeSignals.InitializeNode.disconnect(&InitializeNode);
553 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
556 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
558 // Find the first block the caller has in the main chain
559 BOOST_FOREACH(const uint256& hash, locator.vHave) {
560 BlockMap::iterator mi = mapBlockIndex.find(hash);
561 if (mi != mapBlockIndex.end())
563 CBlockIndex* pindex = (*mi).second;
564 if (pindex != 0 && chain.Contains(pindex))
566 if (pindex != 0 && pindex->GetAncestor(chain.Height()) == chain.Tip()) {
571 return chain.Genesis();
574 CCoinsViewCache *pcoinsTip = NULL;
575 CBlockTreeDB *pblocktree = NULL;
582 //////////////////////////////////////////////////////////////////////////////
584 // mapOrphanTransactions
587 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
589 uint256 hash = tx.GetHash();
590 if (mapOrphanTransactions.count(hash))
593 // Ignore big transactions, to avoid a
594 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
595 // large transaction with a missing parent then we assume
596 // it will rebroadcast it later, after the parent transaction(s)
597 // have been mined or received.
598 // 10,000 orphans, each of which is at most 5,000 bytes big is
599 // at most 500 megabytes of orphans:
600 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
603 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
607 mapOrphanTransactions[hash].tx = tx;
608 mapOrphanTransactions[hash].fromPeer = peer;
609 BOOST_FOREACH(const CTxIn& txin, tx.vin)
610 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
612 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
613 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
617 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
619 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
620 if (it == mapOrphanTransactions.end())
622 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
624 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
625 if (itPrev == mapOrphanTransactionsByPrev.end())
627 itPrev->second.erase(hash);
628 if (itPrev->second.empty())
629 mapOrphanTransactionsByPrev.erase(itPrev);
631 mapOrphanTransactions.erase(it);
634 void EraseOrphansFor(NodeId peer)
637 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
638 while (iter != mapOrphanTransactions.end())
640 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
641 if (maybeErase->second.fromPeer == peer)
643 EraseOrphanTx(maybeErase->second.tx.GetHash());
647 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
651 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
653 unsigned int nEvicted = 0;
654 while (mapOrphanTransactions.size() > nMaxOrphans)
656 // Evict a random orphan:
657 uint256 randomhash = GetRandHash();
658 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
659 if (it == mapOrphanTransactions.end())
660 it = mapOrphanTransactions.begin();
661 EraseOrphanTx(it->first);
668 bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight)
670 bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
673 // Overwinter standard rules apply
674 if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) {
675 reason = "overwinter-version";
679 // Sprout standard rules apply
680 if (tx.nVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION) {
686 BOOST_FOREACH(const CTxIn& txin, tx.vin)
688 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
689 // keys. (remember the 520 byte limit on redeemScript size) That works
690 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
691 // bytes of scriptSig, which we round off to 1650 bytes for some minor
692 // future-proofing. That's also enough to spend a 20-of-20
693 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
694 // considered standard)
695 if (txin.scriptSig.size() > 1650) {
696 reason = "scriptsig-size";
699 if (!txin.scriptSig.IsPushOnly()) {
700 reason = "scriptsig-not-pushonly";
705 unsigned int v=0,nDataOut = 0;
706 txnouttype whichType;
707 BOOST_FOREACH(const CTxOut& txout, tx.vout)
709 if (!::IsStandard(txout.scriptPubKey, whichType))
711 reason = "scriptpubkey";
712 fprintf(stderr,">>>>>>>>>>>>>>> vout.%d nDataout.%d\n",v,nDataOut);
716 if (whichType == TX_NULL_DATA)
719 //fprintf(stderr,"is OP_RETURN\n");
721 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
722 reason = "bare-multisig";
724 } else if (txout.IsDust(::minRelayTxFee)) {
731 // only one OP_RETURN txout is permitted
733 reason = "multi-op-return";
740 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
743 if (tx.nLockTime == 0)
745 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
747 BOOST_FOREACH(const CTxIn& txin, tx.vin)
749 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)) )
753 else if (!txin.IsFinal())
755 //printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime);
762 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight)
764 if (tx.nExpiryHeight == 0 || tx.IsCoinBase()) {
767 return static_cast<uint32_t>(nBlockHeight) > tx.nExpiryHeight;
770 bool CheckFinalTx(const CTransaction &tx, int flags)
772 AssertLockHeld(cs_main);
774 // By convention a negative value for flags indicates that the
775 // current network-enforced consensus rules should be used. In
776 // a future soft-fork scenario that would mean checking which
777 // rules would be enforced for the next block and setting the
778 // appropriate flags. At the present time no soft-forks are
779 // scheduled, so no flags are set.
780 flags = std::max(flags, 0);
782 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
783 // nLockTime because when IsFinalTx() is called within
784 // CBlock::AcceptBlock(), the height of the block *being*
785 // evaluated is what is used. Thus if we want to know if a
786 // transaction can be part of the *next* block, we need to call
787 // IsFinalTx() with one more than chainActive.Height().
788 const int nBlockHeight = chainActive.Height() + 1;
790 // Timestamps on the other hand don't get any special treatment,
791 // because we can't know what timestamp the next block will have,
792 // and there aren't timestamp applications where it matters.
793 // However this changes once median past time-locks are enforced:
794 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
795 ? chainActive.Tip()->GetMedianTimePast()
798 return IsFinalTx(tx, nBlockHeight, nBlockTime);
802 * Check transaction inputs to mitigate two
803 * potential denial-of-service attacks:
805 * 1. scriptSigs with extra data stuffed into them,
806 * not consumed by scriptPubKey (or P2SH script)
807 * 2. P2SH scripts with a crazy number of expensive
808 * CHECKSIG/CHECKMULTISIG operations
810 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId)
813 return true; // Coinbases don't use vin normally
815 for (unsigned int i = 0; i < tx.vin.size(); i++)
817 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
819 vector<vector<unsigned char> > vSolutions;
820 txnouttype whichType;
821 // get the scriptPubKey corresponding to this input:
822 const CScript& prevScript = prev.scriptPubKey;
823 if (!Solver(prevScript, whichType, vSolutions))
825 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
826 if (nArgsExpected < 0)
829 // Transactions with extra stuff in their scriptSigs are
830 // non-standard. Note that this EvalScript() call will
831 // be quick, because if there are any operations
832 // beside "push data" in the scriptSig
833 // IsStandardTx() will have already returned false
834 // and this method isn't called.
835 vector<vector<unsigned char> > stack;
836 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), consensusBranchId))
839 if (whichType == TX_SCRIPTHASH)
843 CScript subscript(stack.back().begin(), stack.back().end());
844 vector<vector<unsigned char> > vSolutions2;
845 txnouttype whichType2;
846 if (Solver(subscript, whichType2, vSolutions2))
848 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
851 nArgsExpected += tmpExpected;
855 // Any other Script with less than 15 sigops OK:
856 unsigned int sigops = subscript.GetSigOpCount(true);
857 // ... extra data left on the stack after execution is OK, too:
858 return (sigops <= MAX_P2SH_SIGOPS);
862 if (stack.size() != (unsigned int)nArgsExpected)
869 unsigned int GetLegacySigOpCount(const CTransaction& tx)
871 unsigned int nSigOps = 0;
872 BOOST_FOREACH(const CTxIn& txin, tx.vin)
874 nSigOps += txin.scriptSig.GetSigOpCount(false);
876 BOOST_FOREACH(const CTxOut& txout, tx.vout)
878 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
883 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
888 unsigned int nSigOps = 0;
889 for (unsigned int i = 0; i < tx.vin.size(); i++)
891 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
892 if (prevout.scriptPubKey.IsPayToScriptHash())
893 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
899 * Check a transaction contextually against a set of consensus rules valid at a given block height.
902 * 1. AcceptToMemoryPool calls CheckTransaction and this function.
903 * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction)
904 * and ContextualCheckBlock (which calls this function).
906 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const int nHeight, const int dosLevel)
908 bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
909 bool isSprout = !isOverwinter;
911 // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond
912 if (isSprout && tx.fOverwintered) {
913 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter is not active yet"),
914 REJECT_INVALID, "tx-overwinter-not-active");
917 // If Overwinter rules apply:
919 // Reject transactions with valid version but missing overwinter flag
920 if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) {
921 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"),
922 REJECT_INVALID, "tx-overwinter-flag-not-set");
925 // Reject transactions with invalid version
926 if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) {
927 return state.DoS(100, error("CheckTransaction(): overwinter version too high"),
928 REJECT_INVALID, "bad-tx-overwinter-version-too-high");
931 // Reject transactions intended for Sprout
932 if (!tx.fOverwintered) {
933 return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"),
934 REJECT_INVALID, "tx-overwinter-active");
937 // Check that all transactions are unexpired
938 if (IsExpiredTx(tx, nHeight)) {
939 return state.DoS(dosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired");
943 if (!(tx.IsCoinBase() || tx.vjoinsplit.empty())) {
944 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
945 // Empty output script.
947 uint256 dataToBeSigned;
949 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId);
950 } catch (std::logic_error ex) {
951 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
952 REJECT_INVALID, "error-computing-signature-hash");
955 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
957 // We rely on libsodium to check that the signature is canonical.
958 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
959 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
960 dataToBeSigned.begin(), 32,
961 tx.joinSplitPubKey.begin()
963 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
964 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
970 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
971 libzcash::ProofVerifier& verifier)
973 static uint256 array[64]; static int32_t numbanned,indallvouts; int32_t j,k,n;
974 if ( *(int32_t *)&array[0] == 0 )
975 numbanned = komodo_bannedset(&indallvouts,array,(int32_t)(sizeof(array)/sizeof(*array)));
979 for (k=0; k<numbanned; k++)
981 if ( tx.vin[j].prevout.hash == array[k] && (tx.vin[j].prevout.n == 1 || k >= indallvouts) )
983 static uint32_t counter;
984 if ( counter++ < 100 )
985 printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->nHeight,j);
990 // Don't count coinbase transactions because mining skews the count
991 if (!tx.IsCoinBase()) {
992 transactionsValidated.increment();
995 if (!CheckTransactionWithoutProofVerification(tx, state)) {
998 // Ensure that zk-SNARKs verify
999 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1000 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
1001 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
1002 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
1009 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
1011 // Basic checks that don't depend on any context
1015 * 1. The consensus rule below was:
1016 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
1017 * which checked if tx.nVersion fell within the range:
1018 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
1019 * 2. The parser allowed tx.nVersion to be negative
1022 * 1. The consensus rule checks to see if tx.Version falls within the range:
1023 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
1024 * 2. The previous consensus rule checked for negative values within the range:
1025 * INT32_MIN <= tx.nVersion < 0
1026 * This is unnecessary for Overwinter transactions since the parser now
1027 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
1028 * and when Overwinter is not active ContextualCheckTransaction rejects
1029 * transactions with fOverwintered set. When fOverwintered is set,
1030 * this function and ContextualCheckTransaction will together check to
1031 * ensure tx.nVersion avoids the following ranges:
1032 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
1033 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
1035 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
1036 return state.DoS(100, error("CheckTransaction(): version too low"),
1037 REJECT_INVALID, "bad-txns-version-too-low");
1039 else if (tx.fOverwintered) {
1040 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
1041 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
1042 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
1044 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
1045 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
1046 REJECT_INVALID, "bad-tx-version-group-id");
1048 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
1049 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
1050 REJECT_INVALID, "bad-tx-expiry-height-too-high");
1054 // Transactions can contain empty `vin` and `vout` so long as
1055 // `vjoinsplit` is non-empty.
1056 if (tx.vin.empty() && tx.vjoinsplit.empty())
1057 return state.DoS(10, error("CheckTransaction(): vin empty"),
1058 REJECT_INVALID, "bad-txns-vin-empty");
1059 if (tx.vout.empty() && tx.vjoinsplit.empty())
1060 return state.DoS(10, error("CheckTransaction(): vout empty"),
1061 REJECT_INVALID, "bad-txns-vout-empty");
1064 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
1065 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
1066 return state.DoS(100, error("CheckTransaction(): size limits failed"),
1067 REJECT_INVALID, "bad-txns-oversize");
1069 // Check for negative or overflow output values
1070 CAmount nValueOut = 0;
1071 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1073 if (txout.nValue < 0)
1074 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
1075 REJECT_INVALID, "bad-txns-vout-negative");
1076 if (txout.nValue > MAX_MONEY)
1078 fprintf(stderr,"%.8f > max %.8f\n",(double)txout.nValue/COIN,(double)MAX_MONEY/COIN);
1079 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),REJECT_INVALID, "bad-txns-vout-toolarge");
1081 nValueOut += txout.nValue;
1082 if (!MoneyRange(nValueOut))
1083 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1084 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1087 // Ensure that joinsplit values are well-formed
1088 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1090 if (joinsplit.vpub_old < 0) {
1091 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
1092 REJECT_INVALID, "bad-txns-vpub_old-negative");
1095 if (joinsplit.vpub_new < 0) {
1096 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
1097 REJECT_INVALID, "bad-txns-vpub_new-negative");
1100 if (joinsplit.vpub_old > MAX_MONEY) {
1101 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
1102 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
1105 if (joinsplit.vpub_new > MAX_MONEY) {
1106 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
1107 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
1110 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1111 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
1112 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1115 nValueOut += joinsplit.vpub_old;
1116 if (!MoneyRange(nValueOut)) {
1117 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1118 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1122 // Ensure input values do not exceed MAX_MONEY
1123 // We have not resolved the txin values at this stage,
1124 // but we do know what the joinsplits claim to add
1125 // to the value pool.
1127 CAmount nValueIn = 0;
1128 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1130 nValueIn += it->vpub_new;
1132 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1133 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1134 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1140 // Check for duplicate inputs
1141 set<COutPoint> vInOutPoints;
1142 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1144 if (vInOutPoints.count(txin.prevout))
1145 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1146 REJECT_INVALID, "bad-txns-inputs-duplicate");
1147 vInOutPoints.insert(txin.prevout);
1150 // Check for duplicate joinsplit nullifiers in this transaction
1151 set<uint256> vJoinSplitNullifiers;
1152 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1154 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1156 if (vJoinSplitNullifiers.count(nf))
1157 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1158 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1160 vJoinSplitNullifiers.insert(nf);
1164 if (tx.IsCoinBase())
1166 // There should be no joinsplits in a coinbase transaction
1167 if (tx.vjoinsplit.size() > 0)
1168 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1169 REJECT_INVALID, "bad-cb-has-joinsplits");
1171 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1172 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1173 REJECT_INVALID, "bad-cb-length");
1177 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1178 if (txin.prevout.IsNull())
1179 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1180 REJECT_INVALID, "bad-txns-prevout-null");
1186 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1188 extern int32_t KOMODO_ON_DEMAND;
1191 uint256 hash = tx.GetHash();
1192 double dPriorityDelta = 0;
1193 CAmount nFeeDelta = 0;
1194 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1195 if (dPriorityDelta > 0 || nFeeDelta > 0)
1199 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1203 // There is a free transaction area in blocks created by most miners,
1204 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1205 // to be considered to fall into this category. We don't want to encourage sending
1206 // multiple transactions instead of one big transaction to avoid fees.
1207 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1211 if (!MoneyRange(nMinFee))
1212 nMinFee = MAX_MONEY;
1217 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
1219 AssertLockHeld(cs_main);
1220 if (pfMissingInputs)
1221 *pfMissingInputs = false;
1223 int nextBlockHeight = chainActive.Height() + 1;
1224 auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus());
1226 // Node operator can choose to reject tx by number of transparent inputs
1227 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1228 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1230 size_t n = tx.vin.size();
1232 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1237 auto verifier = libzcash::ProofVerifier::Strict();
1238 if ( komodo_validate_interest(tx,chainActive.Tip()->nHeight+1,chainActive.Tip()->GetMedianTimePast() + 777,0) < 0 )
1240 //fprintf(stderr,"AcceptToMemoryPool komodo_validate_interest failure\n");
1241 return error("AcceptToMemoryPool: komodo_validate_interest failed");
1243 if (!CheckTransaction(tx, state, verifier))
1244 return error("AcceptToMemoryPool: CheckTransaction failed");
1246 // DoS level set to 10 to be more forgiving.
1247 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
1248 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1249 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1252 // Coinbase is only valid in a block, not as a loose transaction
1253 if (tx.IsCoinBase())
1255 fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
1256 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
1258 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1260 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
1262 fprintf(stderr,"AcceptToMemoryPool reject nonstandard transaction: %s\n",reason.c_str());
1263 return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
1265 // Only accept nLockTime-using transactions that can be mined in the next
1266 // block; we don't want our mempool filled up with transactions that can't
1268 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1270 //fprintf(stderr,"AcceptToMemoryPool reject non-final\n");
1271 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1273 // is it already in the memory pool?
1274 uint256 hash = tx.GetHash();
1275 if (pool.exists(hash))
1277 fprintf(stderr,"already in mempool\n");
1281 // Check for conflicts with in-memory transactions
1283 LOCK(pool.cs); // protect pool.mapNextTx
1284 for (unsigned int i = 0; i < tx.vin.size(); i++)
1286 COutPoint outpoint = tx.vin[i].prevout;
1287 if (pool.mapNextTx.count(outpoint))
1289 static uint32_t counter;
1290 // Disable replacement feature for now
1291 //if ( counter++ < 100 )
1292 fprintf(stderr,"Disable replacement feature for now\n");
1296 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit)
1298 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers)
1300 if (pool.mapNullifiers.count(nf))
1302 fprintf(stderr,"pool.mapNullifiers.count\n");
1311 CCoinsViewCache view(&dummy);
1313 CAmount nValueIn = 0;
1316 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1317 view.SetBackend(viewMemPool);
1319 // do we already have it?
1320 if (view.HaveCoins(hash))
1322 fprintf(stderr,"view.HaveCoins(hash) error\n");
1326 // do all inputs exist?
1327 // Note that this does not check for the presence of actual outputs (see the next check for that),
1328 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1329 BOOST_FOREACH(const CTxIn txin, tx.vin)
1331 if (!view.HaveCoins(txin.prevout.hash))
1333 if (pfMissingInputs)
1334 *pfMissingInputs = true;
1335 //fprintf(stderr,"missing inputs\n");
1340 // are the actual inputs available?
1341 if (!view.HaveInputs(tx))
1343 //fprintf(stderr,"accept failure.1\n");
1344 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent");
1346 // are the joinsplit's requirements met?
1347 if (!view.HaveJoinSplitRequirements(tx))
1349 //fprintf(stderr,"accept failure.2\n");
1350 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1353 // Bring the best block into scope
1354 view.GetBestBlock();
1356 nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
1357 if ( 0 && interest != 0 )
1358 fprintf(stderr,"add interest %.8f\n",(double)interest/COIN);
1359 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1360 view.SetBackend(dummy);
1363 // Check for non-standard pay-to-script-hash in inputs
1364 if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId))
1365 return error("AcceptToMemoryPool: reject nonstandard transaction input");
1367 // Check that the transaction doesn't have an excessive number of
1368 // sigops, making it impossible to mine. Since the coinbase transaction
1369 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1370 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1371 // merely non-standard transaction.
1372 unsigned int nSigOps = GetLegacySigOpCount(tx);
1373 nSigOps += GetP2SHSigOpCount(tx, view);
1374 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1376 fprintf(stderr,"accept failure.4\n");
1377 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");
1380 CAmount nValueOut = tx.GetValueOut();
1381 CAmount nFees = nValueIn-nValueOut;
1382 double dPriority = view.GetPriority(tx, chainActive.Height());
1384 // Keep track of transactions that spend a coinbase, which we re-scan
1385 // during reorgs to ensure COINBASE_MATURITY is still met.
1386 bool fSpendsCoinbase = false;
1387 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1388 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1389 if (coins->IsCoinBase()) {
1390 fSpendsCoinbase = true;
1395 // Grab the branch ID we expect this transaction to commit to. We don't
1396 // yet know if it does, but if the entry gets added to the mempool, then
1397 // it has passed ContextualCheckInputs and therefore this is correct.
1398 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1400 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
1401 unsigned int nSize = entry.GetTxSize();
1403 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1404 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1405 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1407 // Don't accept it if it can't get into a block
1408 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1409 if (fLimitFree && nFees < txMinFee)
1411 fprintf(stderr,"accept failure.5\n");
1412 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee");
1416 // Require that free transactions have sufficient priority to be mined in the next block.
1417 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1418 fprintf(stderr,"accept failure.6\n");
1419 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1422 // Continuously rate-limit free (really, very-low-fee) transactions
1423 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1424 // be annoying or make others' transactions take longer to confirm.
1425 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1427 static CCriticalSection csFreeLimiter;
1428 static double dFreeCount;
1429 static int64_t nLastTime;
1430 int64_t nNow = GetTime();
1432 LOCK(csFreeLimiter);
1434 // Use an exponentially decaying ~10-minute window:
1435 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1437 // -limitfreerelay unit is thousand-bytes-per-minute
1438 // At default rate it would take over a month to fill 1GB
1439 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1441 fprintf(stderr,"accept failure.7\n");
1442 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1444 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1445 dFreeCount += nSize;
1448 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000 && nFees > nValueOut/19 )
1450 fprintf(stderr,"accept failure.8\n");
1451 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1454 // Check against previous transactions
1455 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1456 PrecomputedTransactionData txdata(tx);
1457 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1459 //fprintf(stderr,"accept failure.9\n");
1460 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1463 // Check again against just the consensus-critical mandatory script
1464 // verification flags, in case of bugs in the standard flags that cause
1465 // transactions to pass as valid when they're actually invalid. For
1466 // instance the STRICTENC flag was incorrectly allowing certain
1467 // CHECKSIG NOT scripts to pass, even though they were invalid.
1469 // There is a similar check in CreateNewBlock() to prevent creating
1470 // invalid blocks, however allowing such transactions into the mempool
1471 // can be exploited as a DoS attack.
1472 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1474 fprintf(stderr,"accept failure.10\n");
1475 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1478 // Store transaction in memory
1479 if ( komodo_is_notarytx(tx) == 0 )
1481 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1484 SyncWithWallets(tx, NULL);
1489 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1490 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1492 CBlockIndex *pindexSlow = NULL;
1496 if (mempool.lookup(hash, txOut))
1503 if (pblocktree->ReadTxIndex(hash, postx)) {
1504 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1506 return error("%s: OpenBlockFile failed", __func__);
1507 CBlockHeader header;
1510 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1512 } catch (const std::exception& e) {
1513 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1515 hashBlock = header.GetHash();
1516 if (txOut.GetHash() != hash)
1517 return error("%s: txid mismatch", __func__);
1522 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1525 CCoinsViewCache &view = *pcoinsTip;
1526 const CCoins* coins = view.AccessCoins(hash);
1528 nHeight = coins->nHeight;
1531 pindexSlow = chainActive[nHeight];
1536 if (ReadBlockFromDisk(block, pindexSlow)) {
1537 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1538 if (tx.GetHash() == hash) {
1540 hashBlock = pindexSlow->GetBlockHash();
1550 /*char *komodo_getspendscript(uint256 hash,int32_t n)
1552 CTransaction tx; uint256 hashBlock;
1553 if ( !GetTransaction(hash,tx,hashBlock,true) )
1555 printf("null GetTransaction\n");
1558 if ( n >= 0 && n < tx.vout.size() )
1559 return((char *)tx.vout[n].scriptPubKey.ToString().c_str());
1560 else printf("getspendscript illegal n.%d\n",n);
1565 //////////////////////////////////////////////////////////////////////////////
1567 // CBlock and CBlockIndex
1570 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1572 // Open history file to append
1573 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1574 if (fileout.IsNull())
1575 return error("WriteBlockToDisk: OpenBlockFile failed");
1577 // Write index header
1578 unsigned int nSize = fileout.GetSerializeSize(block);
1579 fileout << FLATDATA(messageStart) << nSize;
1582 long fileOutPos = ftell(fileout.Get());
1584 return error("WriteBlockToDisk: ftell failed");
1585 pos.nPos = (unsigned int)fileOutPos;
1591 bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos)
1593 uint8_t pubkey33[33];
1596 // Open history file to read
1597 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1598 if (filein.IsNull())
1600 //fprintf(stderr,"readblockfromdisk err A\n");
1601 return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1608 catch (const std::exception& e) {
1609 fprintf(stderr,"readblockfromdisk err B\n");
1610 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1613 komodo_block2pubkey33(pubkey33,block);
1614 if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus())))
1616 int32_t i; for (i=0; i<33; i++)
1617 printf("%02x",pubkey33[i]);
1618 fprintf(stderr," warning unexpected diff at ht.%d\n",height);
1620 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1625 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1629 if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos()))
1631 if (block.GetHash() != pindex->GetBlockHash())
1632 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1633 pindex->ToString(), pindex->GetBlockPos().ToString());
1637 //uint64_t komodo_moneysupply(int32_t height);
1638 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
1639 extern uint32_t ASSETCHAINS_MAGIC;
1640 extern uint64_t ASSETCHAINS_STAKED,ASSETCHAINS_ENDSUBSIDY,ASSETCHAINS_REWARD,ASSETCHAINS_HALVING,ASSETCHAINS_LINEAR,ASSETCHAINS_COMMISSION,ASSETCHAINS_SUPPLY;
1642 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1644 static uint64_t cached_subsidy; static int32_t cached_numhalvings;
1645 int32_t numhalvings,i; uint64_t numerator; CAmount nSubsidy = 3 * COIN;
1646 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1649 return(100000000 * COIN); // ICO allocation
1650 else if ( nHeight < KOMODO_ENDOFERA ) //komodo_moneysupply(nHeight) < MAX_MONEY )
1657 return(ASSETCHAINS_SUPPLY * COIN + (ASSETCHAINS_MAGIC & 0xffffff));
1658 else if ( ASSETCHAINS_ENDSUBSIDY == 0 || nHeight < ASSETCHAINS_ENDSUBSIDY )
1660 if ( ASSETCHAINS_REWARD == 0 )
1662 else if ( ASSETCHAINS_ENDSUBSIDY != 0 && nHeight >= ASSETCHAINS_ENDSUBSIDY )
1666 nSubsidy = ASSETCHAINS_REWARD;
1667 if ( ASSETCHAINS_HALVING != 0 )
1669 if ( (numhalvings= (nHeight / ASSETCHAINS_HALVING)) > 0 )
1671 if ( numhalvings >= 64 && ASSETCHAINS_DECAY == 0 )
1673 if ( ASSETCHAINS_DECAY == 0 )
1674 nSubsidy >>= numhalvings;
1675 else if ( ASSETCHAINS_DECAY == 100000000 && ASSETCHAINS_ENDSUBSIDY != 0 )
1677 numerator = (ASSETCHAINS_ENDSUBSIDY - nHeight);
1678 nSubsidy = (nSubsidy * numerator) / ASSETCHAINS_ENDSUBSIDY;
1682 if ( cached_subsidy > 0 && cached_numhalvings == numhalvings )
1683 nSubsidy = cached_subsidy;
1686 for (i=0; i<numhalvings&&nSubsidy!=0; i++)
1687 nSubsidy = (nSubsidy * ASSETCHAINS_DECAY) / 100000000;
1688 cached_subsidy = nSubsidy;
1689 cached_numhalvings = numhalvings;
1699 // Mining slow start
1700 // The subsidy is ramped up linearly, skipping the middle payout of
1701 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1702 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1703 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1704 nSubsidy *= nHeight;
1706 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1707 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1708 nSubsidy *= (nHeight+1);
1712 assert(nHeight > consensusParams.SubsidySlowStartShift());
1713 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/
1714 // Force block reward to zero when right shift is undefined.
1715 //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1716 //if (halvings >= 64)
1719 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1720 //nSubsidy >>= halvings;
1724 bool IsInitialBlockDownload()
1726 const CChainParams& chainParams = Params();
1728 if (fImporting || fReindex)
1730 //fprintf(stderr,"IsInitialBlockDownload: fImporting %d || %d fReindex\n",(int32_t)fImporting,(int32_t)fReindex);
1733 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1735 //fprintf(stderr,"IsInitialBlockDownload: checkpoint -> initialdownload\n");
1738 static bool lockIBDState = false;
1741 //fprintf(stderr,"lockIBDState true %d < %d\n",chainActive.Height(),pindexBestHeader->nHeight - 10);
1744 bool state; CBlockIndex *ptr = chainActive.Tip();
1746 ptr = pindexBestHeader;
1747 else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight )
1748 ptr = pindexBestHeader;
1749 //if ( ASSETCHAINS_SYMBOL[0] == 0 )
1750 state = ((chainActive.Height() < ptr->nHeight - 24*60) ||
1751 ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge()));
1752 //else state = (chainActive.Height() < ptr->nHeight - 24*60);
1753 //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()));
1756 lockIBDState = true;
1761 bool fLargeWorkForkFound = false;
1762 bool fLargeWorkInvalidChainFound = false;
1763 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1765 void CheckForkWarningConditions()
1767 AssertLockHeld(cs_main);
1768 // Before we get past initial download, we cannot reliably alert about forks
1769 // (we assume we don't get stuck on a fork before the last checkpoint)
1770 if (IsInitialBlockDownload())
1773 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1774 // of our head, drop it
1775 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1776 pindexBestForkTip = NULL;
1778 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1780 if (!fLargeWorkForkFound && pindexBestForkBase)
1782 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1783 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1784 CAlert::Notify(warning, true);
1786 if (pindexBestForkTip && pindexBestForkBase)
1788 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__,
1789 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1790 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1791 fLargeWorkForkFound = true;
1795 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1796 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1797 CAlert::Notify(warning, true);
1798 fLargeWorkInvalidChainFound = true;
1803 fLargeWorkForkFound = false;
1804 fLargeWorkInvalidChainFound = false;
1808 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1810 AssertLockHeld(cs_main);
1811 // If we are on a fork that is sufficiently large, set a warning flag
1812 CBlockIndex* pfork = pindexNewForkTip;
1813 CBlockIndex* plonger = chainActive.Tip();
1814 while (pfork && pfork != plonger)
1816 while (plonger && plonger->nHeight > pfork->nHeight)
1817 plonger = plonger->pprev;
1818 if (pfork == plonger)
1820 pfork = pfork->pprev;
1823 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1824 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1825 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1826 // hash rate operating on the fork.
1827 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1828 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1829 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1830 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1831 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1832 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1834 pindexBestForkTip = pindexNewForkTip;
1835 pindexBestForkBase = pfork;
1838 CheckForkWarningConditions();
1841 // Requires cs_main.
1842 void Misbehaving(NodeId pnode, int howmuch)
1847 CNodeState *state = State(pnode);
1851 state->nMisbehavior += howmuch;
1852 int banscore = GetArg("-banscore", 100);
1853 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1855 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1856 state->fShouldBan = true;
1858 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1861 void static InvalidChainFound(CBlockIndex* pindexNew)
1863 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1864 pindexBestInvalid = pindexNew;
1866 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1867 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1868 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1869 pindexNew->GetBlockTime()));
1870 CBlockIndex *tip = chainActive.Tip();
1872 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1873 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1874 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1875 CheckForkWarningConditions();
1878 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1880 if (state.IsInvalid(nDoS)) {
1881 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1882 if (it != mapBlockSource.end() && State(it->second)) {
1883 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1884 State(it->second)->rejects.push_back(reject);
1886 Misbehaving(it->second, nDoS);
1889 if (!state.CorruptionPossible()) {
1890 pindex->nStatus |= BLOCK_FAILED_VALID;
1891 setDirtyBlockIndex.insert(pindex);
1892 setBlockIndexCandidates.erase(pindex);
1893 InvalidChainFound(pindex);
1897 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1899 if (!tx.IsCoinBase()) // mark inputs spent
1901 txundo.vprevout.reserve(tx.vin.size());
1902 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1903 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1904 unsigned nPos = txin.prevout.n;
1906 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1908 // mark an outpoint spent, and construct undo information
1909 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1911 if (coins->vout.size() == 0) {
1912 CTxInUndo& undo = txundo.vprevout.back();
1913 undo.nHeight = coins->nHeight;
1914 undo.fCoinBase = coins->fCoinBase;
1915 undo.nVersion = coins->nVersion;
1919 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { // spend nullifiers
1920 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1921 inputs.SetNullifier(nf, true);
1924 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); // add outputs
1927 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1930 UpdateCoins(tx, inputs, txundo, nHeight);
1933 bool CScriptCheck::operator()() {
1934 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1935 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, ServerTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) {
1936 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1941 int GetSpendHeight(const CCoinsViewCache& inputs)
1944 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1945 return pindexPrev->nHeight + 1;
1948 namespace Consensus {
1949 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1951 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1952 // for an attacker to attempt to split the network.
1953 if (!inputs.HaveInputs(tx))
1954 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1956 // are the JoinSplit's requirements met?
1957 if (!inputs.HaveJoinSplitRequirements(tx))
1958 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1960 CAmount nValueIn = 0;
1962 for (unsigned int i = 0; i < tx.vin.size(); i++)
1964 const COutPoint &prevout = tx.vin[i].prevout;
1965 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1968 if (coins->IsCoinBase()) {
1969 // Ensure that coinbases are matured
1970 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1971 return state.Invalid(
1972 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1973 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1976 // Ensure that coinbases cannot be spent to transparent outputs
1977 // Disabled on regtest
1978 if (fCoinbaseEnforcedProtectionEnabled &&
1979 consensusParams.fCoinbaseMustBeProtected &&
1981 return state.Invalid(
1982 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1983 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1987 // Check for negative or overflow input values
1988 nValueIn += coins->vout[prevout.n].nValue;
1989 #ifdef KOMODO_ENABLE_INTEREST
1990 if ( ASSETCHAINS_SYMBOL[0] == 0 && nSpendHeight > 60000 )//chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 )
1992 if ( coins->vout[prevout.n].nValue >= 10*COIN )
1994 int64_t interest; int32_t txheight; uint32_t locktime;
1995 if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue,(int32_t)nSpendHeight-1)) != 0 )
1997 //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);
1998 nValueIn += interest;
2003 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
2004 return state.DoS(100, error("CheckInputs(): txin values out of range"),
2005 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2009 nValueIn += tx.GetJoinSplitValueIn();
2010 if (!MoneyRange(nValueIn))
2011 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
2012 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2014 if (nValueIn < tx.GetValueOut())
2016 fprintf(stderr,"spentheight.%d valuein %s vs %s error\n",nSpendHeight,FormatMoney(nValueIn).c_str(), FormatMoney(tx.GetValueOut()).c_str());
2017 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f",
2018 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout");
2020 // Tally transaction fees
2021 CAmount nTxFee = nValueIn - tx.GetValueOut();
2023 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
2024 REJECT_INVALID, "bad-txns-fee-negative");
2026 if (!MoneyRange(nFees))
2027 return state.DoS(100, error("CheckInputs(): nFees out of range"),
2028 REJECT_INVALID, "bad-txns-fee-outofrange");
2031 }// namespace Consensus
2033 bool ContextualCheckInputs(
2034 const CTransaction& tx,
2035 CValidationState &state,
2036 const CCoinsViewCache &inputs,
2040 PrecomputedTransactionData& txdata,
2041 const Consensus::Params& consensusParams,
2042 uint32_t consensusBranchId,
2043 std::vector<CScriptCheck> *pvChecks)
2045 if (!tx.IsCoinBase())
2047 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
2052 pvChecks->reserve(tx.vin.size());
2054 // The first loop above does all the inexpensive checks.
2055 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
2056 // Helps prevent CPU exhaustion attacks.
2058 // Skip ECDSA signature verification when connecting blocks
2059 // before the last block chain checkpoint. This is safe because block merkle hashes are
2060 // still computed and checked, and any change will be caught at the next checkpoint.
2061 if (fScriptChecks) {
2062 for (unsigned int i = 0; i < tx.vin.size(); i++) {
2063 const COutPoint &prevout = tx.vin[i].prevout;
2064 const CCoins* coins = inputs.AccessCoins(prevout.hash);
2068 CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata);
2070 pvChecks->push_back(CScriptCheck());
2071 check.swap(pvChecks->back());
2072 } else if (!check()) {
2073 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2074 // Check whether the failure was caused by a
2075 // non-mandatory script verification check, such as
2076 // non-standard DER encodings or non-null dummy
2077 // arguments; if so, don't trigger DoS protection to
2078 // avoid splitting the network between upgraded and
2079 // non-upgraded nodes.
2080 CScriptCheck check2(*coins, tx, i,
2081 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata);
2083 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
2085 // Failures of other flags indicate a transaction that is
2086 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
2087 // such nodes as they are not following the protocol. That
2088 // said during an upgrade careful thought should be taken
2089 // as to the correct behavior - we may want to continue
2090 // peering with non-upgraded nodes even after a soft-fork
2091 // super-majority vote has passed.
2092 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
2102 /*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)
2104 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
2105 fprintf(stderr,"ContextualCheckInputs failure.0\n");
2109 if (!tx.IsCoinBase())
2111 // While checking, GetBestBlock() refers to the parent block.
2112 // This is also true for mempool checks.
2113 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
2114 int nSpendHeight = pindexPrev->nHeight + 1;
2115 for (unsigned int i = 0; i < tx.vin.size(); i++)
2117 const COutPoint &prevout = tx.vin[i].prevout;
2118 const CCoins *coins = inputs.AccessCoins(prevout.hash);
2119 // Assertion is okay because NonContextualCheckInputs ensures the inputs
2123 // If prev is coinbase, check that it's matured
2124 if (coins->IsCoinBase()) {
2125 if ( ASSETCHAINS_SYMBOL[0] == 0 )
2126 COINBASE_MATURITY = _COINBASE_MATURITY;
2127 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
2128 fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size());
2130 return state.Invalid(
2131 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
2142 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
2144 // Open history file to append
2145 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
2146 if (fileout.IsNull())
2147 return error("%s: OpenUndoFile failed", __func__);
2149 // Write index header
2150 unsigned int nSize = fileout.GetSerializeSize(blockundo);
2151 fileout << FLATDATA(messageStart) << nSize;
2154 long fileOutPos = ftell(fileout.Get());
2156 return error("%s: ftell failed", __func__);
2157 pos.nPos = (unsigned int)fileOutPos;
2158 fileout << blockundo;
2160 // calculate & write checksum
2161 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2162 hasher << hashBlock;
2163 hasher << blockundo;
2164 fileout << hasher.GetHash();
2169 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
2171 // Open history file to read
2172 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
2173 if (filein.IsNull())
2174 return error("%s: OpenBlockFile failed", __func__);
2177 uint256 hashChecksum;
2179 filein >> blockundo;
2180 filein >> hashChecksum;
2182 catch (const std::exception& e) {
2183 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2187 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2188 hasher << hashBlock;
2189 hasher << blockundo;
2190 if (hashChecksum != hasher.GetHash())
2191 return error("%s: Checksum mismatch", __func__);
2196 /** Abort with a message */
2197 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2199 strMiscWarning = strMessage;
2200 LogPrintf("*** %s\n", strMessage);
2201 uiInterface.ThreadSafeMessageBox(
2202 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2203 "", CClientUIInterface::MSG_ERROR);
2208 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2210 AbortNode(strMessage, userMessage);
2211 return state.Error(strMessage);
2217 * Apply the undo operation of a CTxInUndo to the given chain state.
2218 * @param undo The undo object.
2219 * @param view The coins view to which to apply the changes.
2220 * @param out The out point that corresponds to the tx input.
2221 * @return True on success.
2223 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2227 CCoinsModifier coins = view.ModifyCoins(out.hash);
2228 if (undo.nHeight != 0) {
2229 // undo data contains height: this is the last output of the prevout tx being spent
2230 if (!coins->IsPruned())
2231 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2233 coins->fCoinBase = undo.fCoinBase;
2234 coins->nHeight = undo.nHeight;
2235 coins->nVersion = undo.nVersion;
2237 if (coins->IsPruned())
2238 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2240 if (coins->IsAvailable(out.n))
2241 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2242 if (coins->vout.size() < out.n+1)
2243 coins->vout.resize(out.n+1);
2244 coins->vout[out.n] = undo.txout;
2249 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2251 assert(pindex->GetBlockHash() == view.GetBestBlock());
2257 komodo_disconnect(pindex,block);
2258 CBlockUndo blockUndo;
2259 CDiskBlockPos pos = pindex->GetUndoPos();
2261 return error("DisconnectBlock(): no undo data available");
2262 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2263 return error("DisconnectBlock(): failure reading undo data");
2265 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2266 return error("DisconnectBlock(): block and undo data inconsistent");
2268 // undo transactions in reverse order
2269 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2270 const CTransaction &tx = block.vtx[i];
2271 uint256 hash = tx.GetHash();
2273 // Check that all outputs are available and match the outputs in the block itself
2276 CCoinsModifier outs = view.ModifyCoins(hash);
2277 outs->ClearUnspendable();
2279 CCoins outsBlock(tx, pindex->nHeight);
2280 // The CCoins serialization does not serialize negative numbers.
2281 // No network rules currently depend on the version here, so an inconsistency is harmless
2282 // but it must be corrected before txout nversion ever influences a network rule.
2283 if (outsBlock.nVersion < 0)
2284 outs->nVersion = outsBlock.nVersion;
2285 if (*outs != outsBlock)
2286 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2292 // unspend nullifiers
2293 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2294 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2295 view.SetNullifier(nf, false);
2300 if (i > 0) { // not coinbases
2301 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2302 if (txundo.vprevout.size() != tx.vin.size())
2303 return error("DisconnectBlock(): transaction and undo data inconsistent");
2304 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2305 const COutPoint &out = tx.vin[j].prevout;
2306 const CTxInUndo &undo = txundo.vprevout[j];
2307 if (!ApplyTxInUndo(undo, view, out))
2313 // set the old best anchor back
2314 view.PopAnchor(blockUndo.old_tree_root);
2316 // move best block pointer to prevout block
2317 view.SetBestBlock(pindex->pprev->GetBlockHash());
2327 void static FlushBlockFile(bool fFinalize = false)
2329 LOCK(cs_LastBlockFile);
2331 CDiskBlockPos posOld(nLastBlockFile, 0);
2333 FILE *fileOld = OpenBlockFile(posOld);
2336 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2337 FileCommit(fileOld);
2341 fileOld = OpenUndoFile(posOld);
2344 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2345 FileCommit(fileOld);
2350 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2352 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2354 void ThreadScriptCheck() {
2355 RenameThread("zcash-scriptch");
2356 scriptcheckqueue.Thread();
2360 // Called periodically asynchronously; alerts if it smells like
2361 // we're being fed a bad chain (blocks being generated much
2362 // too slowly or too quickly).
2364 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2365 int64_t nPowTargetSpacing)
2367 if (bestHeader == NULL || initialDownloadCheck()) return;
2369 static int64_t lastAlertTime = 0;
2370 int64_t now = GetAdjustedTime();
2371 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2373 const int SPAN_HOURS=4;
2374 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2375 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2377 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2379 std::string strWarning;
2380 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2383 const CBlockIndex* i = bestHeader;
2385 while (i->GetBlockTime() >= startTime) {
2388 if (i == NULL) return; // Ran out of chain, we must not be fully synced
2391 // How likely is it to find that many by chance?
2392 double p = boost::math::pdf(poisson, nBlocks);
2394 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2395 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2397 // Aim for one false-positive about every fifty years of normal running:
2398 const int FIFTY_YEARS = 50*365*24*60*60;
2399 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2401 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2403 // Many fewer blocks than expected: alert!
2404 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2405 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2407 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2409 // Many more blocks than expected: alert!
2410 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2411 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2413 if (!strWarning.empty())
2415 strMiscWarning = strWarning;
2416 CAlert::Notify(strWarning, true);
2417 lastAlertTime = now;
2421 static int64_t nTimeVerify = 0;
2422 static int64_t nTimeConnect = 0;
2423 static int64_t nTimeIndex = 0;
2424 static int64_t nTimeCallbacks = 0;
2425 static int64_t nTimeTotal = 0;
2427 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2429 const CChainParams& chainparams = Params();
2430 //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight);
2431 AssertLockHeld(cs_main);
2432 bool fExpensiveChecks = true;
2433 if (fCheckpointsEnabled) {
2434 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2435 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2436 // This block is an ancestor of a checkpoint: disable script checks
2437 fExpensiveChecks = false;
2440 auto verifier = libzcash::ProofVerifier::Strict();
2441 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2443 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2444 if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2447 // verify that the view's current state corresponds to the previous block
2448 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2449 assert(hashPrevBlock == view.GetBestBlock());
2451 // Special case for the genesis block, skipping connection of its transactions
2452 // (its coinbase is unspendable)
2453 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2455 view.SetBestBlock(pindex->GetBlockHash());
2456 // Before the genesis block, there was an empty tree
2457 ZCIncrementalMerkleTree tree;
2458 pindex->hashAnchor = tree.root();
2459 // The genesis block contained no JoinSplits
2460 pindex->hashAnchorEnd = pindex->hashAnchor;
2465 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2466 //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet"
2468 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2469 // unless those are already completely spent.
2470 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2471 const CCoins* coins = view.AccessCoins(tx.GetHash());
2472 if (coins && !coins->IsPruned())
2473 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2474 REJECT_INVALID, "bad-txns-BIP30");
2477 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2479 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2481 CBlockUndo blockundo;
2483 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2485 int64_t nTimeStart = GetTimeMicros();
2488 int64_t interest,sum = 0;
2489 unsigned int nSigOps = 0;
2490 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2491 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2492 vPos.reserve(block.vtx.size());
2493 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2495 // Construct the incremental merkle tree at the current
2497 auto old_tree_root = view.GetBestAnchor();
2498 // saving the top anchor in the block index as we go.
2500 pindex->hashAnchor = old_tree_root;
2502 ZCIncrementalMerkleTree tree;
2503 // This should never fail: we should always be able to get the root
2504 // that is on the tip of our chain
2505 assert(view.GetAnchorAt(old_tree_root, tree));
2508 // Consistency check: the root of the tree we're given should
2509 // match what we asked for.
2510 assert(tree.root() == old_tree_root);
2513 // Grab the consensus branch ID for the block's height
2514 auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus());
2516 std::vector<PrecomputedTransactionData> txdata;
2517 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2518 for (unsigned int i = 0; i < block.vtx.size(); i++)
2520 const CTransaction &tx = block.vtx[i];
2521 nInputs += tx.vin.size();
2522 nSigOps += GetLegacySigOpCount(tx);
2523 if (nSigOps > MAX_BLOCK_SIGOPS)
2524 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2525 REJECT_INVALID, "bad-blk-sigops");
2526 //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
2527 if (!tx.IsCoinBase())
2529 if (!view.HaveInputs(tx))
2530 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2531 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2533 // are the JoinSplit's requirements met?
2534 if (!view.HaveJoinSplitRequirements(tx))
2535 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2536 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2538 // Add in sigops done by pay-to-script-hash inputs;
2539 // this is to prevent a "rogue miner" from creating
2540 // an incredibly-expensive-to-validate block.
2541 nSigOps += GetP2SHSigOpCount(tx, view);
2542 if (nSigOps > MAX_BLOCK_SIGOPS)
2543 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2544 REJECT_INVALID, "bad-blk-sigops");
2547 txdata.emplace_back(tx);
2549 if (!tx.IsCoinBase())
2551 nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
2554 std::vector<CScriptCheck> vChecks;
2555 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL))
2557 control.Add(vChecks);
2559 //if ( ASSETCHAINS_SYMBOL[0] == 0 )
2560 // komodo_earned_interest(pindex->nHeight,sum);
2563 blockundo.vtxundo.push_back(CTxUndo());
2565 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2567 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2568 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2569 // Insert the note commitments into our temporary tree.
2571 tree.append(note_commitment);
2575 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2576 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2579 view.PushAnchor(tree);
2581 pindex->hashAnchorEnd = tree.root();
2583 blockundo.old_tree_root = old_tree_root;
2585 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2586 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);
2588 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()) + sum;
2589 if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && block.vtx[0].vout.size() > 1 )
2591 uint64_t checktoshis;
2592 if ( (checktoshis = komodo_commission(block)) != 0 )
2594 if ( block.vtx[0].vout.size() == 2 && block.vtx[0].vout[1].nValue == checktoshis )
2595 blockReward += checktoshis;
2596 else fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(block.vtx[0].vout[1].nValue));
2599 if ( block.vtx[0].GetValueOut() > blockReward+1 )
2601 if ( ASSETCHAINS_SYMBOL[0] != 0 || pindex->nHeight >= KOMODO_NOTARIES_HEIGHT1 || block.vtx[0].vout[0].nValue > blockReward )
2603 return state.DoS(100,
2604 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2605 block.vtx[0].GetValueOut(), blockReward),
2606 REJECT_INVALID, "bad-cb-amount");
2607 } else if ( NOTARY_PUBKEY33[0] != 0 )
2608 fprintf(stderr,"allow nHeight.%d coinbase %.8f vs %.8f interest %.8f\n",(int32_t)pindex->nHeight,dstr(block.vtx[0].GetValueOut()),dstr(blockReward),dstr(sum));
2610 if (!control.Wait())
2611 return state.DoS(100, false);
2612 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2613 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);
2618 // Write undo information to disk
2619 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2621 if (pindex->GetUndoPos().IsNull()) {
2623 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2624 return error("ConnectBlock(): FindUndoPos failed");
2625 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2626 return AbortNode(state, "Failed to write undo data");
2628 // update nUndoPos in block index
2629 pindex->nUndoPos = pos.nPos;
2630 pindex->nStatus |= BLOCK_HAVE_UNDO;
2633 // Now that all consensus rules have been validated, set nCachedBranchId.
2634 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2635 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
2636 "nCachedBranchId must be set after all consensus rules have been validated.");
2637 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2638 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
2639 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
2640 } else if (pindex->pprev) {
2641 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
2644 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2645 setDirtyBlockIndex.insert(pindex);
2649 if (!pblocktree->WriteTxIndex(vPos))
2650 return AbortNode(state, "Failed to write transaction index");
2652 // add this block to the view's block chain
2653 view.SetBestBlock(pindex->GetBlockHash());
2655 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2656 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2658 // Watch for changes to the previous coinbase transaction.
2659 static uint256 hashPrevBestCoinBase;
2660 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2661 hashPrevBestCoinBase = block.vtx[0].GetHash();
2663 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2664 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2666 //FlushStateToDisk();
2667 komodo_connectblock(pindex,*(CBlock *)&block);
2671 enum FlushStateMode {
2673 FLUSH_STATE_IF_NEEDED,
2674 FLUSH_STATE_PERIODIC,
2679 * Update the on-disk chain state.
2680 * The caches and indexes are flushed depending on the mode we're called with
2681 * if they're too large, if it's been a while since the last write,
2682 * or always and in all cases if we're in prune mode and are deleting files.
2684 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2685 LOCK2(cs_main, cs_LastBlockFile);
2686 static int64_t nLastWrite = 0;
2687 static int64_t nLastFlush = 0;
2688 static int64_t nLastSetChain = 0;
2689 std::set<int> setFilesToPrune;
2690 bool fFlushForPrune = false;
2692 if (fPruneMode && fCheckForPruning && !fReindex) {
2693 FindFilesToPrune(setFilesToPrune);
2694 fCheckForPruning = false;
2695 if (!setFilesToPrune.empty()) {
2696 fFlushForPrune = true;
2698 pblocktree->WriteFlag("prunedblockfiles", true);
2703 int64_t nNow = GetTimeMicros();
2704 // Avoid writing/flushing immediately after startup.
2705 if (nLastWrite == 0) {
2708 if (nLastFlush == 0) {
2711 if (nLastSetChain == 0) {
2712 nLastSetChain = nNow;
2714 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2715 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2716 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2717 // The cache is over the limit, we have to write now.
2718 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2719 // 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.
2720 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2721 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2722 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2723 // Combine all conditions that result in a full cache flush.
2724 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2725 // Write blocks and block index to disk.
2726 if (fDoFullFlush || fPeriodicWrite) {
2727 // Depend on nMinDiskSpace to ensure we can write block index
2728 if (!CheckDiskSpace(0))
2729 return state.Error("out of disk space");
2730 // First make sure all block and undo data is flushed to disk.
2732 // Then update all block file information (which may refer to block and undo files).
2734 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2735 vFiles.reserve(setDirtyFileInfo.size());
2736 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2737 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2738 setDirtyFileInfo.erase(it++);
2740 std::vector<const CBlockIndex*> vBlocks;
2741 vBlocks.reserve(setDirtyBlockIndex.size());
2742 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2743 vBlocks.push_back(*it);
2744 setDirtyBlockIndex.erase(it++);
2746 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2747 return AbortNode(state, "Files to write to block index database");
2750 // Finally remove any pruned files
2752 UnlinkPrunedFiles(setFilesToPrune);
2755 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2757 // Typical CCoins structures on disk are around 128 bytes in size.
2758 // Pushing a new one to the database can cause it to be written
2759 // twice (once in the log, and once in the tables). This is already
2760 // an overestimation, as most will delete an existing entry or
2761 // overwrite one. Still, use a conservative safety factor of 2.
2762 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2763 return state.Error("out of disk space");
2764 // Flush the chainstate (which may refer to block index entries).
2765 if (!pcoinsTip->Flush())
2766 return AbortNode(state, "Failed to write to coin database");
2769 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2770 // Update best block in wallet (so we can detect restored wallets).
2771 GetMainSignals().SetBestChain(chainActive.GetLocator());
2772 nLastSetChain = nNow;
2774 } catch (const std::runtime_error& e) {
2775 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2780 void FlushStateToDisk() {
2781 CValidationState state;
2782 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2785 void PruneAndFlush() {
2786 CValidationState state;
2787 fCheckForPruning = true;
2788 FlushStateToDisk(state, FLUSH_STATE_NONE);
2791 /** Update chainActive and related internal data structures. */
2792 void static UpdateTip(CBlockIndex *pindexNew) {
2793 const CChainParams& chainParams = Params();
2794 chainActive.SetTip(pindexNew);
2797 nTimeBestReceived = GetTime();
2798 mempool.AddTransactionsUpdated(1);
2800 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2801 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2802 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2803 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2805 cvBlockChange.notify_all();
2807 // Check the version of the last 100 blocks to see if we need to upgrade:
2808 static bool fWarned = false;
2809 if (!IsInitialBlockDownload() && !fWarned)
2812 const CBlockIndex* pindex = chainActive.Tip();
2813 for (int i = 0; i < 100 && pindex != NULL; i++)
2815 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2817 pindex = pindex->pprev;
2820 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2821 if (nUpgraded > 100/2)
2823 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2824 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2825 CAlert::Notify(strMiscWarning, true);
2832 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2833 * mempool.removeWithoutBranchId after this, with cs_main held.
2835 bool static DisconnectTip(CValidationState &state, bool fBare = false) {
2836 CBlockIndex *pindexDelete = chainActive.Tip();
2837 assert(pindexDelete);
2838 // Read block from disk.
2840 if (!ReadBlockFromDisk(block, pindexDelete))
2841 return AbortNode(state, "Failed to read block");
2842 // Apply the block atomically to the chain state.
2843 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2844 int64_t nStart = GetTimeMicros();
2846 CCoinsViewCache view(pcoinsTip);
2847 if (!DisconnectBlock(block, state, pindexDelete, view))
2848 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2849 assert(view.Flush());
2851 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2852 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2853 // Write the chain state to disk, if necessary.
2854 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2858 // Resurrect mempool transactions from the disconnected block.
2859 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2860 // ignore validation errors in resurrected transactions
2861 list<CTransaction> removed;
2862 CValidationState stateDummy;
2863 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2864 mempool.remove(tx, removed, true);
2866 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2867 // The anchor may not change between block disconnects,
2868 // in which case we don't want to evict from the mempool yet!
2869 mempool.removeWithAnchor(anchorBeforeDisconnect);
2873 // Update chainActive and related variables.
2874 UpdateTip(pindexDelete->pprev);
2875 // Get the current commitment tree
2876 ZCIncrementalMerkleTree newTree;
2877 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2878 // Let wallets know transactions went from 1-confirmed to
2879 // 0-confirmed or conflicted:
2880 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2881 SyncWithWallets(tx, NULL);
2883 // Update cached incremental witnesses
2884 //fprintf(stderr,"chaintip false\n");
2885 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2889 static int64_t nTimeReadFromDisk = 0;
2890 static int64_t nTimeConnectTotal = 0;
2891 static int64_t nTimeFlush = 0;
2892 static int64_t nTimeChainState = 0;
2893 static int64_t nTimePostConnect = 0;
2896 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2897 * corresponding to pindexNew, to bypass loading it again from disk.
2898 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
2900 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2902 assert(pindexNew->pprev == chainActive.Tip());
2903 // Read block from disk.
2904 int64_t nTime1 = GetTimeMicros();
2907 if (!ReadBlockFromDisk(block, pindexNew))
2908 return AbortNode(state, "Failed to read block");
2911 // Get the current commitment tree
2912 ZCIncrementalMerkleTree oldTree;
2913 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2914 // Apply the block atomically to the chain state.
2915 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2917 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2919 CCoinsViewCache view(pcoinsTip);
2920 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2921 GetMainSignals().BlockChecked(*pblock, state);
2923 if (state.IsInvalid())
2924 InvalidBlockFound(pindexNew, state);
2925 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2927 mapBlockSource.erase(pindexNew->GetBlockHash());
2928 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2929 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2930 assert(view.Flush());
2932 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2933 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2934 // Write the chain state to disk, if necessary.
2935 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2937 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2938 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2939 // Remove conflicting transactions from the mempool.
2940 list<CTransaction> txConflicted;
2941 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2943 // Remove transactions that expire at new block height from mempool
2944 mempool.removeExpired(pindexNew->nHeight);
2946 // Update chainActive & related variables.
2947 UpdateTip(pindexNew);
2948 // Tell wallet about transactions that went from mempool
2950 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2951 SyncWithWallets(tx, NULL);
2953 // ... and about transactions that got confirmed:
2954 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2955 SyncWithWallets(tx, pblock);
2957 // Update cached incremental witnesses
2958 //fprintf(stderr,"chaintip true\n");
2959 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2961 EnforceNodeDeprecation(pindexNew->nHeight);
2963 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2964 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2965 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2970 * Return the tip of the chain with the most work in it, that isn't
2971 * known to be invalid (it's however far from certain to be valid).
2973 static CBlockIndex* FindMostWorkChain() {
2975 CBlockIndex *pindexNew = NULL;
2977 // Find the best candidate header.
2979 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2980 if (it == setBlockIndexCandidates.rend())
2985 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2986 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2987 CBlockIndex *pindexTest = pindexNew;
2988 bool fInvalidAncestor = false;
2989 while (pindexTest && !chainActive.Contains(pindexTest)) {
2990 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2992 // Pruned nodes may have entries in setBlockIndexCandidates for
2993 // which block files have been deleted. Remove those as candidates
2994 // for the most work chain if we come across them; we can't switch
2995 // to a chain unless we have all the non-active-chain parent blocks.
2996 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2997 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2998 if (fFailedChain || fMissingData) {
2999 // Candidate chain is not usable (either invalid or missing data)
3000 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
3001 pindexBestInvalid = pindexNew;
3002 CBlockIndex *pindexFailed = pindexNew;
3003 // Remove the entire chain from the set.
3004 while (pindexTest != pindexFailed) {
3006 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
3007 } else if (fMissingData) {
3008 // If we're missing data, then add back to mapBlocksUnlinked,
3009 // so that if the block arrives in the future we can try adding
3010 // to setBlockIndexCandidates again.
3011 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
3013 setBlockIndexCandidates.erase(pindexFailed);
3014 pindexFailed = pindexFailed->pprev;
3016 setBlockIndexCandidates.erase(pindexTest);
3017 fInvalidAncestor = true;
3020 pindexTest = pindexTest->pprev;
3022 if (!fInvalidAncestor)
3027 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
3028 static void PruneBlockIndexCandidates() {
3029 // Note that we can't delete the current block itself, as we may need to return to it later in case a
3030 // reorganization to a better block fails.
3031 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3032 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
3033 setBlockIndexCandidates.erase(it++);
3035 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3036 assert(!setBlockIndexCandidates.empty());
3040 * Try to make some progress towards making pindexMostWork the active block.
3041 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
3043 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
3044 AssertLockHeld(cs_main);
3045 bool fInvalidFound = false;
3046 const CBlockIndex *pindexOldTip = chainActive.Tip();
3047 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
3049 // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks.
3050 // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain,
3051 // then pindexFork will be null, and we would need to remove the entire chain including
3052 // our genesis block. In practice this (probably) won't happen because of checks elsewhere.
3053 auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0;
3054 static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance");
3055 if (reorgLength > MAX_REORG_LENGTH) {
3056 auto msg = strprintf(_(
3057 "A block chain reorganization has been detected that would roll back %d blocks! "
3058 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
3059 ), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
3060 _("Reorganization details") + ":\n" +
3061 "- " + strprintf(_("Current tip: %s, height %d, work %s"),
3062 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" +
3063 "- " + strprintf(_("New tip: %s, height %d, work %s"),
3064 pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" +
3065 "- " + strprintf(_("Fork point: %s, height %d"),
3066 pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" +
3067 _("Please help, human!");
3068 LogPrintf("*** %s\n", msg);
3069 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
3074 // Disconnect active blocks which are no longer in the best chain.
3075 bool fBlocksDisconnected = false;
3076 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
3077 if (!DisconnectTip(state))
3079 fBlocksDisconnected = true;
3081 if ( KOMODO_REWIND != 0 )
3083 fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.Tip()->nHeight,KOMODO_REWIND);
3084 while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND )
3086 fprintf(stderr,"%d ",(int32_t)chainActive.Tip()->nHeight);
3087 if ( !DisconnectTip(state) )
3089 InvalidateBlock(state,chainActive.Tip());
3093 fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli -ac_name=%s stop\n",KOMODO_REWIND,ASSETCHAINS_SYMBOL);
3095 fprintf(stderr,"resuming normal operations\n");
3099 // Build list of new blocks to connect.
3100 std::vector<CBlockIndex*> vpindexToConnect;
3101 bool fContinue = true;
3102 int nHeight = pindexFork ? pindexFork->nHeight : -1;
3103 while (fContinue && nHeight != pindexMostWork->nHeight) {
3104 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3105 // a few blocks along the way.
3106 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3107 vpindexToConnect.clear();
3108 vpindexToConnect.reserve(nTargetHeight - nHeight);
3109 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3110 while (pindexIter && pindexIter->nHeight != nHeight) {
3111 vpindexToConnect.push_back(pindexIter);
3112 pindexIter = pindexIter->pprev;
3114 nHeight = nTargetHeight;
3116 // Connect new blocks.
3117 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
3118 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
3119 if (state.IsInvalid()) {
3120 // The block violates a consensus rule.
3121 if (!state.CorruptionPossible())
3122 InvalidChainFound(vpindexToConnect.back());
3123 state = CValidationState();
3124 fInvalidFound = true;
3128 // A system error occurred (disk space, database error, ...).
3132 PruneBlockIndexCandidates();
3133 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
3134 // We're in a better position than we were. Return temporarily to release the lock.
3142 if (fBlocksDisconnected) {
3143 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3145 mempool.removeWithoutBranchId(
3146 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3147 mempool.check(pcoinsTip);
3149 // Callbacks/notifications for a new best chain.
3151 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
3153 CheckForkWarningConditions();
3159 * Make the best chain active, in multiple steps. The result is either failure
3160 * or an activated best chain. pblock is either NULL or a pointer to a block
3161 * that is already loaded (to avoid loading it again from disk).
3163 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
3164 CBlockIndex *pindexNewTip = NULL;
3165 CBlockIndex *pindexMostWork = NULL;
3166 const CChainParams& chainParams = Params();
3168 boost::this_thread::interruption_point();
3170 bool fInitialDownload;
3173 pindexMostWork = FindMostWorkChain();
3175 // Whether we have anything to do at all.
3176 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
3179 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
3181 pindexNewTip = chainActive.Tip();
3182 fInitialDownload = IsInitialBlockDownload();
3184 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3186 // Notifications/callbacks that can run without cs_main
3187 if (!fInitialDownload) {
3188 uint256 hashNewTip = pindexNewTip->GetBlockHash();
3189 // Relay inventory, but don't relay old inventory during initial block download.
3190 int nBlockEstimate = 0;
3191 if (fCheckpointsEnabled)
3192 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
3193 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
3194 // in a stalled download if the block file is pruned before the request.
3195 if (nLocalServices & NODE_NETWORK) {
3197 BOOST_FOREACH(CNode* pnode, vNodes)
3198 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
3199 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
3201 // Notify external listeners about the new tip.
3202 GetMainSignals().UpdatedBlockTip(pindexNewTip);
3203 uiInterface.NotifyBlockTip(hashNewTip);
3204 } //else fprintf(stderr,"initial download skips propagation\n");
3205 } while(pindexMostWork != chainActive.Tip());
3208 // Write changes periodically to disk, after relay.
3209 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
3216 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
3217 AssertLockHeld(cs_main);
3219 // Mark the block itself as invalid.
3220 pindex->nStatus |= BLOCK_FAILED_VALID;
3221 setDirtyBlockIndex.insert(pindex);
3222 setBlockIndexCandidates.erase(pindex);
3224 while (chainActive.Contains(pindex)) {
3225 CBlockIndex *pindexWalk = chainActive.Tip();
3226 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3227 setDirtyBlockIndex.insert(pindexWalk);
3228 setBlockIndexCandidates.erase(pindexWalk);
3229 // ActivateBestChain considers blocks already in chainActive
3230 // unconditionally valid already, so force disconnect away from it.
3231 if (!DisconnectTip(state)) {
3232 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3233 mempool.removeWithoutBranchId(
3234 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3238 //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
3240 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3242 BlockMap::iterator it = mapBlockIndex.begin();
3243 while (it != mapBlockIndex.end() && it->second != 0 ) {
3244 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3245 setBlockIndexCandidates.insert(it->second);
3250 InvalidChainFound(pindex);
3251 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3252 mempool.removeWithoutBranchId(
3253 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3257 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
3258 AssertLockHeld(cs_main);
3260 int nHeight = pindex->nHeight;
3262 // Remove the invalidity flag from this block and all its descendants.
3263 BlockMap::iterator it = mapBlockIndex.begin();
3264 while (it != mapBlockIndex.end()) {
3265 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3266 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3267 setDirtyBlockIndex.insert(it->second);
3268 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3269 setBlockIndexCandidates.insert(it->second);
3271 if (it->second == pindexBestInvalid) {
3272 // Reset invalid block marker if it was pointing to one of those.
3273 pindexBestInvalid = NULL;
3279 // Remove the invalidity flag from all ancestors too.
3280 while (pindex != NULL) {
3281 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3282 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3283 setDirtyBlockIndex.insert(pindex);
3285 pindex = pindex->pprev;
3290 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3292 // Check for duplicate
3293 uint256 hash = block.GetHash();
3294 BlockMap::iterator it = mapBlockIndex.find(hash);
3295 if (it != mapBlockIndex.end())
3298 // Construct new block index object
3299 CBlockIndex* pindexNew = new CBlockIndex(block);
3301 // We assign the sequence id to blocks only when the full data is available,
3302 // to avoid miners withholding blocks but broadcasting headers, to get a
3303 // competitive advantage.
3304 pindexNew->nSequenceId = 0;
3305 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3306 pindexNew->phashBlock = &((*mi).first);
3307 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3308 if (miPrev != mapBlockIndex.end())
3310 pindexNew->pprev = (*miPrev).second;
3311 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3312 pindexNew->BuildSkip();
3314 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3315 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3316 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3317 pindexBestHeader = pindexNew;
3319 setDirtyBlockIndex.insert(pindexNew);
3324 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3325 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3327 pindexNew->nTx = block.vtx.size();
3328 pindexNew->nChainTx = 0;
3329 CAmount sproutValue = 0;
3330 for (auto tx : block.vtx) {
3331 for (auto js : tx.vjoinsplit) {
3332 sproutValue += js.vpub_old;
3333 sproutValue -= js.vpub_new;
3336 pindexNew->nSproutValue = sproutValue;
3337 pindexNew->nChainSproutValue = boost::none;
3338 pindexNew->nFile = pos.nFile;
3339 pindexNew->nDataPos = pos.nPos;
3340 pindexNew->nUndoPos = 0;
3341 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3342 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3343 setDirtyBlockIndex.insert(pindexNew);
3345 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3346 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3347 deque<CBlockIndex*> queue;
3348 queue.push_back(pindexNew);
3350 // Recursively process any descendant blocks that now may be eligible to be connected.
3351 while (!queue.empty()) {
3352 CBlockIndex *pindex = queue.front();
3354 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3355 if (pindex->pprev) {
3356 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3357 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3359 pindex->nChainSproutValue = boost::none;
3362 pindex->nChainSproutValue = pindex->nSproutValue;
3365 LOCK(cs_nBlockSequenceId);
3366 pindex->nSequenceId = nBlockSequenceId++;
3368 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3369 setBlockIndexCandidates.insert(pindex);
3371 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3372 while (range.first != range.second) {
3373 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3374 queue.push_back(it->second);
3376 mapBlocksUnlinked.erase(it);
3380 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3381 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3388 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3390 LOCK(cs_LastBlockFile);
3392 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3393 if (vinfoBlockFile.size() <= nFile) {
3394 vinfoBlockFile.resize(nFile + 1);
3398 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3400 if (vinfoBlockFile.size() <= nFile) {
3401 vinfoBlockFile.resize(nFile + 1);
3405 pos.nPos = vinfoBlockFile[nFile].nSize;
3408 if (nFile != nLastBlockFile) {
3410 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3412 FlushBlockFile(!fKnown);
3413 nLastBlockFile = nFile;
3416 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3418 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3420 vinfoBlockFile[nFile].nSize += nAddSize;
3423 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3424 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3425 if (nNewChunks > nOldChunks) {
3427 fCheckForPruning = true;
3428 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3429 FILE *file = OpenBlockFile(pos);
3431 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3432 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3437 return state.Error("out of disk space");
3441 setDirtyFileInfo.insert(nFile);
3445 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3449 LOCK(cs_LastBlockFile);
3451 unsigned int nNewSize;
3452 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3453 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3454 setDirtyFileInfo.insert(nFile);
3456 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3457 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3458 if (nNewChunks > nOldChunks) {
3460 fCheckForPruning = true;
3461 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3462 FILE *file = OpenUndoFile(pos);
3464 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3465 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3470 return state.Error("out of disk space");
3476 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3478 uint8_t pubkey33[33];
3482 uint256 hash; int32_t i;
3483 hash = blockhdr.GetHash();
3484 for (i=31; i>=0; i--)
3485 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3486 fprintf(stderr," <- CheckBlockHeader\n");
3487 if ( chainActive.Tip() != 0 )
3489 hash = chainActive.Tip()->GetBlockHash();
3490 for (i=31; i>=0; i--)
3491 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3492 fprintf(stderr," <- chainTip\n");
3495 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3496 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3497 else if ( ASSETCHAINS_STAKED != 0 && pindex != 0 && pindex->pprev != 0 && pindex->nTime <= pindex->pprev->nTime )
3499 fprintf(stderr,"ht.%d %u vs ht.%d %u, is not monotonic\n",pindex->nHeight,pindex->nTime,pindex->pprev->nHeight,pindex->pprev->nTime);
3500 return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new");
3502 // Check block version
3503 //if (block.nVersion < MIN_BLOCK_VERSION)
3504 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3506 // Check Equihash solution is valid
3507 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3508 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3510 // Check proof of work matches claimed amount
3511 komodo_index2pubkey33(pubkey33,pindex,height);
3512 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3513 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3517 int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime);
3519 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
3520 libzcash::ProofVerifier& verifier,
3521 bool fCheckPOW, bool fCheckMerkleRoot)
3523 // These are checks that are independent of context.
3525 // Check that the header is valid (particularly PoW). This is mostly
3526 // redundant with the call in AcceptBlockHeader.
3527 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3530 // Check the merkle root.
3531 if (fCheckMerkleRoot) {
3533 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3534 if (block.hashMerkleRoot != hashMerkleRoot2)
3535 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3536 REJECT_INVALID, "bad-txnmrklroot", true);
3538 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3539 // of transactions in a block without affecting the merkle root of a block,
3540 // while still invalidating it.
3542 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3543 REJECT_INVALID, "bad-txns-duplicate", true);
3546 // All potential-corruption validation must be done before we do any
3547 // transaction validation, as otherwise we may mark the header as invalid
3548 // because we receive the wrong transactions for it.
3551 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3552 return state.DoS(100, error("CheckBlock(): size limits failed"),
3553 REJECT_INVALID, "bad-blk-length");
3555 // First transaction must be coinbase, the rest must not be
3556 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3557 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3558 REJECT_INVALID, "bad-cb-missing");
3559 for (unsigned int i = 1; i < block.vtx.size(); i++)
3560 if (block.vtx[i].IsCoinBase())
3561 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3562 REJECT_INVALID, "bad-cb-multiple");
3564 // Check transactions
3565 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3567 if ( komodo_validate_interest(tx,height == 0 ? komodo_block2height((CBlock *)&block) : height,block.nTime,1) < 0 )
3568 return error("CheckBlock: komodo_validate_interest failed");
3569 if (!CheckTransaction(tx, state, verifier))
3570 return error("CheckBlock(): CheckTransaction failed");
3572 unsigned int nSigOps = 0;
3573 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3575 nSigOps += GetLegacySigOpCount(tx);
3577 if (nSigOps > MAX_BLOCK_SIGOPS)
3578 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3579 REJECT_INVALID, "bad-blk-sigops", true);
3580 if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 )
3581 //if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block,pindex==0||pindex->pprev==0?0:pindex->pprev->nTime) < 0 )
3583 static uint32_t counter;
3584 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
3585 fprintf(stderr,"check deposit rejection\n");
3591 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3593 const CChainParams& chainParams = Params();
3594 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3595 uint256 hash = block.GetHash();
3596 if (hash == consensusParams.hashGenesisBlock)
3601 int nHeight = pindexPrev->nHeight+1;
3603 // Check proof of work
3604 if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3606 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3607 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3608 REJECT_INVALID, "bad-diffbits");
3611 // Check timestamp against prev
3612 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3613 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3614 REJECT_INVALID, "time-too-old");
3616 if (fCheckpointsEnabled)
3618 // Check that the block chain matches the known block chain up to a checkpoint
3619 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3621 CBlockIndex *heightblock = chainActive[nHeight];
3622 if ( heightblock != 0 && heightblock->GetBlockHash() == hash )
3624 //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight);
3626 } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3628 // Don't accept any forks from the main chain prior to last checkpoint
3629 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3630 int32_t notarized_height;
3631 if (pcheckpoint && nHeight > 1 && nHeight < pcheckpoint->nHeight )
3632 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3633 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3635 CBlockIndex *heightblock = chainActive[nHeight];
3636 if ( heightblock != 0 && heightblock->GetBlockHash() == hash )
3638 //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight);
3640 } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3643 // Reject block.nVersion < 4 blocks
3644 if (block.nVersion < 4)
3645 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3646 REJECT_OBSOLETE, "bad-version");
3651 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3653 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3654 const Consensus::Params& consensusParams = Params().GetConsensus();
3656 // Check that all transactions are finalized
3657 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3659 // Check transaction contextually against consensus rules at block height
3660 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3661 return false; // Failure reason has been set in validation state object
3664 int nLockTimeFlags = 0;
3665 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3666 ? pindexPrev->GetMedianTimePast()
3667 : block.GetBlockTime();
3668 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3669 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3673 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3674 // In Zcash this has been enforced since launch, except that the genesis
3675 // block didn't include the height in the coinbase (see Zcash protocol spec
3676 // section '6.8 Bitcoin Improvement Proposals').
3679 CScript expect = CScript() << nHeight;
3680 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3681 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3682 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3689 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3691 const CChainParams& chainparams = Params();
3692 AssertLockHeld(cs_main);
3693 // Check for duplicate
3694 uint256 hash = block.GetHash();
3695 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3696 CBlockIndex *pindex = NULL;
3697 if (miSelf != mapBlockIndex.end()) {
3698 // Block header is already known.
3699 pindex = miSelf->second;
3702 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3703 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3704 if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test
3706 if (!CheckBlockHeader(pindex->nHeight,pindex, block, state))
3708 pindex->nStatus |= BLOCK_FAILED_MASK;
3709 fprintf(stderr,"known block failing CheckBlockHeader %d\n",(int32_t)pindex->nHeight);
3712 CBlockIndex* pindexPrev = NULL;
3713 if (hash != chainparams.GetConsensus().hashGenesisBlock)
3715 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3716 if (mi == mapBlockIndex.end())
3718 pindex->nStatus |= BLOCK_FAILED_MASK;
3719 fprintf(stderr,"known block.%d failing to find prevblock\n",(int32_t)pindex->nHeight);
3720 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3722 pindexPrev = (*mi).second;
3723 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3725 pindex->nStatus |= BLOCK_FAILED_MASK;
3726 fprintf(stderr,"known block.%d found invalid prevblock\n",(int32_t)pindex->nHeight);
3727 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3730 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3732 pindex->nStatus |= BLOCK_FAILED_MASK;
3733 fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight);
3741 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3744 // Get prev block index
3745 CBlockIndex* pindexPrev = NULL;
3746 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3747 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3748 if (mi == mapBlockIndex.end())
3750 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3752 pindexPrev = (*mi).second;
3753 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3754 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3756 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3759 pindex = AddToBlockIndex(block);
3765 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3767 const CChainParams& chainparams = Params();
3768 AssertLockHeld(cs_main);
3770 CBlockIndex *&pindex = *ppindex;
3771 if (!AcceptBlockHeader(block, state, &pindex))
3775 fprintf(stderr,"AcceptBlock error null pindex\n");
3778 // Try to process all requested blocks that we don't have, but only
3779 // process an unrequested block if it's new and has enough work to
3780 // advance our tip, and isn't too many blocks ahead.
3781 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3782 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3783 // Blocks that are too out-of-order needlessly limit the effectiveness of
3784 // pruning, because pruning will not delete block files that contain any
3785 // blocks which are too close in height to the tip. Apply this test
3786 // regardless of whether pruning is enabled; it should generally be safe to
3787 // not process unrequested blocks.
3788 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3790 // TODO: deal better with return value and error conditions for duplicate
3791 // and unrequested blocks.
3792 if (fAlreadyHave) return true;
3793 if (!fRequested) { // If we didn't ask for it:
3794 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3795 if (!fHasMoreWork) return true; // Don't process less-work chains
3796 if (fTooFarAhead) return true; // Block height is too high
3799 // See method docstring for why this is always disabled
3800 auto verifier = libzcash::ProofVerifier::Disabled();
3801 if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3802 if (state.IsInvalid() && !state.CorruptionPossible()) {
3803 pindex->nStatus |= BLOCK_FAILED_VALID;
3804 setDirtyBlockIndex.insert(pindex);
3809 int nHeight = pindex->nHeight;
3811 // Write block to history file
3813 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3814 CDiskBlockPos blockPos;
3817 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3818 return error("AcceptBlock(): FindBlockPos failed");
3820 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3821 AbortNode(state, "Failed to write block");
3822 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3823 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3824 } catch (const std::runtime_error& e) {
3825 return AbortNode(state, std::string("System error: ") + e.what());
3828 if (fCheckForPruning)
3829 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3834 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3836 unsigned int nFound = 0;
3837 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3839 if (pstart->nVersion >= minVersion)
3841 pstart = pstart->pprev;
3843 return (nFound >= nRequired);
3846 void komodo_currentheight_set(int32_t height);
3848 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3850 // Preliminary checks
3852 auto verifier = libzcash::ProofVerifier::Disabled();
3853 if ( chainActive.Tip() != 0 )
3854 komodo_currentheight_set(chainActive.Tip()->nHeight);
3855 if ( ASSETCHAINS_SYMBOL[0] == 0 )
3856 checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3857 else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3860 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3861 fRequested |= fForceProcessing;
3864 Misbehaving(pfrom->GetId(), 1);
3865 return error("%s: CheckBlock FAILED", __func__);
3869 CBlockIndex *pindex = NULL;
3870 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3871 if (pindex && pfrom) {
3872 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3876 return error("%s: AcceptBlock FAILED", __func__);
3879 if (!ActivateBestChain(state, pblock))
3880 return error("%s: ActivateBestChain failed", __func__);
3885 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3887 AssertLockHeld(cs_main);
3888 assert(pindexPrev == chainActive.Tip());
3890 CCoinsViewCache viewNew(pcoinsTip);
3891 CBlockIndex indexDummy(block);
3892 indexDummy.pprev = pindexPrev;
3893 indexDummy.nHeight = pindexPrev->nHeight + 1;
3894 // JoinSplit proofs are verified in ConnectBlock
3895 auto verifier = libzcash::ProofVerifier::Disabled();
3897 // NOTE: CheckBlockHeader is called by CheckBlock
3898 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3900 fprintf(stderr,"TestBlockValidity failure A\n");
3903 if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3905 //fprintf(stderr,"TestBlockValidity failure B\n");
3908 if (!ContextualCheckBlock(block, state, pindexPrev))
3910 fprintf(stderr,"TestBlockValidity failure C\n");
3913 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3915 fprintf(stderr,"TestBlockValidity failure D\n");
3918 assert(state.IsValid());
3924 * BLOCK PRUNING CODE
3927 /* Calculate the amount of disk space the block & undo files currently use */
3928 uint64_t CalculateCurrentUsage()
3930 uint64_t retval = 0;
3931 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3932 retval += file.nSize + file.nUndoSize;
3937 /* Prune a block file (modify associated database entries)*/
3938 void PruneOneBlockFile(const int fileNumber)
3940 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3941 CBlockIndex* pindex = it->second;
3942 if (pindex->nFile == fileNumber) {
3943 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3944 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3946 pindex->nDataPos = 0;
3947 pindex->nUndoPos = 0;
3948 setDirtyBlockIndex.insert(pindex);
3950 // Prune from mapBlocksUnlinked -- any block we prune would have
3951 // to be downloaded again in order to consider its chain, at which
3952 // point it would be considered as a candidate for
3953 // mapBlocksUnlinked or setBlockIndexCandidates.
3954 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3955 while (range.first != range.second) {
3956 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3958 if (it->second == pindex) {
3959 mapBlocksUnlinked.erase(it);
3965 vinfoBlockFile[fileNumber].SetNull();
3966 setDirtyFileInfo.insert(fileNumber);
3970 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3972 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3973 CDiskBlockPos pos(*it, 0);
3974 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3975 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3976 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3980 /* Calculate the block/rev files that should be deleted to remain under target*/
3981 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3983 LOCK2(cs_main, cs_LastBlockFile);
3984 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3987 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3991 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3992 uint64_t nCurrentUsage = CalculateCurrentUsage();
3993 // We don't check to prune until after we've allocated new space for files
3994 // So we should leave a buffer under our target to account for another allocation
3995 // before the next pruning.
3996 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3997 uint64_t nBytesToPrune;
4000 if (nCurrentUsage + nBuffer >= nPruneTarget) {
4001 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
4002 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
4004 if (vinfoBlockFile[fileNumber].nSize == 0)
4007 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
4010 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
4011 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
4014 PruneOneBlockFile(fileNumber);
4015 // Queue up the files for removal
4016 setFilesToPrune.insert(fileNumber);
4017 nCurrentUsage -= nBytesToPrune;
4022 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
4023 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
4024 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
4025 nLastBlockWeCanPrune, count);
4028 bool CheckDiskSpace(uint64_t nAdditionalBytes)
4030 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
4032 // Check for nMinDiskSpace bytes (currently 50MB)
4033 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
4034 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
4039 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
4041 static int32_t didinit; long fsize,fpos; int32_t incr = 16*1024*1024;
4044 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
4045 boost::filesystem::create_directories(path.parent_path());
4046 FILE* file = fopen(path.string().c_str(), "rb+");
4047 if (!file && !fReadOnly)
4048 file = fopen(path.string().c_str(), "wb+");
4050 LogPrintf("Unable to open file %s\n", path.string());
4053 if ( didinit == 0 && strcmp(prefix,(char *)"blk") == 0 )
4056 fseek(file,0,SEEK_END);
4057 fsize = ftell(file);
4060 char *ignore = (char *)malloc(incr);
4064 while ( fread(ignore,1,incr,file) == incr )
4065 fprintf(stderr,".");
4067 fprintf(stderr,"loaded %ld bytes set fpos.%ld loading.%d\n",(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS);
4070 fseek(file,fpos,SEEK_SET);
4071 KOMODO_LOADINGBLOCKS = 0;
4075 if (fseek(file, pos.nPos, SEEK_SET)) {
4076 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
4084 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
4085 return OpenDiskFile(pos, "blk", fReadOnly);
4088 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
4089 return OpenDiskFile(pos, "rev", fReadOnly);
4092 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
4094 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
4097 CBlockIndex * InsertBlockIndex(uint256 hash)
4103 BlockMap::iterator mi = mapBlockIndex.find(hash);
4104 if (mi != mapBlockIndex.end())
4105 return (*mi).second;
4108 CBlockIndex* pindexNew = new CBlockIndex();
4110 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
4111 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
4112 pindexNew->phashBlock = &((*mi).first);
4117 bool static LoadBlockIndexDB()
4119 const CChainParams& chainparams = Params();
4120 if (!pblocktree->LoadBlockIndexGuts())
4123 boost::this_thread::interruption_point();
4125 // Calculate nChainWork
4126 vector<pair<int, CBlockIndex*> > vSortedByHeight;
4127 vSortedByHeight.reserve(mapBlockIndex.size());
4128 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4130 CBlockIndex* pindex = item.second;
4131 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
4133 sort(vSortedByHeight.begin(), vSortedByHeight.end());
4134 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
4136 CBlockIndex* pindex = item.second;
4137 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
4138 // We can link the chain of blocks for which we've received transactions at some point.
4139 // Pruned nodes may have deleted the block.
4140 if (pindex->nTx > 0) {
4141 if (pindex->pprev) {
4142 if (pindex->pprev->nChainTx) {
4143 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4144 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
4145 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
4147 pindex->nChainSproutValue = boost::none;
4150 pindex->nChainTx = 0;
4151 pindex->nChainSproutValue = boost::none;
4152 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
4155 pindex->nChainTx = pindex->nTx;
4156 pindex->nChainSproutValue = pindex->nSproutValue;
4159 // Construct in-memory chain of branch IDs.
4160 // Relies on invariant: a block that does not activate a network upgrade
4161 // will always be valid under the same consensus rules as its parent.
4162 // Genesis block has a branch ID of zero by definition, but has no
4163 // validity status because it is side-loaded into a fresh chain.
4164 // Activation blocks will have branch IDs set (read from disk).
4165 if (pindex->pprev) {
4166 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
4167 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
4170 pindex->nCachedBranchId = SPROUT_BRANCH_ID;
4172 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
4173 setBlockIndexCandidates.insert(pindex);
4174 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
4175 pindexBestInvalid = pindex;
4177 pindex->BuildSkip();
4178 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4179 pindexBestHeader = pindex;
4182 // Load block file info
4183 pblocktree->ReadLastBlockFile(nLastBlockFile);
4184 vinfoBlockFile.resize(nLastBlockFile + 1);
4185 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4186 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4187 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4189 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4190 for (int nFile = nLastBlockFile + 1; true; nFile++) {
4191 CBlockFileInfo info;
4192 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4193 vinfoBlockFile.push_back(info);
4199 // Check presence of blk files
4200 LogPrintf("Checking all blk files are present...\n");
4201 set<int> setBlkDataFiles;
4202 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4204 CBlockIndex* pindex = item.second;
4205 if (pindex->nStatus & BLOCK_HAVE_DATA) {
4206 setBlkDataFiles.insert(pindex->nFile);
4209 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4211 CDiskBlockPos pos(*it, 0);
4212 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4217 // Check whether we have ever pruned block & undo files
4218 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4220 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4222 // Check whether we need to continue reindexing
4223 bool fReindexing = false;
4224 pblocktree->ReadReindexing(fReindexing);
4225 fReindex |= fReindexing;
4227 // Check whether we have a transaction index
4228 pblocktree->ReadFlag("txindex", fTxIndex);
4229 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
4231 // Fill in-memory data
4232 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4234 CBlockIndex* pindex = item.second;
4235 // - This relationship will always be true even if pprev has multiple
4236 // children, because hashAnchor is technically a property of pprev,
4237 // not its children.
4238 // - This will miss chain tips; we handle the best tip below, and other
4239 // tips will be handled by ConnectTip during a re-org.
4240 if (pindex->pprev) {
4241 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
4245 // Load pointer to end of best chain
4246 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4247 if (it == mapBlockIndex.end())
4249 chainActive.SetTip(it->second);
4250 // Set hashAnchorEnd for the end of best chain
4251 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
4253 PruneBlockIndexCandidates();
4255 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
4256 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
4257 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4258 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
4260 EnforceNodeDeprecation(chainActive.Height(), true);
4265 CVerifyDB::CVerifyDB()
4267 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
4270 CVerifyDB::~CVerifyDB()
4272 uiInterface.ShowProgress("", 100);
4275 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4278 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
4281 // Verify blocks in the best chain
4282 if (nCheckDepth <= 0)
4283 nCheckDepth = 1000000000; // suffices until the year 19000
4284 if (nCheckDepth > chainActive.Height())
4285 nCheckDepth = chainActive.Height();
4286 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4287 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4288 CCoinsViewCache coins(coinsview);
4289 CBlockIndex* pindexState = chainActive.Tip();
4290 CBlockIndex* pindexFailure = NULL;
4291 int nGoodTransactions = 0;
4292 CValidationState state;
4293 // No need to verify JoinSplits twice
4294 auto verifier = libzcash::ProofVerifier::Disabled();
4295 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
4297 boost::this_thread::interruption_point();
4298 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
4299 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
4302 // check level 0: read from disk
4303 if (!ReadBlockFromDisk(block, pindex))
4304 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4305 // check level 1: verify block validity
4306 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier))
4307 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4308 // check level 2: verify undo validity
4309 if (nCheckLevel >= 2 && pindex) {
4311 CDiskBlockPos pos = pindex->GetUndoPos();
4312 if (!pos.IsNull()) {
4313 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
4314 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4317 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4318 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
4320 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
4321 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4322 pindexState = pindex->pprev;
4324 nGoodTransactions = 0;
4325 pindexFailure = pindex;
4327 nGoodTransactions += block.vtx.size();
4329 if (ShutdownRequested())
4333 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4335 // check level 4: try reconnecting blocks
4336 if (nCheckLevel >= 4) {
4337 CBlockIndex *pindex = pindexState;
4338 while (pindex != chainActive.Tip()) {
4339 boost::this_thread::interruption_point();
4340 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
4341 pindex = chainActive.Next(pindex);
4343 if (!ReadBlockFromDisk(block, pindex))
4344 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4345 if (!ConnectBlock(block, state, pindex, coins))
4346 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4350 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4355 bool RewindBlockIndex(const CChainParams& params)
4359 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
4360 // index will have nCachedBranchId set based on the values previously persisted
4361 // to disk. By definition, a set nCachedBranchId means that the block was
4362 // fully-validated under the corresponding consensus rules. Thus we can quickly
4363 // identify whether the current active chain matches our expected sequence of
4364 // consensus rule changes, with two checks:
4366 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
4367 // - nCachedBranchId for each block matches what we expect.
4368 auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) {
4369 auto consensus = params.GetConsensus();
4370 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
4371 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
4372 return fFlagSet == fFlagExpected &&
4373 pindex->nCachedBranchId &&
4374 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
4378 while (nHeight <= chainActive.Height()) {
4379 if (!sufficientlyValidated(chainActive[nHeight])) {
4385 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4386 auto rewindLength = chainActive.Height() - nHeight;
4387 if (rewindLength > 0 && rewindLength > MAX_REORG_LENGTH) {
4388 auto pindexOldTip = chainActive.Tip();
4389 auto pindexRewind = chainActive[nHeight - 1];
4390 auto msg = strprintf(_(
4391 "A block chain rewind has been detected that would roll back %d blocks! "
4392 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
4393 ), rewindLength, MAX_REORG_LENGTH) + "\n\n" +
4394 _("Rewind details") + ":\n" +
4395 "- " + strprintf(_("Current tip: %s, height %d"),
4396 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" +
4397 "- " + strprintf(_("Rewinding to: %s, height %d"),
4398 pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" +
4399 _("Please help, human!");
4400 LogPrintf("*** %s\n", msg);
4401 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
4406 CValidationState state;
4407 CBlockIndex* pindex = chainActive.Tip();
4408 while (chainActive.Height() >= nHeight) {
4409 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4410 // If pruning, don't try rewinding past the HAVE_DATA point;
4411 // since older blocks can't be served anyway, there's
4412 // no need to walk further, and trying to DisconnectTip()
4413 // will fail (and require a needless reindex/redownload
4414 // of the blockchain).
4417 if (!DisconnectTip(state, true)) {
4418 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4420 // Occasionally flush state to disk.
4421 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
4425 // Reduce validity flag and have-data flags.
4426 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4427 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4428 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4429 CBlockIndex* pindexIter = it->second;
4431 // Note: If we encounter an insufficiently validated block that
4432 // is on chainActive, it must be because we are a pruning node, and
4433 // this block or some successor doesn't HAVE_DATA, so we were unable to
4434 // rewind all the way. Blocks remaining on chainActive at this point
4435 // must not have their validity reduced.
4436 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
4438 pindexIter->nStatus =
4439 std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) |
4440 (pindexIter->nStatus & ~BLOCK_VALID_MASK);
4441 // Remove have-data flags
4442 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4444 pindexIter->nStatus &= ~BLOCK_ACTIVATES_UPGRADE;
4445 pindexIter->nCachedBranchId = boost::none;
4446 // Remove storage location
4447 pindexIter->nFile = 0;
4448 pindexIter->nDataPos = 0;
4449 pindexIter->nUndoPos = 0;
4450 // Remove various other things
4451 pindexIter->nTx = 0;
4452 pindexIter->nChainTx = 0;
4453 pindexIter->nSproutValue = boost::none;
4454 pindexIter->nChainSproutValue = boost::none;
4455 pindexIter->nSequenceId = 0;
4456 // Make sure it gets written
4457 setDirtyBlockIndex.insert(pindexIter);
4459 setBlockIndexCandidates.erase(pindexIter);
4460 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4461 while (ret.first != ret.second) {
4462 if (ret.first->second == pindexIter) {
4463 mapBlocksUnlinked.erase(ret.first++);
4468 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4469 setBlockIndexCandidates.insert(pindexIter);
4473 PruneBlockIndexCandidates();
4477 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4484 void UnloadBlockIndex()
4487 setBlockIndexCandidates.clear();
4488 chainActive.SetTip(NULL);
4489 pindexBestInvalid = NULL;
4490 pindexBestHeader = NULL;
4492 mapOrphanTransactions.clear();
4493 mapOrphanTransactionsByPrev.clear();
4495 mapBlocksUnlinked.clear();
4496 vinfoBlockFile.clear();
4498 nBlockSequenceId = 1;
4499 mapBlockSource.clear();
4500 mapBlocksInFlight.clear();
4501 nQueuedValidatedHeaders = 0;
4502 nPreferredDownload = 0;
4503 setDirtyBlockIndex.clear();
4504 setDirtyFileInfo.clear();
4505 mapNodeState.clear();
4506 recentRejects.reset(NULL);
4508 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4509 delete entry.second;
4511 mapBlockIndex.clear();
4512 fHavePruned = false;
4515 bool LoadBlockIndex()
4517 // Load block index from databases
4518 KOMODO_LOADINGBLOCKS = 1;
4519 if (!fReindex && !LoadBlockIndexDB())
4521 KOMODO_LOADINGBLOCKS = 0;
4524 KOMODO_LOADINGBLOCKS = 0;
4525 fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL);
4530 bool InitBlockIndex() {
4531 const CChainParams& chainparams = Params();
4534 // Initialize global variables that cannot be constructed at startup.
4535 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4537 // Check whether we're already initialized
4538 if (chainActive.Genesis() != NULL)
4541 // Use the provided setting for -txindex in the new database
4542 fTxIndex = GetBoolArg("-txindex", true);
4543 pblocktree->WriteFlag("txindex", fTxIndex);
4544 LogPrintf("Initializing databases...\n");
4546 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4549 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4550 // Start new block file
4551 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4552 CDiskBlockPos blockPos;
4553 CValidationState state;
4554 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4555 return error("LoadBlockIndex(): FindBlockPos failed");
4556 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4557 return error("LoadBlockIndex(): writing genesis block to disk failed");
4558 CBlockIndex *pindex = AddToBlockIndex(block);
4560 return error("LoadBlockIndex(): couldnt add to block index");
4561 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4562 return error("LoadBlockIndex(): genesis block not accepted");
4563 if (!ActivateBestChain(state, &block))
4564 return error("LoadBlockIndex(): genesis block cannot be activated");
4565 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4566 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4567 } catch (const std::runtime_error& e) {
4568 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4577 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4579 const CChainParams& chainparams = Params();
4580 // Map of disk positions for blocks with unknown parent (only used for reindex)
4581 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4582 int64_t nStart = GetTimeMillis();
4586 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4587 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4588 uint64_t nRewind = blkdat.GetPos();
4589 while (!blkdat.eof()) {
4590 boost::this_thread::interruption_point();
4592 blkdat.SetPos(nRewind);
4593 nRewind++; // start one byte further next time, in case of failure
4594 blkdat.SetLimit(); // remove former limit
4595 unsigned int nSize = 0;
4598 unsigned char buf[MESSAGE_START_SIZE];
4599 blkdat.FindByte(Params().MessageStart()[0]);
4600 nRewind = blkdat.GetPos()+1;
4601 blkdat >> FLATDATA(buf);
4602 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4606 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4608 } catch (const std::exception&) {
4609 // no valid block header found; don't complain
4614 uint64_t nBlockPos = blkdat.GetPos();
4616 dbp->nPos = nBlockPos;
4617 blkdat.SetLimit(nBlockPos + nSize);
4618 blkdat.SetPos(nBlockPos);
4621 nRewind = blkdat.GetPos();
4623 // detect out of order blocks, and store them for later
4624 uint256 hash = block.GetHash();
4625 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4626 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4627 block.hashPrevBlock.ToString());
4629 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4633 // process in case the block isn't known yet
4634 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4635 CValidationState state;
4636 if (ProcessNewBlock(0,state, NULL, &block, true, dbp))
4638 if (state.IsError())
4640 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4641 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4644 // Recursively process earlier encountered successors of this block
4645 deque<uint256> queue;
4646 queue.push_back(hash);
4647 while (!queue.empty()) {
4648 uint256 head = queue.front();
4650 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4651 while (range.first != range.second) {
4652 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4653 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
4655 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4657 CValidationState dummy;
4658 if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second))
4661 queue.push_back(block.GetHash());
4665 mapBlocksUnknownParent.erase(it);
4668 } catch (const std::exception& e) {
4669 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4672 } catch (const std::runtime_error& e) {
4673 AbortNode(std::string("System error: ") + e.what());
4676 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4680 void static CheckBlockIndex()
4682 const Consensus::Params& consensusParams = Params().GetConsensus();
4683 if (!fCheckBlockIndex) {
4689 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4690 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4691 // iterating the block tree require that chainActive has been initialized.)
4692 if (chainActive.Height() < 0) {
4693 assert(mapBlockIndex.size() <= 1);
4697 // Build forward-pointing map of the entire block tree.
4698 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4699 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4700 forward.insert(std::make_pair(it->second->pprev, it->second));
4703 assert(forward.size() == mapBlockIndex.size());
4705 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4706 CBlockIndex *pindex = rangeGenesis.first->second;
4707 rangeGenesis.first++;
4708 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4710 // Iterate over the entire block tree, using depth-first search.
4711 // Along the way, remember whether there are blocks on the path from genesis
4712 // block being explored which are the first to have certain properties.
4715 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4716 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4717 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4718 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4719 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4720 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4721 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4722 while (pindex != NULL) {
4724 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4725 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4726 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4727 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4728 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4729 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4730 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4732 // Begin: actual consistency checks.
4733 if (pindex->pprev == NULL) {
4734 // Genesis block checks.
4735 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4736 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4738 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4739 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4740 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4742 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4743 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4744 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4746 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4747 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4749 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4750 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4751 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4752 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4753 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4754 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4755 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.
4756 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4757 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4758 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4759 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4760 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4761 if (pindexFirstInvalid == NULL) {
4762 // Checks for not-invalid blocks.
4763 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4765 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4766 if (pindexFirstInvalid == NULL) {
4767 // If this block sorts at least as good as the current tip and
4768 // is valid and we have all data for its parents, it must be in
4769 // setBlockIndexCandidates. chainActive.Tip() must also be there
4770 // even if some data has been pruned.
4771 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4772 assert(setBlockIndexCandidates.count(pindex));
4774 // If some parent is missing, then it could be that this block was in
4775 // setBlockIndexCandidates but had to be removed because of the missing data.
4776 // In this case it must be in mapBlocksUnlinked -- see test below.
4778 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4779 assert(setBlockIndexCandidates.count(pindex) == 0);
4781 // Check whether this block is in mapBlocksUnlinked.
4782 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4783 bool foundInUnlinked = false;
4784 while (rangeUnlinked.first != rangeUnlinked.second) {
4785 assert(rangeUnlinked.first->first == pindex->pprev);
4786 if (rangeUnlinked.first->second == pindex) {
4787 foundInUnlinked = true;
4790 rangeUnlinked.first++;
4792 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4793 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4794 assert(foundInUnlinked);
4796 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4797 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4798 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4799 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4800 assert(fHavePruned); // We must have pruned.
4801 // This block may have entered mapBlocksUnlinked if:
4802 // - it has a descendant that at some point had more work than the
4804 // - we tried switching to that descendant but were missing
4805 // data for some intermediate block between chainActive and the
4807 // So if this block is itself better than chainActive.Tip() and it wasn't in
4808 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4809 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4810 if (pindexFirstInvalid == NULL) {
4811 assert(foundInUnlinked);
4815 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4816 // End: actual consistency checks.
4818 // Try descending into the first subnode.
4819 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4820 if (range.first != range.second) {
4821 // A subnode was found.
4822 pindex = range.first->second;
4826 // This is a leaf node.
4827 // Move upwards until we reach a node of which we have not yet visited the last child.
4829 // We are going to either move to a parent or a sibling of pindex.
4830 // If pindex was the first with a certain property, unset the corresponding variable.
4831 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4832 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4833 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4834 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4835 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4836 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4837 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4839 CBlockIndex* pindexPar = pindex->pprev;
4840 // Find which child we just visited.
4841 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4842 while (rangePar.first->second != pindex) {
4843 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4846 // Proceed to the next one.
4848 if (rangePar.first != rangePar.second) {
4849 // Move to the sibling.
4850 pindex = rangePar.first->second;
4861 // Check that we actually traversed the entire map.
4862 assert(nNodes == forward.size());
4865 //////////////////////////////////////////////////////////////////////////////
4870 std::string GetWarnings(const std::string& strFor)
4873 string strStatusBar;
4876 if (!CLIENT_VERSION_IS_RELEASE)
4877 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4879 if (GetBoolArg("-testsafemode", false))
4880 strStatusBar = strRPC = "testsafemode enabled";
4882 // Misc warnings like out of disk space and clock is wrong
4883 if (strMiscWarning != "")
4886 strStatusBar = strMiscWarning;
4889 if (fLargeWorkForkFound)
4892 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4894 else if (fLargeWorkInvalidChainFound)
4897 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.");
4903 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4905 const CAlert& alert = item.second;
4906 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4908 nPriority = alert.nPriority;
4909 strStatusBar = alert.strStatusBar;
4910 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4911 strRPC = alert.strRPCError;
4917 if (strFor == "statusbar")
4918 return strStatusBar;
4919 else if (strFor == "rpc")
4921 assert(!"GetWarnings(): invalid parameter");
4932 //////////////////////////////////////////////////////////////////////////////
4938 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4944 assert(recentRejects);
4945 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4947 // If the chain tip has changed previously rejected transactions
4948 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4949 // or a double-spend. Reset the rejects filter and give those
4950 // txs a second chance.
4951 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4952 recentRejects->reset();
4955 return recentRejects->contains(inv.hash) ||
4956 mempool.exists(inv.hash) ||
4957 mapOrphanTransactions.count(inv.hash) ||
4958 pcoinsTip->HaveCoins(inv.hash);
4961 return mapBlockIndex.count(inv.hash);
4963 // Don't know what it is, just say we already got one
4967 void static ProcessGetData(CNode* pfrom)
4969 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4971 vector<CInv> vNotFound;
4975 while (it != pfrom->vRecvGetData.end()) {
4976 // Don't bother if send buffer is too full to respond anyway
4977 if (pfrom->nSendSize >= SendBufferSize())
4980 const CInv &inv = *it;
4982 boost::this_thread::interruption_point();
4985 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4988 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4989 if (mi != mapBlockIndex.end())
4991 if (chainActive.Contains(mi->second)) {
4994 static const int nOneMonth = 30 * 24 * 60 * 60;
4995 // To prevent fingerprinting attacks, only send blocks outside of the active
4996 // chain if they are valid, and no more than a month older (both in time, and in
4997 // best equivalent proof of work) than the best header chain we know about.
4998 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4999 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
5000 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
5002 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
5006 // Pruned nodes may have deleted the block, so check whether
5007 // it's available before trying to send.
5008 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
5010 // Send block from disk
5012 if (!ReadBlockFromDisk(block, (*mi).second))
5014 assert(!"cannot load block from disk");
5018 if (inv.type == MSG_BLOCK)
5020 //uint256 hash; int32_t z;
5021 //hash = block.GetHash();
5022 //for (z=31; z>=0; z--)
5023 // fprintf(stderr,"%02x",((uint8_t *)&hash)[z]);
5024 //fprintf(stderr," send block %d\n",komodo_block2height(&block));
5025 pfrom->PushMessage("block", block);
5027 else // MSG_FILTERED_BLOCK)
5029 LOCK(pfrom->cs_filter);
5032 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
5033 pfrom->PushMessage("merkleblock", merkleBlock);
5034 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
5035 // This avoids hurting performance by pointlessly requiring a round-trip
5036 // Note that there is currently no way for a node to request any single transactions we didn't send here -
5037 // they must either disconnect and retry or request the full block.
5038 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
5039 // however we MUST always provide at least what the remote peer needs
5040 typedef std::pair<unsigned int, uint256> PairType;
5041 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
5042 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
5043 pfrom->PushMessage("tx", block.vtx[pair.first]);
5049 // Trigger the peer node to send a getblocks request for the next batch of inventory
5050 if (inv.hash == pfrom->hashContinue)
5052 // Bypass PushInventory, this must send even if redundant,
5053 // and we want it right after the last block so they don't
5054 // wait for other stuff first.
5056 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
5057 pfrom->PushMessage("inv", vInv);
5058 pfrom->hashContinue.SetNull();
5062 else if (inv.IsKnownType())
5064 // Send stream from relay memory
5065 bool pushed = false;
5068 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
5069 if (mi != mapRelay.end()) {
5070 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
5074 if (!pushed && inv.type == MSG_TX) {
5076 if (mempool.lookup(inv.hash, tx)) {
5077 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
5080 pfrom->PushMessage("tx", ss);
5085 vNotFound.push_back(inv);
5089 // Track requests for our stuff.
5090 GetMainSignals().Inventory(inv.hash);
5092 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
5097 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
5099 if (!vNotFound.empty()) {
5100 // Let the peer know that we didn't find what it asked for, so it doesn't
5101 // have to wait around forever. Currently only SPV clients actually care
5102 // about this message: it's needed when they are recursively walking the
5103 // dependencies of relevant unconfirmed transactions. SPV clients want to
5104 // do that because they want to know about (and store and rebroadcast and
5105 // risk analyze) the dependencies of transactions relevant to them, without
5106 // having to download the entire memory pool.
5107 pfrom->PushMessage("notfound", vNotFound);
5111 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
5113 const CChainParams& chainparams = Params();
5114 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
5115 //fprintf(stderr, "recv: %s peer=%d\n", SanitizeString(strCommand).c_str(), (int32_t)pfrom->GetId());
5116 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
5118 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
5125 if (strCommand == "version")
5127 // Each connection can only send one version message
5128 if (pfrom->nVersion != 0)
5130 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
5131 Misbehaving(pfrom->GetId(), 1);
5138 uint64_t nNonce = 1;
5139 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
5140 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
5142 // disconnect from peers older than this proto version
5143 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5144 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5145 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
5146 pfrom->fDisconnect = true;
5150 // When Overwinter is active, reject incoming connections from non-Overwinter nodes
5151 const Consensus::Params& params = Params().GetConsensus();
5152 if (NetworkUpgradeActive(GetHeight(), params, Consensus::UPGRADE_OVERWINTER)
5153 && pfrom->nVersion < params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)
5155 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5156 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5157 strprintf("Version must be %d or greater",
5158 params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion));
5159 pfrom->fDisconnect = true;
5163 if (pfrom->nVersion == 10300)
5164 pfrom->nVersion = 300;
5166 vRecv >> addrFrom >> nNonce;
5167 if (!vRecv.empty()) {
5168 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
5169 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
5172 vRecv >> pfrom->nStartingHeight;
5174 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
5176 pfrom->fRelayTxes = true;
5178 // Disconnect if we connected to ourself
5179 if (nNonce == nLocalHostNonce && nNonce > 1)
5181 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
5182 pfrom->fDisconnect = true;
5186 pfrom->addrLocal = addrMe;
5187 if (pfrom->fInbound && addrMe.IsRoutable())
5192 // Be shy and don't send version until we hear
5193 if (pfrom->fInbound)
5194 pfrom->PushVersion();
5196 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
5198 // Potentially mark this peer as a preferred download peer.
5199 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
5202 pfrom->PushMessage("verack");
5203 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5205 if (!pfrom->fInbound)
5207 // Advertise our address
5208 if (fListen && !IsInitialBlockDownload())
5210 CAddress addr = GetLocalAddress(&pfrom->addr);
5211 if (addr.IsRoutable())
5213 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5214 pfrom->PushAddress(addr);
5215 } else if (IsPeerAddrLocalGood(pfrom)) {
5216 addr.SetIP(pfrom->addrLocal);
5217 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5218 pfrom->PushAddress(addr);
5222 // Get recent addresses
5223 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
5225 pfrom->PushMessage("getaddr");
5226 pfrom->fGetAddr = true;
5228 addrman.Good(pfrom->addr);
5230 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
5232 addrman.Add(addrFrom, addrFrom);
5233 addrman.Good(addrFrom);
5240 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
5241 item.second.RelayTo(pfrom);
5244 pfrom->fSuccessfullyConnected = true;
5248 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
5250 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
5251 pfrom->cleanSubVer, pfrom->nVersion,
5252 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
5255 int64_t nTimeOffset = nTime - GetTime();
5256 pfrom->nTimeOffset = nTimeOffset;
5257 AddTimeData(pfrom->addr, nTimeOffset);
5261 else if (pfrom->nVersion == 0)
5263 // Must have a version message before anything else
5264 Misbehaving(pfrom->GetId(), 1);
5269 else if (strCommand == "verack")
5271 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5273 // Mark this node as currently connected, so we update its timestamp later.
5274 if (pfrom->fNetworkNode) {
5276 State(pfrom->GetId())->fCurrentlyConnected = true;
5281 // Disconnect existing peer connection when:
5282 // 1. The version message has been received
5283 // 2. Overwinter is active
5284 // 3. Peer version is pre-Overwinter
5285 else if (NetworkUpgradeActive(GetHeight(), chainparams.GetConsensus(), Consensus::UPGRADE_OVERWINTER)
5286 && (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion))
5288 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5289 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5290 strprintf("Version must be %d or greater",
5291 chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion));
5292 pfrom->fDisconnect = true;
5297 else if (strCommand == "addr")
5299 vector<CAddress> vAddr;
5302 // Don't want addr from older versions unless seeding
5303 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
5305 if (vAddr.size() > 1000)
5307 Misbehaving(pfrom->GetId(), 20);
5308 return error("message addr size() = %u", vAddr.size());
5311 // Store the new addresses
5312 vector<CAddress> vAddrOk;
5313 int64_t nNow = GetAdjustedTime();
5314 int64_t nSince = nNow - 10 * 60;
5315 BOOST_FOREACH(CAddress& addr, vAddr)
5317 boost::this_thread::interruption_point();
5319 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
5320 addr.nTime = nNow - 5 * 24 * 60 * 60;
5321 pfrom->AddAddressKnown(addr);
5322 bool fReachable = IsReachable(addr);
5323 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
5325 // Relay to a limited number of other nodes
5328 // Use deterministic randomness to send to the same nodes for 24 hours
5329 // at a time so the addrKnowns of the chosen nodes prevent repeats
5330 static uint256 hashSalt;
5331 if (hashSalt.IsNull())
5332 hashSalt = GetRandHash();
5333 uint64_t hashAddr = addr.GetHash();
5334 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
5335 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5336 multimap<uint256, CNode*> mapMix;
5337 BOOST_FOREACH(CNode* pnode, vNodes)
5339 if (pnode->nVersion < CADDR_TIME_VERSION)
5341 unsigned int nPointer;
5342 memcpy(&nPointer, &pnode, sizeof(nPointer));
5343 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
5344 hashKey = Hash(BEGIN(hashKey), END(hashKey));
5345 mapMix.insert(make_pair(hashKey, pnode));
5347 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
5348 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
5349 ((*mi).second)->PushAddress(addr);
5352 // Do not store addresses outside our network
5354 vAddrOk.push_back(addr);
5356 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
5357 if (vAddr.size() < 1000)
5358 pfrom->fGetAddr = false;
5359 if (pfrom->fOneShot)
5360 pfrom->fDisconnect = true;
5364 else if (strCommand == "inv")
5368 if (vInv.size() > MAX_INV_SZ)
5370 Misbehaving(pfrom->GetId(), 20);
5371 return error("message inv size() = %u", vInv.size());
5376 std::vector<CInv> vToFetch;
5378 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
5380 const CInv &inv = vInv[nInv];
5382 boost::this_thread::interruption_point();
5383 pfrom->AddInventoryKnown(inv);
5385 bool fAlreadyHave = AlreadyHave(inv);
5386 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
5388 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
5391 if (inv.type == MSG_BLOCK) {
5392 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
5393 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
5394 // First request the headers preceding the announced block. In the normal fully-synced
5395 // case where a new block is announced that succeeds the current tip (no reorganization),
5396 // there are no such headers.
5397 // Secondly, and only when we are close to being synced, we request the announced block directly,
5398 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
5399 // time the block arrives, the header chain leading up to it is already validated. Not
5400 // doing this will result in the received block being rejected as an orphan in case it is
5401 // not a direct successor.
5402 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
5403 CNodeState *nodestate = State(pfrom->GetId());
5404 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
5405 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5406 vToFetch.push_back(inv);
5407 // Mark block as in flight already, even though the actual "getdata" message only goes out
5408 // later (within the same cs_main lock, though).
5409 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
5411 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
5415 // Track requests for our stuff
5416 GetMainSignals().Inventory(inv.hash);
5418 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
5419 Misbehaving(pfrom->GetId(), 50);
5420 return error("send buffer size() = %u", pfrom->nSendSize);
5424 if (!vToFetch.empty())
5425 pfrom->PushMessage("getdata", vToFetch);
5429 else if (strCommand == "getdata")
5433 if (vInv.size() > MAX_INV_SZ)
5435 Misbehaving(pfrom->GetId(), 20);
5436 return error("message getdata size() = %u", vInv.size());
5439 if (fDebug || (vInv.size() != 1))
5440 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
5442 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
5443 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
5445 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
5446 ProcessGetData(pfrom);
5450 else if (strCommand == "getblocks")
5452 CBlockLocator locator;
5454 vRecv >> locator >> hashStop;
5458 // Find the last block the caller has in the main chain
5459 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
5461 // Send the rest of the chain
5463 pindex = chainActive.Next(pindex);
5465 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
5466 for (; pindex; pindex = chainActive.Next(pindex))
5468 if (pindex->GetBlockHash() == hashStop)
5470 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5473 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5476 // When this block is requested, we'll send an inv that'll
5477 // trigger the peer to getblocks the next batch of inventory.
5478 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5479 pfrom->hashContinue = pindex->GetBlockHash();
5486 else if (strCommand == "getheaders")
5488 CBlockLocator locator;
5490 vRecv >> locator >> hashStop;
5494 if (IsInitialBlockDownload())
5497 CBlockIndex* pindex = NULL;
5498 if (locator.IsNull())
5500 // If locator is null, return the hashStop block
5501 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
5502 if (mi == mapBlockIndex.end())
5504 pindex = (*mi).second;
5508 // Find the last block the caller has in the main chain
5509 pindex = FindForkInGlobalIndex(chainActive, locator);
5511 pindex = chainActive.Next(pindex);
5514 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5515 vector<CBlock> vHeaders;
5516 int nLimit = MAX_HEADERS_RESULTS;
5517 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5518 if ( pfrom->lasthdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pfrom->lasthdrsreq != (int32_t)(pindex ? pindex->nHeight : -1) )
5520 pfrom->lasthdrsreq = (int32_t)(pindex ? pindex->nHeight : -1);
5521 for (; pindex; pindex = chainActive.Next(pindex))
5523 vHeaders.push_back(pindex->GetBlockHeader());
5524 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5527 pfrom->PushMessage("headers", vHeaders);
5529 else if ( NOTARY_PUBKEY33[0] != 0 )
5531 static uint32_t counter;
5532 if ( counter++ < 3 )
5533 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);
5538 else if (strCommand == "tx")
5540 vector<uint256> vWorkQueue;
5541 vector<uint256> vEraseQueue;
5545 CInv inv(MSG_TX, tx.GetHash());
5546 pfrom->AddInventoryKnown(inv);
5550 bool fMissingInputs = false;
5551 CValidationState state;
5553 pfrom->setAskFor.erase(inv.hash);
5554 mapAlreadyAskedFor.erase(inv);
5556 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5558 mempool.check(pcoinsTip);
5559 RelayTransaction(tx);
5560 vWorkQueue.push_back(inv.hash);
5562 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5563 pfrom->id, pfrom->cleanSubVer,
5564 tx.GetHash().ToString(),
5565 mempool.mapTx.size());
5567 // Recursively process any orphan transactions that depended on this one
5568 set<NodeId> setMisbehaving;
5569 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5571 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5572 if (itByPrev == mapOrphanTransactionsByPrev.end())
5574 for (set<uint256>::iterator mi = itByPrev->second.begin();
5575 mi != itByPrev->second.end();
5578 const uint256& orphanHash = *mi;
5579 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5580 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5581 bool fMissingInputs2 = false;
5582 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5583 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5584 // anyone relaying LegitTxX banned)
5585 CValidationState stateDummy;
5588 if (setMisbehaving.count(fromPeer))
5590 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5592 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5593 RelayTransaction(orphanTx);
5594 vWorkQueue.push_back(orphanHash);
5595 vEraseQueue.push_back(orphanHash);
5597 else if (!fMissingInputs2)
5600 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5602 // Punish peer that gave us an invalid orphan tx
5603 Misbehaving(fromPeer, nDos);
5604 setMisbehaving.insert(fromPeer);
5605 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5607 // Has inputs but not accepted to mempool
5608 // Probably non-standard or insufficient fee/priority
5609 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5610 vEraseQueue.push_back(orphanHash);
5611 assert(recentRejects);
5612 recentRejects->insert(orphanHash);
5614 mempool.check(pcoinsTip);
5618 BOOST_FOREACH(uint256 hash, vEraseQueue)
5619 EraseOrphanTx(hash);
5621 // TODO: currently, prohibit joinsplits from entering mapOrphans
5622 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5624 AddOrphanTx(tx, pfrom->GetId());
5626 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5627 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5628 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5630 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5632 assert(recentRejects);
5633 recentRejects->insert(tx.GetHash());
5635 if (pfrom->fWhitelisted) {
5636 // Always relay transactions received from whitelisted peers, even
5637 // if they were already in the mempool or rejected from it due
5638 // to policy, allowing the node to function as a gateway for
5639 // nodes hidden behind it.
5641 // Never relay transactions that we would assign a non-zero DoS
5642 // score for, as we expect peers to do the same with us in that
5645 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5646 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5647 RelayTransaction(tx);
5649 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5650 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5655 if (state.IsInvalid(nDoS))
5657 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5658 pfrom->id, pfrom->cleanSubVer,
5659 state.GetRejectReason());
5660 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5661 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5663 Misbehaving(pfrom->GetId(), nDoS);
5668 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5670 std::vector<CBlockHeader> headers;
5672 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5673 unsigned int nCount = ReadCompactSize(vRecv);
5674 if (nCount > MAX_HEADERS_RESULTS) {
5675 Misbehaving(pfrom->GetId(), 20);
5676 return error("headers message size = %u", nCount);
5678 headers.resize(nCount);
5679 for (unsigned int n = 0; n < nCount; n++) {
5680 vRecv >> headers[n];
5681 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5687 // Nothing interesting. Stop asking this peers for more headers.
5691 CBlockIndex *pindexLast = NULL;
5692 BOOST_FOREACH(const CBlockHeader& header, headers) {
5693 CValidationState state;
5694 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5695 Misbehaving(pfrom->GetId(), 20);
5696 return error("non-continuous headers sequence");
5698 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5700 if (state.IsInvalid(nDoS)) {
5702 Misbehaving(pfrom->GetId(), nDoS/nDoS);
5703 return error("invalid header received");
5709 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5711 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5712 // Headers message had its maximum size; the peer may have more headers.
5713 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5714 // from there instead.
5715 if ( pfrom->sendhdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pindexLast->nHeight != pfrom->sendhdrsreq )
5717 pfrom->sendhdrsreq = (int32_t)pindexLast->nHeight;
5718 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5719 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5726 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5731 CInv inv(MSG_BLOCK, block.GetHash());
5732 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5734 pfrom->AddInventoryKnown(inv);
5736 CValidationState state;
5737 // Process all blocks from whitelisted peers, even if not requested,
5738 // unless we're still syncing with the network.
5739 // Such an unrequested block may still be processed, subject to the
5740 // conditions in AcceptBlock().
5741 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5742 ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL);
5744 if (state.IsInvalid(nDoS)) {
5745 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5746 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5749 Misbehaving(pfrom->GetId(), nDoS);
5756 // This asymmetric behavior for inbound and outbound connections was introduced
5757 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5758 // to users' AddrMan and later request them by sending getaddr messages.
5759 // Making nodes which are behind NAT and can only make outgoing connections ignore
5760 // the getaddr message mitigates the attack.
5761 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5763 // Only send one GetAddr response per connection to reduce resource waste
5764 // and discourage addr stamping of INV announcements.
5765 if (pfrom->fSentAddr) {
5766 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5769 pfrom->fSentAddr = true;
5771 pfrom->vAddrToSend.clear();
5772 vector<CAddress> vAddr = addrman.GetAddr();
5773 BOOST_FOREACH(const CAddress &addr, vAddr)
5774 pfrom->PushAddress(addr);
5778 else if (strCommand == "mempool")
5780 LOCK2(cs_main, pfrom->cs_filter);
5782 std::vector<uint256> vtxid;
5783 mempool.queryHashes(vtxid);
5785 BOOST_FOREACH(uint256& hash, vtxid) {
5786 CInv inv(MSG_TX, hash);
5788 bool fInMemPool = mempool.lookup(hash, tx);
5789 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5790 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5792 vInv.push_back(inv);
5793 if (vInv.size() == MAX_INV_SZ) {
5794 pfrom->PushMessage("inv", vInv);
5798 if (vInv.size() > 0)
5799 pfrom->PushMessage("inv", vInv);
5803 else if (strCommand == "ping")
5805 if (pfrom->nVersion > BIP0031_VERSION)
5809 // Echo the message back with the nonce. This allows for two useful features:
5811 // 1) A remote node can quickly check if the connection is operational
5812 // 2) Remote nodes can measure the latency of the network thread. If this node
5813 // is overloaded it won't respond to pings quickly and the remote node can
5814 // avoid sending us more work, like chain download requests.
5816 // The nonce stops the remote getting confused between different pings: without
5817 // it, if the remote node sends a ping once per second and this node takes 5
5818 // seconds to respond to each, the 5th ping the remote sends would appear to
5819 // return very quickly.
5820 pfrom->PushMessage("pong", nonce);
5825 else if (strCommand == "pong")
5827 int64_t pingUsecEnd = nTimeReceived;
5829 size_t nAvail = vRecv.in_avail();
5830 bool bPingFinished = false;
5831 std::string sProblem;
5833 if (nAvail >= sizeof(nonce)) {
5836 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5837 if (pfrom->nPingNonceSent != 0) {
5838 if (nonce == pfrom->nPingNonceSent) {
5839 // Matching pong received, this ping is no longer outstanding
5840 bPingFinished = true;
5841 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5842 if (pingUsecTime > 0) {
5843 // Successful ping time measurement, replace previous
5844 pfrom->nPingUsecTime = pingUsecTime;
5845 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5847 // This should never happen
5848 sProblem = "Timing mishap";
5851 // Nonce mismatches are normal when pings are overlapping
5852 sProblem = "Nonce mismatch";
5854 // This is most likely a bug in another implementation somewhere; cancel this ping
5855 bPingFinished = true;
5856 sProblem = "Nonce zero";
5860 sProblem = "Unsolicited pong without ping";
5863 // This is most likely a bug in another implementation somewhere; cancel this ping
5864 bPingFinished = true;
5865 sProblem = "Short payload";
5868 if (!(sProblem.empty())) {
5869 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5873 pfrom->nPingNonceSent,
5877 if (bPingFinished) {
5878 pfrom->nPingNonceSent = 0;
5883 else if (fAlerts && strCommand == "alert")
5888 uint256 alertHash = alert.GetHash();
5889 if (pfrom->setKnown.count(alertHash) == 0)
5891 if (alert.ProcessAlert(Params().AlertKey()))
5894 pfrom->setKnown.insert(alertHash);
5897 BOOST_FOREACH(CNode* pnode, vNodes)
5898 alert.RelayTo(pnode);
5902 // Small DoS penalty so peers that send us lots of
5903 // duplicate/expired/invalid-signature/whatever alerts
5904 // eventually get banned.
5905 // This isn't a Misbehaving(100) (immediate ban) because the
5906 // peer might be an older or different implementation with
5907 // a different signature key, etc.
5908 Misbehaving(pfrom->GetId(), 10);
5914 else if (strCommand == "filterload")
5916 CBloomFilter filter;
5919 if (!filter.IsWithinSizeConstraints())
5920 // There is no excuse for sending a too-large filter
5921 Misbehaving(pfrom->GetId(), 100);
5924 LOCK(pfrom->cs_filter);
5925 delete pfrom->pfilter;
5926 pfrom->pfilter = new CBloomFilter(filter);
5927 pfrom->pfilter->UpdateEmptyFull();
5929 pfrom->fRelayTxes = true;
5933 else if (strCommand == "filteradd")
5935 vector<unsigned char> vData;
5938 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5939 // and thus, the maximum size any matched object can have) in a filteradd message
5940 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5942 Misbehaving(pfrom->GetId(), 100);
5944 LOCK(pfrom->cs_filter);
5946 pfrom->pfilter->insert(vData);
5948 Misbehaving(pfrom->GetId(), 100);
5953 else if (strCommand == "filterclear")
5955 LOCK(pfrom->cs_filter);
5956 delete pfrom->pfilter;
5957 pfrom->pfilter = new CBloomFilter();
5958 pfrom->fRelayTxes = true;
5962 else if (strCommand == "reject")
5966 string strMsg; unsigned char ccode; string strReason;
5967 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5970 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5972 if (strMsg == "block" || strMsg == "tx")
5976 ss << ": hash " << hash.ToString();
5978 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5979 } catch (const std::ios_base::failure&) {
5980 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5981 LogPrint("net", "Unparseable reject message received\n");
5985 else if (strCommand == "notfound") {
5986 // We do not care about the NOTFOUND message, but logging an Unknown Command
5987 // message would be undesirable as we transmit it ourselves.
5991 // Ignore unknown commands for extensibility
5992 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
6000 // requires LOCK(cs_vRecvMsg)
6001 bool ProcessMessages(CNode* pfrom)
6004 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
6008 // (4) message start
6016 if (!pfrom->vRecvGetData.empty())
6017 ProcessGetData(pfrom);
6019 // this maintains the order of responses
6020 if (!pfrom->vRecvGetData.empty()) return fOk;
6022 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
6023 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
6024 // Don't bother if send buffer is too full to respond anyway
6025 if (pfrom->nSendSize >= SendBufferSize())
6029 CNetMessage& msg = *it;
6032 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
6033 // msg.hdr.nMessageSize, msg.vRecv.size(),
6034 // msg.complete() ? "Y" : "N");
6036 // end, if an incomplete message is found
6037 if (!msg.complete())
6040 // at this point, any failure means we can delete the current message
6043 // Scan for message start
6044 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
6045 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
6051 CMessageHeader& hdr = msg.hdr;
6052 if (!hdr.IsValid(Params().MessageStart()))
6054 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
6057 string strCommand = hdr.GetCommand();
6060 unsigned int nMessageSize = hdr.nMessageSize;
6063 CDataStream& vRecv = msg.vRecv;
6064 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
6065 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
6066 if (nChecksum != hdr.nChecksum)
6068 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
6069 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
6077 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
6078 boost::this_thread::interruption_point();
6080 catch (const std::ios_base::failure& e)
6082 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
6083 if (strstr(e.what(), "end of data"))
6085 // Allow exceptions from under-length message on vRecv
6086 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());
6088 else if (strstr(e.what(), "size too large"))
6090 // Allow exceptions from over-long size
6091 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
6095 //PrintExceptionContinue(&e, "ProcessMessages()");
6098 catch (const boost::thread_interrupted&) {
6101 catch (const std::exception& e) {
6102 PrintExceptionContinue(&e, "ProcessMessages()");
6104 PrintExceptionContinue(NULL, "ProcessMessages()");
6108 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
6113 // In case the connection got shut down, its receive buffer was wiped
6114 if (!pfrom->fDisconnect)
6115 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
6121 bool SendMessages(CNode* pto, bool fSendTrickle)
6123 const Consensus::Params& consensusParams = Params().GetConsensus();
6125 // Don't send anything until we get its version message
6126 if (pto->nVersion == 0)
6132 bool pingSend = false;
6133 if (pto->fPingQueued) {
6134 // RPC ping request by user
6137 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
6138 // Ping automatically sent as a latency probe & keepalive.
6143 while (nonce == 0) {
6144 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
6146 pto->fPingQueued = false;
6147 pto->nPingUsecStart = GetTimeMicros();
6148 if (pto->nVersion > BIP0031_VERSION) {
6149 pto->nPingNonceSent = nonce;
6150 pto->PushMessage("ping", nonce);
6152 // Peer is too old to support ping command with nonce, pong will never arrive.
6153 pto->nPingNonceSent = 0;
6154 pto->PushMessage("ping");
6158 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
6162 // Address refresh broadcast
6163 static int64_t nLastRebroadcast;
6164 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
6167 BOOST_FOREACH(CNode* pnode, vNodes)
6169 // Periodically clear addrKnown to allow refresh broadcasts
6170 if (nLastRebroadcast)
6171 pnode->addrKnown.reset();
6173 // Rebroadcast our address
6174 AdvertizeLocal(pnode);
6176 if (!vNodes.empty())
6177 nLastRebroadcast = GetTime();
6185 vector<CAddress> vAddr;
6186 vAddr.reserve(pto->vAddrToSend.size());
6187 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
6189 if (!pto->addrKnown.contains(addr.GetKey()))
6191 pto->addrKnown.insert(addr.GetKey());
6192 vAddr.push_back(addr);
6193 // receiver rejects addr messages larger than 1000
6194 if (vAddr.size() >= 1000)
6196 pto->PushMessage("addr", vAddr);
6201 pto->vAddrToSend.clear();
6203 pto->PushMessage("addr", vAddr);
6206 CNodeState &state = *State(pto->GetId());
6207 if (state.fShouldBan) {
6208 if (pto->fWhitelisted)
6209 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
6211 pto->fDisconnect = true;
6212 if (pto->addr.IsLocal())
6213 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
6216 CNode::Ban(pto->addr);
6219 state.fShouldBan = false;
6222 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
6223 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
6224 state.rejects.clear();
6227 if (pindexBestHeader == NULL)
6228 pindexBestHeader = chainActive.Tip();
6229 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.
6230 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
6231 // Only actively request headers from a single peer, unless we're close to today.
6232 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
6233 state.fSyncStarted = true;
6235 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
6236 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
6237 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
6241 // Resend wallet transactions that haven't gotten in a block yet
6242 // Except during reindex, importing and IBD, when old wallet
6243 // transactions become unconfirmed and spams other nodes.
6244 if (!fReindex && !fImporting && !IsInitialBlockDownload())
6246 GetMainSignals().Broadcast(nTimeBestReceived);
6250 // Message: inventory
6253 vector<CInv> vInvWait;
6255 LOCK(pto->cs_inventory);
6256 vInv.reserve(pto->vInventoryToSend.size());
6257 vInvWait.reserve(pto->vInventoryToSend.size());
6258 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
6260 if (pto->setInventoryKnown.count(inv))
6263 // trickle out tx inv to protect privacy
6264 if (inv.type == MSG_TX && !fSendTrickle)
6266 // 1/4 of tx invs blast to all immediately
6267 static uint256 hashSalt;
6268 if (hashSalt.IsNull())
6269 hashSalt = GetRandHash();
6270 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
6271 hashRand = Hash(BEGIN(hashRand), END(hashRand));
6272 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
6276 vInvWait.push_back(inv);
6281 // returns true if wasn't already contained in the set
6282 if (pto->setInventoryKnown.insert(inv).second)
6284 vInv.push_back(inv);
6285 if (vInv.size() >= 1000)
6287 pto->PushMessage("inv", vInv);
6292 pto->vInventoryToSend = vInvWait;
6295 pto->PushMessage("inv", vInv);
6297 // Detect whether we're stalling
6298 int64_t nNow = GetTimeMicros();
6299 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
6300 // Stalling only triggers when the block download window cannot move. During normal steady state,
6301 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6302 // should only happen during initial block download.
6303 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
6304 pto->fDisconnect = true;
6306 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
6307 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
6308 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
6309 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6310 // to unreasonably increase our timeout.
6311 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
6312 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
6313 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
6314 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
6315 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
6316 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
6317 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
6318 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
6319 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
6320 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
6321 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
6323 if (queuedBlock.nTimeDisconnect < nNow) {
6324 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
6325 pto->fDisconnect = true;
6330 // Message: getdata (blocks)
6332 vector<CInv> vGetData;
6333 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
6334 vector<CBlockIndex*> vToDownload;
6335 NodeId staller = -1;
6336 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
6337 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
6338 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
6339 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
6340 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6341 pindex->nHeight, pto->id);
6343 if (state.nBlocksInFlight == 0 && staller != -1) {
6344 if (State(staller)->nStallingSince == 0) {
6345 State(staller)->nStallingSince = nNow;
6346 LogPrint("net", "Stall started peer=%d\n", staller);
6352 // Message: getdata (non-blocks)
6354 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
6356 const CInv& inv = (*pto->mapAskFor.begin()).second;
6357 if (!AlreadyHave(inv))
6360 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
6361 vGetData.push_back(inv);
6362 if (vGetData.size() >= 1000)
6364 pto->PushMessage("getdata", vGetData);
6368 //If we're not going to ask, don't expect a response.
6369 pto->setAskFor.erase(inv.hash);
6371 pto->mapAskFor.erase(pto->mapAskFor.begin());
6373 if (!vGetData.empty())
6374 pto->PushMessage("getdata", vGetData);
6380 std::string CBlockFileInfo::ToString() const {
6381 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));
6392 BlockMap::iterator it1 = mapBlockIndex.begin();
6393 for (; it1 != mapBlockIndex.end(); it1++)
6394 delete (*it1).second;
6395 mapBlockIndex.clear();
6397 // orphan transactions
6398 mapOrphanTransactions.clear();
6399 mapOrphanTransactionsByPrev.clear();
6401 } instance_of_cmaincleanup;
6403 extern "C" const char* getDataDir()
6405 return GetDataDir().string().c_str();
6409 // Set default values of new CMutableTransaction based on consensus rules at given height.
6410 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
6412 CMutableTransaction mtx;
6414 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
6415 if (isOverwintered) {
6416 mtx.fOverwintered = true;
6417 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
6419 // Expiry height is not set. Only fields required for a parser to treat as a valid Overwinter V3 tx.
6421 // TODO: In future, when moving from Overwinter to Sapling, it will be useful
6422 // to set the expiry height to: min(activation_height - 1, default_expiry_height)