1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "arith_uint256.h"
13 #include "chainparams.h"
14 #include "checkpoints.h"
15 #include "checkqueue.h"
16 #include "consensus/validation.h"
18 #include "merkleblock.h"
23 #include "txmempool.h"
24 #include "ui_interface.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
29 #include "wallet/asyncrpcoperation_sendmany.h"
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/filesystem/fstream.hpp>
36 #include <boost/math/distributions/poisson.hpp>
37 #include <boost/thread.hpp>
38 #include <boost/static_assert.hpp>
43 # error "Zcash cannot be compiled without assertions."
51 CCriticalSection cs_main;
52 extern uint8_t NOTARY_PUBKEY33[33];
54 BlockMap mapBlockIndex;
56 CBlockIndex *pindexBestHeader = NULL;
57 int64_t nTimeBestReceived = 0;
58 CWaitableCriticalSection csBestBlock;
59 CConditionVariable cvBlockChange;
60 int nScriptCheckThreads = 0;
61 bool fExperimentalMode = false;
62 bool fImporting = false;
63 bool fReindex = false;
64 bool fTxIndex = false;
65 bool fHavePruned = false;
66 bool fPruneMode = false;
67 bool fIsBareMultisigStd = true;
68 bool fCheckBlockIndex = false;
69 bool fCheckpointsEnabled = true;
70 bool fCoinbaseEnforcedProtectionEnabled = true;
71 size_t nCoinCacheUsage = 5000 * 300;
72 uint64_t nPruneTarget = 0;
73 bool fAlerts = DEFAULT_ALERTS;
75 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
76 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
78 CTxMemPool mempool(::minRelayTxFee);
84 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
85 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
86 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
89 * Returns true if there are nRequired or more blocks of minVersion or above
90 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
92 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
93 static void CheckBlockIndex();
95 /** Constant stuff for coinbase transactions we create: */
96 CScript COINBASE_FLAGS;
98 const string strMessageMagic = "Komodo Signed Message:\n";
103 struct CBlockIndexWorkComparator
105 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
106 // First sort by most total work, ...
107 if (pa->nChainWork > pb->nChainWork) return false;
108 if (pa->nChainWork < pb->nChainWork) return true;
110 // ... then by earliest time received, ...
111 if (pa->nSequenceId < pb->nSequenceId) return false;
112 if (pa->nSequenceId > pb->nSequenceId) return true;
114 // Use pointer address as tie breaker (should only happen with blocks
115 // loaded from disk, as those all have id 0).
116 if (pa < pb) return false;
117 if (pa > pb) return true;
124 CBlockIndex *pindexBestInvalid;
127 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
128 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
129 * missing the data for the block.
131 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
132 /** Number of nodes with fSyncStarted. */
133 int nSyncStarted = 0;
134 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
135 * Pruned nodes may have entries where B is missing data.
137 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
139 CCriticalSection cs_LastBlockFile;
140 std::vector<CBlockFileInfo> vinfoBlockFile;
141 int nLastBlockFile = 0;
142 /** Global flag to indicate we should check to see if there are
143 * block/undo files that should be deleted. Set on startup
144 * or if we allocate more file space when we're in prune mode
146 bool fCheckForPruning = false;
149 * Every received block is assigned a unique and increasing identifier, so we
150 * know which one to give priority in case of a fork.
152 CCriticalSection cs_nBlockSequenceId;
153 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
154 uint32_t nBlockSequenceId = 1;
157 * Sources of received blocks, saved to be able to send them reject
158 * messages or ban them when processing happens afterwards. Protected by
161 map<uint256, NodeId> mapBlockSource;
164 * Filter for transactions that were recently rejected by
165 * AcceptToMemoryPool. These are not rerequested until the chain tip
166 * changes, at which point the entire filter is reset. Protected by
169 * Without this filter we'd be re-requesting txs from each of our peers,
170 * increasing bandwidth consumption considerably. For instance, with 100
171 * peers, half of which relay a tx we don't accept, that might be a 50x
172 * bandwidth increase. A flooding attacker attempting to roll-over the
173 * filter using minimum-sized, 60byte, transactions might manage to send
174 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
175 * two minute window to send invs to us.
177 * Decreasing the false positive rate is fairly cheap, so we pick one in a
178 * million to make it highly unlikely for users to have issues with this
183 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
184 uint256 hashRecentRejectsChainTip;
186 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
189 CBlockIndex *pindex; //! Optional.
190 int64_t nTime; //! Time of "getdata" request in microseconds.
191 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
192 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
194 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
196 /** Number of blocks in flight with validated headers. */
197 int nQueuedValidatedHeaders = 0;
199 /** Number of preferable block download peers. */
200 int nPreferredDownload = 0;
202 /** Dirty block index entries. */
203 set<CBlockIndex*> setDirtyBlockIndex;
205 /** Dirty block file entries. */
206 set<int> setDirtyFileInfo;
209 //////////////////////////////////////////////////////////////////////////////
211 // Registration of network node signals.
216 struct CBlockReject {
217 unsigned char chRejectCode;
218 string strRejectReason;
223 * Maintain validation-specific state about nodes, protected by cs_main, instead
224 * by CNode's own locks. This simplifies asynchronous operation, where
225 * processing of incoming data is done after the ProcessMessage call returns,
226 * and we're no longer holding the node's locks.
229 //! The peer's address
231 //! Whether we have a fully established connection.
232 bool fCurrentlyConnected;
233 //! Accumulated misbehaviour score for this peer.
235 //! Whether this peer should be disconnected and banned (unless whitelisted).
237 //! String name of this peer (debugging/logging purposes).
239 //! List of asynchronously-determined block rejections to notify this peer about.
240 std::vector<CBlockReject> rejects;
241 //! The best known block we know this peer has announced.
242 CBlockIndex *pindexBestKnownBlock;
243 //! The hash of the last unknown block this peer has announced.
244 uint256 hashLastUnknownBlock;
245 //! The last full block we both have.
246 CBlockIndex *pindexLastCommonBlock;
247 //! Whether we've started headers synchronization with this peer.
249 //! Since when we're stalling block download progress (in microseconds), or 0.
250 int64_t nStallingSince;
251 list<QueuedBlock> vBlocksInFlight;
253 int nBlocksInFlightValidHeaders;
254 //! Whether we consider this a preferred download peer.
255 bool fPreferredDownload;
258 fCurrentlyConnected = false;
261 pindexBestKnownBlock = NULL;
262 hashLastUnknownBlock.SetNull();
263 pindexLastCommonBlock = NULL;
264 fSyncStarted = false;
267 nBlocksInFlightValidHeaders = 0;
268 fPreferredDownload = false;
272 /** Map maintaining per-node state. Requires cs_main. */
273 map<NodeId, CNodeState> mapNodeState;
276 CNodeState *State(NodeId pnode) {
277 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
278 if (it == mapNodeState.end())
286 return chainActive.Height();
289 void UpdatePreferredDownload(CNode* node, CNodeState* state)
291 nPreferredDownload -= state->fPreferredDownload;
293 // Whether this node should be marked as a preferred download node.
294 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
296 nPreferredDownload += state->fPreferredDownload;
299 // Returns time at which to timeout block request (nTime in microseconds)
300 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
302 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
305 void InitializeNode(NodeId nodeid, const CNode *pnode) {
307 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
308 state.name = pnode->addrName;
309 state.address = pnode->addr;
312 void FinalizeNode(NodeId nodeid) {
314 CNodeState *state = State(nodeid);
316 if (state->fSyncStarted)
319 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
320 AddressCurrentlyConnected(state->address);
323 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
324 mapBlocksInFlight.erase(entry.hash);
325 EraseOrphansFor(nodeid);
326 nPreferredDownload -= state->fPreferredDownload;
328 mapNodeState.erase(nodeid);
331 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)
333 /* int expired = pool.Expire(GetTime() - age);
335 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
337 std::vector<uint256> vNoSpendsRemaining;
338 pool.TrimToSize(limit, &vNoSpendsRemaining);
339 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
340 pcoinsTip->Uncache(removed);*/
344 // Returns a bool indicating whether we requested this block.
345 bool MarkBlockAsReceived(const uint256& hash) {
346 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
347 if (itInFlight != mapBlocksInFlight.end()) {
348 CNodeState *state = State(itInFlight->second.first);
349 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
350 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
351 state->vBlocksInFlight.erase(itInFlight->second.second);
352 state->nBlocksInFlight--;
353 state->nStallingSince = 0;
354 mapBlocksInFlight.erase(itInFlight);
361 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
362 CNodeState *state = State(nodeid);
363 assert(state != NULL);
365 // Make sure it's not listed somewhere already.
366 MarkBlockAsReceived(hash);
368 int64_t nNow = GetTimeMicros();
369 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
370 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
371 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
372 state->nBlocksInFlight++;
373 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
374 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
377 /** Check whether the last unknown block a peer advertized is not yet known. */
378 void ProcessBlockAvailability(NodeId nodeid) {
379 CNodeState *state = State(nodeid);
380 assert(state != NULL);
382 if (!state->hashLastUnknownBlock.IsNull()) {
383 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
384 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0)
386 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
387 state->pindexBestKnownBlock = itOld->second;
388 state->hashLastUnknownBlock.SetNull();
393 /** Update tracking information about which blocks a peer is assumed to have. */
394 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
395 CNodeState *state = State(nodeid);
396 assert(state != NULL);
398 /*ProcessBlockAvailability(nodeid);
400 BlockMap::iterator it = mapBlockIndex.find(hash);
401 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
402 // An actually better block was announced.
403 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
404 state->pindexBestKnownBlock = it->second;
407 // An unknown block was announced; just assume that the latest one is the best one.
408 state->hashLastUnknownBlock = hash;
412 /** Find the last common ancestor two blocks have.
413 * Both pa and pb must be non-NULL. */
414 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
415 if (pa->nHeight > pb->nHeight) {
416 pa = pa->GetAncestor(pb->nHeight);
417 } else if (pb->nHeight > pa->nHeight) {
418 pb = pb->GetAncestor(pa->nHeight);
421 while (pa != pb && pa && pb) {
426 // Eventually all chain branches meet at the genesis block.
431 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
432 * at most count entries. */
433 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
437 vBlocks.reserve(vBlocks.size() + count);
438 CNodeState *state = State(nodeid);
439 assert(state != NULL);
441 // Make sure pindexBestKnownBlock is up to date, we'll need it.
442 ProcessBlockAvailability(nodeid);
444 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
445 // This peer has nothing interesting.
449 if (state->pindexLastCommonBlock == NULL) {
450 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
451 // Guessing wrong in either direction is not a problem.
452 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
455 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
456 // of its current tip anymore. Go back enough to fix that.
457 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
458 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
461 std::vector<CBlockIndex*> vToFetch;
462 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
463 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
464 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
465 // download that next block if the window were 1 larger.
466 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
467 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
468 NodeId waitingfor = -1;
469 while (pindexWalk->nHeight < nMaxHeight) {
470 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
471 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
472 // as iterating over ~100 CBlockIndex* entries anyway.
473 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
474 vToFetch.resize(nToFetch);
475 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
476 vToFetch[nToFetch - 1] = pindexWalk;
477 for (unsigned int i = nToFetch - 1; i > 0; i--) {
478 vToFetch[i - 1] = vToFetch[i]->pprev;
481 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
482 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
483 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
484 // already part of our chain (and therefore don't need it even if pruned).
485 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
486 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
487 // We consider the chain that this peer is on invalid.
490 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
491 if (pindex->nChainTx)
492 state->pindexLastCommonBlock = pindex;
493 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
494 // The block is not already downloaded, and not yet in flight.
495 if (pindex->nHeight > nWindowEnd) {
496 // We reached the end of the window.
497 if (vBlocks.size() == 0 && waitingfor != nodeid) {
498 // We aren't able to fetch anything, but we would be if the download window was one larger.
499 nodeStaller = waitingfor;
503 vBlocks.push_back(pindex);
504 if (vBlocks.size() == count) {
507 } else if (waitingfor == -1) {
508 // This is the first already-in-flight block.
509 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
517 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
519 CNodeState *state = State(nodeid);
522 stats.nMisbehavior = state->nMisbehavior;
523 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
524 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
525 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
527 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
532 void RegisterNodeSignals(CNodeSignals& nodeSignals)
534 nodeSignals.GetHeight.connect(&GetHeight);
535 nodeSignals.ProcessMessages.connect(&ProcessMessages);
536 nodeSignals.SendMessages.connect(&SendMessages);
537 nodeSignals.InitializeNode.connect(&InitializeNode);
538 nodeSignals.FinalizeNode.connect(&FinalizeNode);
541 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
543 nodeSignals.GetHeight.disconnect(&GetHeight);
544 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
545 nodeSignals.SendMessages.disconnect(&SendMessages);
546 nodeSignals.InitializeNode.disconnect(&InitializeNode);
547 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
550 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
552 // Find the first block the caller has in the main chain
553 BOOST_FOREACH(const uint256& hash, locator.vHave) {
554 BlockMap::iterator mi = mapBlockIndex.find(hash);
555 if (mi != mapBlockIndex.end())
557 CBlockIndex* pindex = (*mi).second;
558 if (pindex != 0 && chain.Contains(pindex))
562 return chain.Genesis();
565 CCoinsViewCache *pcoinsTip = NULL;
566 CBlockTreeDB *pblocktree = NULL;
573 //////////////////////////////////////////////////////////////////////////////
575 // mapOrphanTransactions
578 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
580 uint256 hash = tx.GetHash();
581 if (mapOrphanTransactions.count(hash))
584 // Ignore big transactions, to avoid a
585 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
586 // large transaction with a missing parent then we assume
587 // it will rebroadcast it later, after the parent transaction(s)
588 // have been mined or received.
589 // 10,000 orphans, each of which is at most 5,000 bytes big is
590 // at most 500 megabytes of orphans:
591 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
594 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
598 mapOrphanTransactions[hash].tx = tx;
599 mapOrphanTransactions[hash].fromPeer = peer;
600 BOOST_FOREACH(const CTxIn& txin, tx.vin)
601 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
603 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
604 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
608 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
610 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
611 if (it == mapOrphanTransactions.end())
613 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
615 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
616 if (itPrev == mapOrphanTransactionsByPrev.end())
618 itPrev->second.erase(hash);
619 if (itPrev->second.empty())
620 mapOrphanTransactionsByPrev.erase(itPrev);
622 mapOrphanTransactions.erase(it);
625 void EraseOrphansFor(NodeId peer)
628 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
629 while (iter != mapOrphanTransactions.end())
631 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
632 if (maybeErase->second.fromPeer == peer)
634 EraseOrphanTx(maybeErase->second.tx.GetHash());
638 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
642 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
644 unsigned int nEvicted = 0;
645 while (mapOrphanTransactions.size() > nMaxOrphans)
647 // Evict a random orphan:
648 uint256 randomhash = GetRandHash();
649 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
650 if (it == mapOrphanTransactions.end())
651 it = mapOrphanTransactions.begin();
652 EraseOrphanTx(it->first);
664 bool IsStandardTx(const CTransaction& tx, string& reason)
666 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
671 BOOST_FOREACH(const CTxIn& txin, tx.vin)
673 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
674 // keys. (remember the 520 byte limit on redeemScript size) That works
675 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
676 // bytes of scriptSig, which we round off to 1650 bytes for some minor
677 // future-proofing. That's also enough to spend a 20-of-20
678 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
679 // considered standard)
680 if (txin.scriptSig.size() > 1650) {
681 reason = "scriptsig-size";
684 if (!txin.scriptSig.IsPushOnly()) {
685 reason = "scriptsig-not-pushonly";
690 unsigned int v=0,nDataOut = 0;
691 txnouttype whichType;
692 BOOST_FOREACH(const CTxOut& txout, tx.vout)
694 if (!::IsStandard(txout.scriptPubKey, whichType))
696 reason = "scriptpubkey";
697 fprintf(stderr,">>>>>>>>>>>>>>> vout.%d nDataout.%d\n",v,nDataOut);
701 if (whichType == TX_NULL_DATA)
704 //fprintf(stderr,"is OP_RETURN\n");
706 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
707 reason = "bare-multisig";
709 } else if (txout.IsDust(::minRelayTxFee)) {
716 // only one OP_RETURN txout is permitted
718 reason = "multi-op-return";
725 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
728 if (tx.nLockTime == 0)
730 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
732 BOOST_FOREACH(const CTxIn& txin, tx.vin)
734 if ( txin.nSequence == 0xfffffffe && (((int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime > nBlockTime) || ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime > nBlockHeight)) )
738 else if (!txin.IsFinal())
740 //printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime);
747 bool CheckFinalTx(const CTransaction &tx, int flags)
749 AssertLockHeld(cs_main);
751 // By convention a negative value for flags indicates that the
752 // current network-enforced consensus rules should be used. In
753 // a future soft-fork scenario that would mean checking which
754 // rules would be enforced for the next block and setting the
755 // appropriate flags. At the present time no soft-forks are
756 // scheduled, so no flags are set.
757 flags = std::max(flags, 0);
759 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
760 // nLockTime because when IsFinalTx() is called within
761 // CBlock::AcceptBlock(), the height of the block *being*
762 // evaluated is what is used. Thus if we want to know if a
763 // transaction can be part of the *next* block, we need to call
764 // IsFinalTx() with one more than chainActive.Height().
765 const int nBlockHeight = chainActive.Height() + 1;
767 // Timestamps on the other hand don't get any special treatment,
768 // because we can't know what timestamp the next block will have,
769 // and there aren't timestamp applications where it matters.
770 // However this changes once median past time-locks are enforced:
771 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
772 ? chainActive.Tip()->GetMedianTimePast()
775 return IsFinalTx(tx, nBlockHeight, nBlockTime);
779 * Check transaction inputs to mitigate two
780 * potential denial-of-service attacks:
782 * 1. scriptSigs with extra data stuffed into them,
783 * not consumed by scriptPubKey (or P2SH script)
784 * 2. P2SH scripts with a crazy number of expensive
785 * CHECKSIG/CHECKMULTISIG operations
787 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
790 return true; // Coinbases don't use vin normally
792 for (unsigned int i = 0; i < tx.vin.size(); i++)
794 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
796 vector<vector<unsigned char> > vSolutions;
797 txnouttype whichType;
798 // get the scriptPubKey corresponding to this input:
799 const CScript& prevScript = prev.scriptPubKey;
800 if (!Solver(prevScript, whichType, vSolutions))
802 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
803 if (nArgsExpected < 0)
806 // Transactions with extra stuff in their scriptSigs are
807 // non-standard. Note that this EvalScript() call will
808 // be quick, because if there are any operations
809 // beside "push data" in the scriptSig
810 // IsStandardTx() will have already returned false
811 // and this method isn't called.
812 vector<vector<unsigned char> > stack;
813 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
816 if (whichType == TX_SCRIPTHASH)
820 CScript subscript(stack.back().begin(), stack.back().end());
821 vector<vector<unsigned char> > vSolutions2;
822 txnouttype whichType2;
823 if (Solver(subscript, whichType2, vSolutions2))
825 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
828 nArgsExpected += tmpExpected;
832 // Any other Script with less than 15 sigops OK:
833 unsigned int sigops = subscript.GetSigOpCount(true);
834 // ... extra data left on the stack after execution is OK, too:
835 return (sigops <= MAX_P2SH_SIGOPS);
839 if (stack.size() != (unsigned int)nArgsExpected)
846 unsigned int GetLegacySigOpCount(const CTransaction& tx)
848 unsigned int nSigOps = 0;
849 BOOST_FOREACH(const CTxIn& txin, tx.vin)
851 nSigOps += txin.scriptSig.GetSigOpCount(false);
853 BOOST_FOREACH(const CTxOut& txout, tx.vout)
855 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
860 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
865 unsigned int nSigOps = 0;
866 for (unsigned int i = 0; i < tx.vin.size(); i++)
868 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
869 if (prevout.scriptPubKey.IsPayToScriptHash())
870 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
875 bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash::ProofVerifier& verifier)
877 static uint256 array[64]; static int32_t numbanned,indallvouts; int32_t j,k,n;
878 if ( *(int32_t *)&array[0] == 0 )
879 numbanned = komodo_bannedset(&indallvouts,array,(int32_t)(sizeof(array)/sizeof(*array)));
883 for (k=0; k<numbanned; k++)
885 if ( tx.vin[j].prevout.hash == array[k] && (tx.vin[j].prevout.n == 1 || k >= indallvouts) )
887 static uint32_t counter;
888 if ( counter++ < 100 )
889 printf("MEMPOOL: banned tx.%d being used at ht.%d vout.%d\n",k,(int32_t)chainActive.Tip()->nHeight,j);
894 // Don't count coinbase transactions because mining skews the count
895 if (!tx.IsCoinBase()) {
896 transactionsValidated.increment();
899 if (!CheckTransactionWithoutProofVerification(tx, state)) {
902 // Ensure that zk-SNARKs verify
903 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
904 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
905 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
906 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
913 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
915 // Basic checks that don't depend on any context
917 // Check transaction version
918 if (tx.nVersion < MIN_TX_VERSION) {
919 return state.DoS(100, error("CheckTransaction(): version too low"),
920 REJECT_INVALID, "bad-txns-version-too-low");
923 // Transactions can contain empty `vin` and `vout` so long as
924 // `vjoinsplit` is non-empty.
925 if (tx.vin.empty() && tx.vjoinsplit.empty())
926 return state.DoS(10, error("CheckTransaction(): vin empty"),
927 REJECT_INVALID, "bad-txns-vin-empty");
928 if (tx.vout.empty() && tx.vjoinsplit.empty())
929 return state.DoS(10, error("CheckTransaction(): vout empty"),
930 REJECT_INVALID, "bad-txns-vout-empty");
933 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
934 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
935 return state.DoS(100, error("CheckTransaction(): size limits failed"),
936 REJECT_INVALID, "bad-txns-oversize");
938 // Check for negative or overflow output values
939 CAmount nValueOut = 0;
940 BOOST_FOREACH(const CTxOut& txout, tx.vout)
942 if (txout.nValue < 0)
943 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
944 REJECT_INVALID, "bad-txns-vout-negative");
945 if (txout.nValue > MAX_MONEY)
947 fprintf(stderr,"%.8f > max %.8f\n",(double)txout.nValue/COIN,(double)MAX_MONEY/COIN);
948 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),REJECT_INVALID, "bad-txns-vout-toolarge");
950 nValueOut += txout.nValue;
951 if (!MoneyRange(nValueOut))
952 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
953 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
956 // Ensure that joinsplit values are well-formed
957 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
959 if (joinsplit.vpub_old < 0) {
960 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
961 REJECT_INVALID, "bad-txns-vpub_old-negative");
964 if (joinsplit.vpub_new < 0) {
965 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
966 REJECT_INVALID, "bad-txns-vpub_new-negative");
969 if (joinsplit.vpub_old > MAX_MONEY) {
970 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
971 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
974 if (joinsplit.vpub_new > MAX_MONEY) {
975 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
976 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
979 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
980 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
981 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
984 nValueOut += joinsplit.vpub_old;
985 if (!MoneyRange(nValueOut)) {
986 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
987 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
991 // Ensure input values do not exceed MAX_MONEY
992 // We have not resolved the txin values at this stage,
993 // but we do know what the joinsplits claim to add
994 // to the value pool.
996 CAmount nValueIn = 0;
997 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
999 nValueIn += it->vpub_new;
1001 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1002 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1003 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1009 // Check for duplicate inputs
1010 set<COutPoint> vInOutPoints;
1011 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1013 if (vInOutPoints.count(txin.prevout))
1014 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1015 REJECT_INVALID, "bad-txns-inputs-duplicate");
1016 vInOutPoints.insert(txin.prevout);
1019 // Check for duplicate joinsplit nullifiers in this transaction
1020 set<uint256> vJoinSplitNullifiers;
1021 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1023 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1025 if (vJoinSplitNullifiers.count(nf))
1026 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1027 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1029 vJoinSplitNullifiers.insert(nf);
1033 if (tx.IsCoinBase())
1035 // There should be no joinsplits in a coinbase transaction
1036 if (tx.vjoinsplit.size() > 0)
1037 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1038 REJECT_INVALID, "bad-cb-has-joinsplits");
1040 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1041 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1042 REJECT_INVALID, "bad-cb-length");
1046 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1047 if (txin.prevout.IsNull())
1048 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1049 REJECT_INVALID, "bad-txns-prevout-null");
1051 if (tx.vjoinsplit.size() > 0) {
1052 // Empty output script.
1054 uint256 dataToBeSigned;
1056 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1057 } catch (std::logic_error ex) {
1058 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1059 REJECT_INVALID, "error-computing-signature-hash");
1062 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1064 // We rely on libsodium to check that the signature is canonical.
1065 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1066 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1067 dataToBeSigned.begin(), 32,
1068 tx.joinSplitPubKey.begin()
1070 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1071 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1079 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1081 extern int32_t KOMODO_ON_DEMAND;
1084 uint256 hash = tx.GetHash();
1085 double dPriorityDelta = 0;
1086 CAmount nFeeDelta = 0;
1087 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1088 if (dPriorityDelta > 0 || nFeeDelta > 0)
1092 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1096 // There is a free transaction area in blocks created by most miners,
1097 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1098 // to be considered to fall into this category. We don't want to encourage sending
1099 // multiple transactions instead of one big transaction to avoid fees.
1100 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1104 if (!MoneyRange(nMinFee))
1105 nMinFee = MAX_MONEY;
1110 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
1112 AssertLockHeld(cs_main);
1113 if (pfMissingInputs)
1114 *pfMissingInputs = false;
1115 auto verifier = libzcash::ProofVerifier::Strict();
1116 if ( komodo_validate_interest(tx,chainActive.Tip()->nHeight+1,chainActive.Tip()->GetMedianTimePast() + 777,0) < 0 )
1118 //fprintf(stderr,"AcceptToMemoryPool komodo_validate_interest failure\n");
1119 return error("AcceptToMemoryPool: komodo_validate_interest failed");
1121 if (!CheckTransaction(tx, state, verifier))
1123 fprintf(stderr,"accept failure.0\n");
1124 return error("AcceptToMemoryPool: CheckTransaction failed");
1126 // Coinbase is only valid in a block, not as a loose transaction
1127 if (tx.IsCoinBase())
1129 fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
1130 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
1132 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1134 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1136 fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str());
1137 return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
1139 // Only accept nLockTime-using transactions that can be mined in the next
1140 // block; we don't want our mempool filled up with transactions that can't
1142 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1144 //fprintf(stderr,"AcceptToMemoryPool reject non-final\n");
1145 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1147 // is it already in the memory pool?
1148 uint256 hash = tx.GetHash();
1149 if (pool.exists(hash))
1151 fprintf(stderr,"already in mempool\n");
1155 // Check for conflicts with in-memory transactions
1157 LOCK(pool.cs); // protect pool.mapNextTx
1158 for (unsigned int i = 0; i < tx.vin.size(); i++)
1160 COutPoint outpoint = tx.vin[i].prevout;
1161 if (pool.mapNextTx.count(outpoint))
1163 static uint32_t counter;
1164 // Disable replacement feature for now
1165 //if ( counter++ < 100 )
1166 fprintf(stderr,"Disable replacement feature for now\n");
1170 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1171 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1172 if (pool.mapNullifiers.count(nf))
1174 fprintf(stderr,"pool.mapNullifiers.count\n");
1183 CCoinsViewCache view(&dummy);
1185 CAmount nValueIn = 0;
1188 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1189 view.SetBackend(viewMemPool);
1191 // do we already have it?
1192 if (view.HaveCoins(hash))
1194 fprintf(stderr,"view.HaveCoins(hash) error\n");
1198 // do all inputs exist?
1199 // Note that this does not check for the presence of actual outputs (see the next check for that),
1200 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1201 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1202 if (!view.HaveCoins(txin.prevout.hash)) {
1203 if (pfMissingInputs)
1204 *pfMissingInputs = true;
1205 //fprintf(stderr,"missing inputs\n");
1210 // are the actual inputs available?
1211 if (!view.HaveInputs(tx))
1213 //fprintf(stderr,"accept failure.1\n");
1214 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent");
1216 // are the joinsplit's requirements met?
1217 if (!view.HaveJoinSplitRequirements(tx))
1219 fprintf(stderr,"accept failure.2\n");
1220 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1223 // Bring the best block into scope
1224 view.GetBestBlock();
1226 nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
1227 if ( 0 && interest != 0 )
1228 fprintf(stderr,"add interest %.8f\n",(double)interest/COIN);
1229 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1230 view.SetBackend(dummy);
1233 // Check for non-standard pay-to-script-hash in inputs
1234 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1236 fprintf(stderr,"accept failure.3\n");
1237 return error("AcceptToMemoryPool: nonstandard transaction input");
1240 // Check that the transaction doesn't have an excessive number of
1241 // sigops, making it impossible to mine. Since the coinbase transaction
1242 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1243 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1244 // merely non-standard transaction.
1245 unsigned int nSigOps = GetLegacySigOpCount(tx);
1246 nSigOps += GetP2SHSigOpCount(tx, view);
1247 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1249 fprintf(stderr,"accept failure.4\n");
1250 return state.DoS(0, error("AcceptToMemoryPool: too many sigops %s, %d > %d", hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1253 CAmount nValueOut = tx.GetValueOut();
1254 CAmount nFees = nValueIn-nValueOut;
1255 double dPriority = view.GetPriority(tx, chainActive.Height());
1257 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1258 unsigned int nSize = entry.GetTxSize();
1260 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1261 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1262 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1264 // Don't accept it if it can't get into a block
1265 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1266 if (fLimitFree && nFees < txMinFee)
1268 fprintf(stderr,"accept failure.5\n");
1269 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee");
1273 // Require that free transactions have sufficient priority to be mined in the next block.
1274 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1275 fprintf(stderr,"accept failure.6\n");
1276 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1279 // Continuously rate-limit free (really, very-low-fee) transactions
1280 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1281 // be annoying or make others' transactions take longer to confirm.
1282 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1284 static CCriticalSection csFreeLimiter;
1285 static double dFreeCount;
1286 static int64_t nLastTime;
1287 int64_t nNow = GetTime();
1289 LOCK(csFreeLimiter);
1291 // Use an exponentially decaying ~10-minute window:
1292 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1294 // -limitfreerelay unit is thousand-bytes-per-minute
1295 // At default rate it would take over a month to fill 1GB
1296 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1298 fprintf(stderr,"accept failure.7\n");
1299 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1301 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1302 dFreeCount += nSize;
1305 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000 && nFees > nValueOut/19 )
1307 fprintf(stderr,"accept failure.8\n");
1308 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1311 // Check against previous transactions
1312 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1313 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1315 fprintf(stderr,"accept failure.9\n");
1316 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1319 // Check again against just the consensus-critical mandatory script
1320 // verification flags, in case of bugs in the standard flags that cause
1321 // transactions to pass as valid when they're actually invalid. For
1322 // instance the STRICTENC flag was incorrectly allowing certain
1323 // CHECKSIG NOT scripts to pass, even though they were invalid.
1325 // There is a similar check in CreateNewBlock() to prevent creating
1326 // invalid blocks, however allowing such transactions into the mempool
1327 // can be exploited as a DoS attack.
1328 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1330 fprintf(stderr,"accept failure.10\n");
1331 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1334 // Store transaction in memory
1335 if ( komodo_is_notarytx(tx) == 0 )
1337 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1340 SyncWithWallets(tx, NULL);
1345 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1346 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1348 CBlockIndex *pindexSlow = NULL;
1352 if (mempool.lookup(hash, txOut))
1359 if (pblocktree->ReadTxIndex(hash, postx)) {
1360 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1362 return error("%s: OpenBlockFile failed", __func__);
1363 CBlockHeader header;
1366 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1368 } catch (const std::exception& e) {
1369 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1371 hashBlock = header.GetHash();
1372 if (txOut.GetHash() != hash)
1373 return error("%s: txid mismatch", __func__);
1378 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1381 CCoinsViewCache &view = *pcoinsTip;
1382 const CCoins* coins = view.AccessCoins(hash);
1384 nHeight = coins->nHeight;
1387 pindexSlow = chainActive[nHeight];
1392 if (ReadBlockFromDisk(block, pindexSlow)) {
1393 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1394 if (tx.GetHash() == hash) {
1396 hashBlock = pindexSlow->GetBlockHash();
1406 /*char *komodo_getspendscript(uint256 hash,int32_t n)
1408 CTransaction tx; uint256 hashBlock;
1409 if ( !GetTransaction(hash,tx,hashBlock,true) )
1411 printf("null GetTransaction\n");
1414 if ( n >= 0 && n < tx.vout.size() )
1415 return((char *)tx.vout[n].scriptPubKey.ToString().c_str());
1416 else printf("getspendscript illegal n.%d\n",n);
1421 //////////////////////////////////////////////////////////////////////////////
1423 // CBlock and CBlockIndex
1426 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1428 // Open history file to append
1429 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1430 if (fileout.IsNull())
1431 return error("WriteBlockToDisk: OpenBlockFile failed");
1433 // Write index header
1434 unsigned int nSize = fileout.GetSerializeSize(block);
1435 fileout << FLATDATA(messageStart) << nSize;
1438 long fileOutPos = ftell(fileout.Get());
1440 return error("WriteBlockToDisk: ftell failed");
1441 pos.nPos = (unsigned int)fileOutPos;
1447 bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos)
1449 uint8_t pubkey33[33];
1452 // Open history file to read
1453 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1454 if (filein.IsNull())
1456 //fprintf(stderr,"readblockfromdisk err A\n");
1457 return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1464 catch (const std::exception& e) {
1465 fprintf(stderr,"readblockfromdisk err B\n");
1466 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1469 komodo_block2pubkey33(pubkey33,block);
1470 if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus())))
1472 int32_t i; for (i=0; i<33; i++)
1473 printf("%02x",pubkey33[i]);
1474 fprintf(stderr," warning unexpected diff at ht.%d\n",height);
1476 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1481 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1485 if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos()))
1487 if (block.GetHash() != pindex->GetBlockHash())
1488 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1489 pindex->ToString(), pindex->GetBlockPos().ToString());
1493 //uint64_t komodo_moneysupply(int32_t height);
1494 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
1495 extern uint32_t ASSETCHAINS_MAGIC;
1496 extern uint64_t ASSETCHAINS_ENDSUBSIDY,ASSETCHAINS_REWARD,ASSETCHAINS_HALVING,ASSETCHAINS_LINEAR,ASSETCHAINS_COMMISSION,ASSETCHAINS_SUPPLY;
1498 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1500 static uint64_t cached_subsidy; static int32_t cached_numhalvings;
1501 int32_t numhalvings,i; uint64_t numerator; CAmount nSubsidy = 3 * COIN;
1502 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1505 return(100000000 * COIN); // ICO allocation
1506 else if ( nHeight < KOMODO_ENDOFERA ) //komodo_moneysupply(nHeight) < MAX_MONEY )
1513 return(ASSETCHAINS_SUPPLY * COIN + (ASSETCHAINS_MAGIC & 0xffffff));
1514 else if ( ASSETCHAINS_ENDSUBSIDY == 0 || nHeight < ASSETCHAINS_ENDSUBSIDY )
1516 if ( ASSETCHAINS_REWARD == 0 )
1518 else if ( ASSETCHAINS_ENDSUBSIDY != 0 && nHeight >= ASSETCHAINS_ENDSUBSIDY )
1522 nSubsidy = ASSETCHAINS_REWARD;
1523 if ( ASSETCHAINS_HALVING != 0 )
1525 if ( (numhalvings= (nHeight / ASSETCHAINS_HALVING)) > 0 )
1527 if ( numhalvings >= 64 && ASSETCHAINS_DECAY == 0 )
1529 if ( ASSETCHAINS_DECAY == 0 )
1530 nSubsidy >>= numhalvings;
1531 else if ( ASSETCHAINS_DECAY == 100000000 && ASSETCHAINS_ENDSUBSIDY != 0 )
1533 numerator = (ASSETCHAINS_ENDSUBSIDY - nHeight);
1534 nSubsidy = (nSubsidy * numerator) / ASSETCHAINS_ENDSUBSIDY;
1538 if ( cached_subsidy > 0 && cached_numhalvings == numhalvings )
1539 nSubsidy = cached_subsidy;
1542 for (i=0; i<numhalvings&&nSubsidy!=0; i++)
1543 nSubsidy = (nSubsidy * ASSETCHAINS_DECAY) / 100000000;
1544 cached_subsidy = nSubsidy;
1545 cached_numhalvings = numhalvings;
1555 // Mining slow start
1556 // The subsidy is ramped up linearly, skipping the middle payout of
1557 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1558 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1559 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1560 nSubsidy *= nHeight;
1562 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1563 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1564 nSubsidy *= (nHeight+1);
1568 assert(nHeight > consensusParams.SubsidySlowStartShift());
1569 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/
1570 // Force block reward to zero when right shift is undefined.
1571 //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1572 //if (halvings >= 64)
1575 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1576 //nSubsidy >>= halvings;
1580 bool IsInitialBlockDownload()
1582 const CChainParams& chainParams = Params();
1584 if (fImporting || fReindex)
1586 //fprintf(stderr,"IsInitialBlockDownload: fImporting %d || %d fReindex\n",(int32_t)fImporting,(int32_t)fReindex);
1589 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1591 //fprintf(stderr,"IsInitialBlockDownload: checkpoint -> initialdownload\n");
1594 static bool lockIBDState = false;
1597 //fprintf(stderr,"lockIBDState true %d < %d\n",chainActive.Height(),pindexBestHeader->nHeight - 10);
1600 bool state; CBlockIndex *ptr = chainActive.Tip();
1602 ptr = pindexBestHeader;
1603 else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight )
1604 ptr = pindexBestHeader;
1605 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1606 state = ((chainActive.Height() < ptr->nHeight - 24*60) ||
1607 ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge()));
1608 else state = (chainActive.Height() < ptr->nHeight - 10);
1609 //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()));
1612 lockIBDState = true;
1617 bool fLargeWorkForkFound = false;
1618 bool fLargeWorkInvalidChainFound = false;
1619 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1621 void CheckForkWarningConditions()
1623 AssertLockHeld(cs_main);
1624 // Before we get past initial download, we cannot reliably alert about forks
1625 // (we assume we don't get stuck on a fork before the last checkpoint)
1626 if (IsInitialBlockDownload())
1629 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1630 // of our head, drop it
1631 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1632 pindexBestForkTip = NULL;
1634 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1636 if (!fLargeWorkForkFound && pindexBestForkBase)
1638 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1639 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1640 CAlert::Notify(warning, true);
1642 if (pindexBestForkTip && pindexBestForkBase)
1644 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__,
1645 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1646 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1647 fLargeWorkForkFound = true;
1651 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1652 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1653 CAlert::Notify(warning, true);
1654 fLargeWorkInvalidChainFound = true;
1659 fLargeWorkForkFound = false;
1660 fLargeWorkInvalidChainFound = false;
1664 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1666 AssertLockHeld(cs_main);
1667 // If we are on a fork that is sufficiently large, set a warning flag
1668 CBlockIndex* pfork = pindexNewForkTip;
1669 CBlockIndex* plonger = chainActive.Tip();
1670 while (pfork && pfork != plonger)
1672 while (plonger && plonger->nHeight > pfork->nHeight)
1673 plonger = plonger->pprev;
1674 if (pfork == plonger)
1676 pfork = pfork->pprev;
1679 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1680 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1681 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1682 // hash rate operating on the fork.
1683 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1684 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1685 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1686 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1687 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1688 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1690 pindexBestForkTip = pindexNewForkTip;
1691 pindexBestForkBase = pfork;
1694 CheckForkWarningConditions();
1697 // Requires cs_main.
1698 void Misbehaving(NodeId pnode, int howmuch)
1703 CNodeState *state = State(pnode);
1707 state->nMisbehavior += howmuch;
1708 int banscore = GetArg("-banscore", 100);
1709 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1711 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1712 state->fShouldBan = true;
1714 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1717 void static InvalidChainFound(CBlockIndex* pindexNew)
1719 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1720 pindexBestInvalid = pindexNew;
1722 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1723 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1724 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1725 pindexNew->GetBlockTime()));
1726 CBlockIndex *tip = chainActive.Tip();
1728 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1729 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1730 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1731 CheckForkWarningConditions();
1734 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1736 if (state.IsInvalid(nDoS)) {
1737 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1738 if (it != mapBlockSource.end() && State(it->second)) {
1739 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1740 State(it->second)->rejects.push_back(reject);
1742 Misbehaving(it->second, nDoS);
1745 if (!state.CorruptionPossible()) {
1746 pindex->nStatus |= BLOCK_FAILED_VALID;
1747 setDirtyBlockIndex.insert(pindex);
1748 setBlockIndexCandidates.erase(pindex);
1749 InvalidChainFound(pindex);
1753 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1755 if (!tx.IsCoinBase()) // mark inputs spent
1757 txundo.vprevout.reserve(tx.vin.size());
1758 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1759 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1760 unsigned nPos = txin.prevout.n;
1762 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1764 // mark an outpoint spent, and construct undo information
1765 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1767 if (coins->vout.size() == 0) {
1768 CTxInUndo& undo = txundo.vprevout.back();
1769 undo.nHeight = coins->nHeight;
1770 undo.fCoinBase = coins->fCoinBase;
1771 undo.nVersion = coins->nVersion;
1775 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { // spend nullifiers
1776 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1777 inputs.SetNullifier(nf, true);
1780 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); // add outputs
1783 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1786 UpdateCoins(tx, state, inputs, txundo, nHeight);
1789 bool CScriptCheck::operator()() {
1790 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1791 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1792 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1797 int GetSpendHeight(const CCoinsViewCache& inputs)
1800 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1801 return pindexPrev->nHeight + 1;
1804 namespace Consensus {
1805 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1807 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1808 // for an attacker to attempt to split the network.
1809 if (!inputs.HaveInputs(tx))
1810 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1812 // are the JoinSplit's requirements met?
1813 if (!inputs.HaveJoinSplitRequirements(tx))
1814 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1816 CAmount nValueIn = 0;
1818 for (unsigned int i = 0; i < tx.vin.size(); i++)
1820 const COutPoint &prevout = tx.vin[i].prevout;
1821 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1824 if (coins->IsCoinBase()) {
1825 // Ensure that coinbases are matured
1826 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1827 return state.Invalid(
1828 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1829 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1832 // Ensure that coinbases cannot be spent to transparent outputs
1833 // Disabled on regtest
1834 if (fCoinbaseEnforcedProtectionEnabled &&
1835 consensusParams.fCoinbaseMustBeProtected &&
1837 return state.Invalid(
1838 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1839 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1843 // Check for negative or overflow input values
1844 nValueIn += coins->vout[prevout.n].nValue;
1845 #ifdef KOMODO_ENABLE_INTEREST
1846 if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 )
1848 if ( coins->vout[prevout.n].nValue >= 10*COIN )
1850 int64_t interest; int32_t txheight; uint32_t locktime;
1851 if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue)) != 0 )
1853 //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);
1854 nValueIn += interest;
1859 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1860 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1861 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1865 nValueIn += tx.GetJoinSplitValueIn();
1866 if (!MoneyRange(nValueIn))
1867 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1868 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1870 if (nValueIn < tx.GetValueOut())
1871 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f",
1872 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout");
1874 // Tally transaction fees
1875 CAmount nTxFee = nValueIn - tx.GetValueOut();
1877 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1878 REJECT_INVALID, "bad-txns-fee-negative");
1880 if (!MoneyRange(nFees))
1881 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1882 REJECT_INVALID, "bad-txns-fee-outofrange");
1885 }// namespace Consensus
1887 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)
1889 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams))
1892 if (!tx.IsCoinBase())
1895 pvChecks->reserve(tx.vin.size());
1897 // The first loop above does all the inexpensive checks.
1898 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1899 // Helps prevent CPU exhaustion attacks.
1901 // Skip ECDSA signature verification when connecting blocks
1902 // before the last block chain checkpoint. This is safe because block merkle hashes are
1903 // still computed and checked, and any change will be caught at the next checkpoint.
1904 if (fScriptChecks) {
1905 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1906 const COutPoint &prevout = tx.vin[i].prevout;
1907 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1911 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1913 pvChecks->push_back(CScriptCheck());
1914 check.swap(pvChecks->back());
1915 } else if (!check()) {
1916 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1917 // Check whether the failure was caused by a
1918 // non-mandatory script verification check, such as
1919 // non-standard DER encodings or non-null dummy
1920 // arguments; if so, don't trigger DoS protection to
1921 // avoid splitting the network between upgraded and
1922 // non-upgraded nodes.
1923 CScriptCheck check(*coins, tx, i,
1924 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1926 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1928 // Failures of other flags indicate a transaction that is
1929 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1930 // such nodes as they are not following the protocol. That
1931 // said during an upgrade careful thought should be taken
1932 // as to the correct behavior - we may want to continue
1933 // peering with non-upgraded nodes even after a soft-fork
1934 // super-majority vote has passed.
1935 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1945 /*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)
1947 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1948 fprintf(stderr,"ContextualCheckInputs failure.0\n");
1952 if (!tx.IsCoinBase())
1954 // While checking, GetBestBlock() refers to the parent block.
1955 // This is also true for mempool checks.
1956 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1957 int nSpendHeight = pindexPrev->nHeight + 1;
1958 for (unsigned int i = 0; i < tx.vin.size(); i++)
1960 const COutPoint &prevout = tx.vin[i].prevout;
1961 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1962 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1966 // If prev is coinbase, check that it's matured
1967 if (coins->IsCoinBase()) {
1968 if ( ASSETCHAINS_SYMBOL[0] == 0 )
1969 COINBASE_MATURITY = _COINBASE_MATURITY;
1970 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1971 fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size());
1973 return state.Invalid(
1974 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1985 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1987 // Open history file to append
1988 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1989 if (fileout.IsNull())
1990 return error("%s: OpenUndoFile failed", __func__);
1992 // Write index header
1993 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1994 fileout << FLATDATA(messageStart) << nSize;
1997 long fileOutPos = ftell(fileout.Get());
1999 return error("%s: ftell failed", __func__);
2000 pos.nPos = (unsigned int)fileOutPos;
2001 fileout << blockundo;
2003 // calculate & write checksum
2004 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2005 hasher << hashBlock;
2006 hasher << blockundo;
2007 fileout << hasher.GetHash();
2012 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
2014 // Open history file to read
2015 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
2016 if (filein.IsNull())
2017 return error("%s: OpenBlockFile failed", __func__);
2020 uint256 hashChecksum;
2022 filein >> blockundo;
2023 filein >> hashChecksum;
2025 catch (const std::exception& e) {
2026 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2030 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2031 hasher << hashBlock;
2032 hasher << blockundo;
2033 if (hashChecksum != hasher.GetHash())
2034 return error("%s: Checksum mismatch", __func__);
2039 /** Abort with a message */
2040 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2042 strMiscWarning = strMessage;
2043 LogPrintf("*** %s\n", strMessage);
2044 uiInterface.ThreadSafeMessageBox(
2045 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2046 "", CClientUIInterface::MSG_ERROR);
2051 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2053 AbortNode(strMessage, userMessage);
2054 return state.Error(strMessage);
2060 * Apply the undo operation of a CTxInUndo to the given chain state.
2061 * @param undo The undo object.
2062 * @param view The coins view to which to apply the changes.
2063 * @param out The out point that corresponds to the tx input.
2064 * @return True on success.
2066 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2070 CCoinsModifier coins = view.ModifyCoins(out.hash);
2071 if (undo.nHeight != 0) {
2072 // undo data contains height: this is the last output of the prevout tx being spent
2073 if (!coins->IsPruned())
2074 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2076 coins->fCoinBase = undo.fCoinBase;
2077 coins->nHeight = undo.nHeight;
2078 coins->nVersion = undo.nVersion;
2080 if (coins->IsPruned())
2081 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2083 if (coins->IsAvailable(out.n))
2084 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2085 if (coins->vout.size() < out.n+1)
2086 coins->vout.resize(out.n+1);
2087 coins->vout[out.n] = undo.txout;
2092 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2094 assert(pindex->GetBlockHash() == view.GetBestBlock());
2100 komodo_disconnect(pindex,block);
2101 CBlockUndo blockUndo;
2102 CDiskBlockPos pos = pindex->GetUndoPos();
2104 return error("DisconnectBlock(): no undo data available");
2105 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2106 return error("DisconnectBlock(): failure reading undo data");
2108 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2109 return error("DisconnectBlock(): block and undo data inconsistent");
2111 // undo transactions in reverse order
2112 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2113 const CTransaction &tx = block.vtx[i];
2114 uint256 hash = tx.GetHash();
2116 // Check that all outputs are available and match the outputs in the block itself
2119 CCoinsModifier outs = view.ModifyCoins(hash);
2120 outs->ClearUnspendable();
2122 CCoins outsBlock(tx, pindex->nHeight);
2123 // The CCoins serialization does not serialize negative numbers.
2124 // No network rules currently depend on the version here, so an inconsistency is harmless
2125 // but it must be corrected before txout nversion ever influences a network rule.
2126 if (outsBlock.nVersion < 0)
2127 outs->nVersion = outsBlock.nVersion;
2128 if (*outs != outsBlock)
2129 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2135 // unspend nullifiers
2136 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2137 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2138 view.SetNullifier(nf, false);
2143 if (i > 0) { // not coinbases
2144 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2145 if (txundo.vprevout.size() != tx.vin.size())
2146 return error("DisconnectBlock(): transaction and undo data inconsistent");
2147 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2148 const COutPoint &out = tx.vin[j].prevout;
2149 const CTxInUndo &undo = txundo.vprevout[j];
2150 if (!ApplyTxInUndo(undo, view, out))
2156 // set the old best anchor back
2157 view.PopAnchor(blockUndo.old_tree_root);
2159 // move best block pointer to prevout block
2160 view.SetBestBlock(pindex->pprev->GetBlockHash());
2170 void static FlushBlockFile(bool fFinalize = false)
2172 LOCK(cs_LastBlockFile);
2174 CDiskBlockPos posOld(nLastBlockFile, 0);
2176 FILE *fileOld = OpenBlockFile(posOld);
2179 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2180 FileCommit(fileOld);
2184 fileOld = OpenUndoFile(posOld);
2187 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2188 FileCommit(fileOld);
2193 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2195 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2197 void ThreadScriptCheck() {
2198 RenameThread("zcash-scriptch");
2199 scriptcheckqueue.Thread();
2203 // Called periodically asynchronously; alerts if it smells like
2204 // we're being fed a bad chain (blocks being generated much
2205 // too slowly or too quickly).
2207 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2208 int64_t nPowTargetSpacing)
2210 if (bestHeader == NULL || initialDownloadCheck()) return;
2212 static int64_t lastAlertTime = 0;
2213 int64_t now = GetAdjustedTime();
2214 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2216 const int SPAN_HOURS=4;
2217 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2218 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2220 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2222 std::string strWarning;
2223 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2226 const CBlockIndex* i = bestHeader;
2228 while (i->GetBlockTime() >= startTime) {
2231 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2234 // How likely is it to find that many by chance?
2235 double p = boost::math::pdf(poisson, nBlocks);
2237 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2238 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2240 // Aim for one false-positive about every fifty years of normal running:
2241 const int FIFTY_YEARS = 50*365*24*60*60;
2242 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2244 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2246 // Many fewer blocks than expected: alert!
2247 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2248 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2250 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2252 // Many more blocks than expected: alert!
2253 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2254 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2256 if (!strWarning.empty())
2258 strMiscWarning = strWarning;
2259 CAlert::Notify(strWarning, true);
2260 lastAlertTime = now;
2264 static int64_t nTimeVerify = 0;
2265 static int64_t nTimeConnect = 0;
2266 static int64_t nTimeIndex = 0;
2267 static int64_t nTimeCallbacks = 0;
2268 static int64_t nTimeTotal = 0;
2270 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2272 const CChainParams& chainparams = Params();
2273 //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight);
2274 AssertLockHeld(cs_main);
2276 // Check it again in case a previous version let a bad block in
2277 bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2280 bool fExpensiveChecks = true;
2281 if (fCheckpointsEnabled) {
2282 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2283 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2284 // This block is an ancestor of a checkpoint: disable script checks
2285 fExpensiveChecks = false;
2288 //>>>>>>> zcash/master
2289 auto verifier = libzcash::ProofVerifier::Strict();
2290 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2292 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2293 if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2296 // verify that the view's current state corresponds to the previous block
2297 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2298 assert(hashPrevBlock == view.GetBestBlock());
2300 // Special case for the genesis block, skipping connection of its transactions
2301 // (its coinbase is unspendable)
2302 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2304 view.SetBestBlock(pindex->GetBlockHash());
2305 // Before the genesis block, there was an empty tree
2306 ZCIncrementalMerkleTree tree;
2307 pindex->hashAnchor = tree.root();
2308 // The genesis block contained no JoinSplits
2309 pindex->hashAnchorEnd = pindex->hashAnchor;
2314 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2315 //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet"
2317 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2318 // unless those are already completely spent.
2319 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2320 const CCoins* coins = view.AccessCoins(tx.GetHash());
2321 if (coins && !coins->IsPruned())
2322 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2323 REJECT_INVALID, "bad-txns-BIP30");
2326 unsigned int flags = SCRIPT_VERIFY_P2SH;
2328 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2329 // when 75% of the network has upgraded:
2330 if (block.nVersion >= 3) {
2331 flags |= SCRIPT_VERIFY_DERSIG;
2334 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2335 // blocks, when 75% of the network has upgraded:
2336 if (block.nVersion >= 4) {
2337 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2340 CBlockUndo blockundo;
2342 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2344 int64_t nTimeStart = GetTimeMicros();
2347 int64_t interest,sum = 0;
2348 unsigned int nSigOps = 0;
2349 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2350 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2351 vPos.reserve(block.vtx.size());
2352 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2354 // Construct the incremental merkle tree at the current
2356 auto old_tree_root = view.GetBestAnchor();
2357 // saving the top anchor in the block index as we go.
2359 pindex->hashAnchor = old_tree_root;
2361 ZCIncrementalMerkleTree tree;
2362 // This should never fail: we should always be able to get the root
2363 // that is on the tip of our chain
2364 assert(view.GetAnchorAt(old_tree_root, tree));
2367 // Consistency check: the root of the tree we're given should
2368 // match what we asked for.
2369 assert(tree.root() == old_tree_root);
2372 for (unsigned int i = 0; i < block.vtx.size(); i++)
2374 const CTransaction &tx = block.vtx[i];
2375 nInputs += tx.vin.size();
2376 nSigOps += GetLegacySigOpCount(tx);
2377 if (nSigOps > MAX_BLOCK_SIGOPS)
2378 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2379 REJECT_INVALID, "bad-blk-sigops");
2380 //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
2381 if (!tx.IsCoinBase())
2383 if (!view.HaveInputs(tx))
2384 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2385 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2387 // are the JoinSplit's requirements met?
2388 if (!view.HaveJoinSplitRequirements(tx))
2389 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2390 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2392 // Add in sigops done by pay-to-script-hash inputs;
2393 // this is to prevent a "rogue miner" from creating
2394 // an incredibly-expensive-to-validate block.
2395 nSigOps += GetP2SHSigOpCount(tx, view);
2396 if (nSigOps > MAX_BLOCK_SIGOPS)
2397 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2398 REJECT_INVALID, "bad-blk-sigops");
2400 nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
2402 std::vector<CScriptCheck> vChecks;
2403 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2405 control.Add(vChecks);
2407 //if ( ASSETCHAINS_SYMBOL[0] == 0 )
2408 // komodo_earned_interest(pindex->nHeight,sum);
2411 blockundo.vtxundo.push_back(CTxUndo());
2413 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2415 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2416 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2417 // Insert the note commitments into our temporary tree.
2419 tree.append(note_commitment);
2423 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2424 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2427 view.PushAnchor(tree);
2429 pindex->hashAnchorEnd = tree.root();
2431 blockundo.old_tree_root = old_tree_root;
2433 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2434 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);
2436 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2437 if (block.vtx[0].vout[0].nValue > blockReward)
2438 //if (block.vtx[0].GetValueOut() > blockReward)
2439 return state.DoS(100,
2440 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2441 block.vtx[0].GetValueOut(), blockReward),
2442 REJECT_INVALID, "bad-cb-amount");
2444 if (!control.Wait())
2445 return state.DoS(100, false);
2446 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2447 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);
2452 // Write undo information to disk
2453 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2455 if (pindex->GetUndoPos().IsNull()) {
2457 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2458 return error("ConnectBlock(): FindUndoPos failed");
2459 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2460 return AbortNode(state, "Failed to write undo data");
2462 // update nUndoPos in block index
2463 pindex->nUndoPos = pos.nPos;
2464 pindex->nStatus |= BLOCK_HAVE_UNDO;
2467 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2468 setDirtyBlockIndex.insert(pindex);
2472 if (!pblocktree->WriteTxIndex(vPos))
2473 return AbortNode(state, "Failed to write transaction index");
2475 // add this block to the view's block chain
2476 view.SetBestBlock(pindex->GetBlockHash());
2478 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2479 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2481 // Watch for changes to the previous coinbase transaction.
2482 static uint256 hashPrevBestCoinBase;
2483 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2484 hashPrevBestCoinBase = block.vtx[0].GetHash();
2486 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2487 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2489 //FlushStateToDisk();
2490 komodo_connectblock(pindex,*(CBlock *)&block);
2494 enum FlushStateMode {
2496 FLUSH_STATE_IF_NEEDED,
2497 FLUSH_STATE_PERIODIC,
2502 * Update the on-disk chain state.
2503 * The caches and indexes are flushed depending on the mode we're called with
2504 * if they're too large, if it's been a while since the last write,
2505 * or always and in all cases if we're in prune mode and are deleting files.
2507 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2508 LOCK2(cs_main, cs_LastBlockFile);
2509 static int64_t nLastWrite = 0;
2510 static int64_t nLastFlush = 0;
2511 static int64_t nLastSetChain = 0;
2512 std::set<int> setFilesToPrune;
2513 bool fFlushForPrune = false;
2515 if (fPruneMode && fCheckForPruning && !fReindex) {
2516 FindFilesToPrune(setFilesToPrune);
2517 fCheckForPruning = false;
2518 if (!setFilesToPrune.empty()) {
2519 fFlushForPrune = true;
2521 pblocktree->WriteFlag("prunedblockfiles", true);
2526 int64_t nNow = GetTimeMicros();
2527 // Avoid writing/flushing immediately after startup.
2528 if (nLastWrite == 0) {
2531 if (nLastFlush == 0) {
2534 if (nLastSetChain == 0) {
2535 nLastSetChain = nNow;
2537 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2538 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2539 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2540 // The cache is over the limit, we have to write now.
2541 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2542 // 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.
2543 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2544 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2545 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2546 // Combine all conditions that result in a full cache flush.
2547 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2548 // Write blocks and block index to disk.
2549 if (fDoFullFlush || fPeriodicWrite) {
2550 // Depend on nMinDiskSpace to ensure we can write block index
2551 if (!CheckDiskSpace(0))
2552 return state.Error("out of disk space");
2553 // First make sure all block and undo data is flushed to disk.
2555 // Then update all block file information (which may refer to block and undo files).
2557 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2558 vFiles.reserve(setDirtyFileInfo.size());
2559 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2560 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2561 setDirtyFileInfo.erase(it++);
2563 std::vector<const CBlockIndex*> vBlocks;
2564 vBlocks.reserve(setDirtyBlockIndex.size());
2565 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2566 vBlocks.push_back(*it);
2567 setDirtyBlockIndex.erase(it++);
2569 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2570 return AbortNode(state, "Files to write to block index database");
2573 // Finally remove any pruned files
2575 UnlinkPrunedFiles(setFilesToPrune);
2578 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2580 // Typical CCoins structures on disk are around 128 bytes in size.
2581 // Pushing a new one to the database can cause it to be written
2582 // twice (once in the log, and once in the tables). This is already
2583 // an overestimation, as most will delete an existing entry or
2584 // overwrite one. Still, use a conservative safety factor of 2.
2585 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2586 return state.Error("out of disk space");
2587 // Flush the chainstate (which may refer to block index entries).
2588 if (!pcoinsTip->Flush())
2589 return AbortNode(state, "Failed to write to coin database");
2592 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2593 // Update best block in wallet (so we can detect restored wallets).
2594 GetMainSignals().SetBestChain(chainActive.GetLocator());
2595 nLastSetChain = nNow;
2597 } catch (const std::runtime_error& e) {
2598 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2603 void FlushStateToDisk() {
2604 CValidationState state;
2605 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2608 void PruneAndFlush() {
2609 CValidationState state;
2610 fCheckForPruning = true;
2611 FlushStateToDisk(state, FLUSH_STATE_NONE);
2614 /** Update chainActive and related internal data structures. */
2615 void static UpdateTip(CBlockIndex *pindexNew) {
2616 const CChainParams& chainParams = Params();
2617 chainActive.SetTip(pindexNew);
2620 nTimeBestReceived = GetTime();
2621 mempool.AddTransactionsUpdated(1);
2623 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2624 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2625 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2626 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2628 cvBlockChange.notify_all();
2630 // Check the version of the last 100 blocks to see if we need to upgrade:
2631 static bool fWarned = false;
2632 if (!IsInitialBlockDownload() && !fWarned)
2635 const CBlockIndex* pindex = chainActive.Tip();
2636 for (int i = 0; i < 100 && pindex != NULL; i++)
2638 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2640 pindex = pindex->pprev;
2643 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2644 if (nUpgraded > 100/2)
2646 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2647 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2648 CAlert::Notify(strMiscWarning, true);
2654 /** Disconnect chainActive's tip. */
2655 bool static DisconnectTip(CValidationState &state) {
2656 CBlockIndex *pindexDelete = chainActive.Tip();
2657 assert(pindexDelete);
2658 mempool.check(pcoinsTip);
2659 // Read block from disk.
2661 if (!ReadBlockFromDisk(block, pindexDelete))
2662 return AbortNode(state, "Failed to read block");
2663 // Apply the block atomically to the chain state.
2664 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2665 int64_t nStart = GetTimeMicros();
2667 CCoinsViewCache view(pcoinsTip);
2668 if (!DisconnectBlock(block, state, pindexDelete, view))
2669 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2670 assert(view.Flush());
2672 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2673 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2674 // Write the chain state to disk, if necessary.
2675 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2677 // Resurrect mempool transactions from the disconnected block.
2678 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2679 // ignore validation errors in resurrected transactions
2680 list<CTransaction> removed;
2681 CValidationState stateDummy;
2682 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2683 mempool.remove(tx, removed, true);
2685 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2686 // The anchor may not change between block disconnects,
2687 // in which case we don't want to evict from the mempool yet!
2688 mempool.removeWithAnchor(anchorBeforeDisconnect);
2690 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2691 mempool.check(pcoinsTip);
2692 // Update chainActive and related variables.
2693 UpdateTip(pindexDelete->pprev);
2694 // Get the current commitment tree
2695 ZCIncrementalMerkleTree newTree;
2696 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2697 // Let wallets know transactions went from 1-confirmed to
2698 // 0-confirmed or conflicted:
2699 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2700 SyncWithWallets(tx, NULL);
2702 // Update cached incremental witnesses
2703 //fprintf(stderr,"chaintip false\n");
2704 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2708 static int64_t nTimeReadFromDisk = 0;
2709 static int64_t nTimeConnectTotal = 0;
2710 static int64_t nTimeFlush = 0;
2711 static int64_t nTimeChainState = 0;
2712 static int64_t nTimePostConnect = 0;
2715 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2716 * corresponding to pindexNew, to bypass loading it again from disk.
2718 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2720 assert(pindexNew->pprev == chainActive.Tip());
2721 mempool.check(pcoinsTip);
2722 // Read block from disk.
2723 int64_t nTime1 = GetTimeMicros();
2726 if (!ReadBlockFromDisk(block, pindexNew))
2727 return AbortNode(state, "Failed to read block");
2730 // Get the current commitment tree
2731 ZCIncrementalMerkleTree oldTree;
2732 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2733 // Apply the block atomically to the chain state.
2734 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2736 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2738 CCoinsViewCache view(pcoinsTip);
2739 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2740 GetMainSignals().BlockChecked(*pblock, state);
2742 if (state.IsInvalid())
2743 InvalidBlockFound(pindexNew, state);
2744 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2746 mapBlockSource.erase(pindexNew->GetBlockHash());
2747 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2748 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2749 assert(view.Flush());
2751 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2752 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2753 // Write the chain state to disk, if necessary.
2754 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2756 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2757 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2758 // Remove conflicting transactions from the mempool.
2759 list<CTransaction> txConflicted;
2760 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2761 mempool.check(pcoinsTip);
2762 // Update chainActive & related variables.
2763 UpdateTip(pindexNew);
2764 // Tell wallet about transactions that went from mempool
2766 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2767 SyncWithWallets(tx, NULL);
2769 // ... and about transactions that got confirmed:
2770 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2771 SyncWithWallets(tx, pblock);
2773 // Update cached incremental witnesses
2774 //fprintf(stderr,"chaintip true\n");
2775 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2777 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2778 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2779 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2784 * Return the tip of the chain with the most work in it, that isn't
2785 * known to be invalid (it's however far from certain to be valid).
2787 static CBlockIndex* FindMostWorkChain() {
2789 CBlockIndex *pindexNew = NULL;
2791 // Find the best candidate header.
2793 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2794 if (it == setBlockIndexCandidates.rend())
2799 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2800 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2801 CBlockIndex *pindexTest = pindexNew;
2802 bool fInvalidAncestor = false;
2803 while (pindexTest && !chainActive.Contains(pindexTest)) {
2804 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2806 // Pruned nodes may have entries in setBlockIndexCandidates for
2807 // which block files have been deleted. Remove those as candidates
2808 // for the most work chain if we come across them; we can't switch
2809 // to a chain unless we have all the non-active-chain parent blocks.
2810 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2811 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2812 if (fFailedChain || fMissingData) {
2813 // Candidate chain is not usable (either invalid or missing data)
2814 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2815 pindexBestInvalid = pindexNew;
2816 CBlockIndex *pindexFailed = pindexNew;
2817 // Remove the entire chain from the set.
2818 while (pindexTest != pindexFailed) {
2820 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2821 } else if (fMissingData) {
2822 // If we're missing data, then add back to mapBlocksUnlinked,
2823 // so that if the block arrives in the future we can try adding
2824 // to setBlockIndexCandidates again.
2825 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2827 setBlockIndexCandidates.erase(pindexFailed);
2828 pindexFailed = pindexFailed->pprev;
2830 setBlockIndexCandidates.erase(pindexTest);
2831 fInvalidAncestor = true;
2834 pindexTest = pindexTest->pprev;
2836 if (!fInvalidAncestor)
2841 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2842 static void PruneBlockIndexCandidates() {
2843 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2844 // reorganization to a better block fails.
2845 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2846 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2847 setBlockIndexCandidates.erase(it++);
2849 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2850 assert(!setBlockIndexCandidates.empty());
2854 * Try to make some progress towards making pindexMostWork the active block.
2855 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2857 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2858 AssertLockHeld(cs_main);
2859 bool fInvalidFound = false;
2860 const CBlockIndex *pindexOldTip = chainActive.Tip();
2861 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2863 // Disconnect active blocks which are no longer in the best chain.
2864 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2865 if (!DisconnectTip(state))
2868 if ( KOMODO_REWIND != 0 )
2870 fprintf(stderr,"rewind start ht.%d\n",chainActive.Tip()->nHeight);
2871 while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND )
2873 if ( !DisconnectTip(state) )
2875 InvalidateBlock(state,chainActive.Tip());
2879 fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli stop\n",KOMODO_REWIND);
2884 // Build list of new blocks to connect.
2885 std::vector<CBlockIndex*> vpindexToConnect;
2886 bool fContinue = true;
2887 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2888 while (fContinue && nHeight != pindexMostWork->nHeight) {
2889 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2890 // a few blocks along the way.
2891 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2892 vpindexToConnect.clear();
2893 vpindexToConnect.reserve(nTargetHeight - nHeight);
2894 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2895 while (pindexIter && pindexIter->nHeight != nHeight) {
2896 vpindexToConnect.push_back(pindexIter);
2897 pindexIter = pindexIter->pprev;
2899 nHeight = nTargetHeight;
2901 // Connect new blocks.
2902 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2903 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2904 if (state.IsInvalid()) {
2905 // The block violates a consensus rule.
2906 if (!state.CorruptionPossible())
2907 InvalidChainFound(vpindexToConnect.back());
2908 state = CValidationState();
2909 fInvalidFound = true;
2913 // A system error occurred (disk space, database error, ...).
2917 PruneBlockIndexCandidates();
2918 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2919 // We're in a better position than we were. Return temporarily to release the lock.
2927 // Callbacks/notifications for a new best chain.
2929 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2931 CheckForkWarningConditions();
2937 * Make the best chain active, in multiple steps. The result is either failure
2938 * or an activated best chain. pblock is either NULL or a pointer to a block
2939 * that is already loaded (to avoid loading it again from disk).
2941 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2942 CBlockIndex *pindexNewTip = NULL;
2943 CBlockIndex *pindexMostWork = NULL;
2944 const CChainParams& chainParams = Params();
2946 boost::this_thread::interruption_point();
2948 bool fInitialDownload;
2951 pindexMostWork = FindMostWorkChain();
2953 // Whether we have anything to do at all.
2954 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2957 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2959 pindexNewTip = chainActive.Tip();
2960 fInitialDownload = IsInitialBlockDownload();
2962 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2964 // Notifications/callbacks that can run without cs_main
2965 if (!fInitialDownload) {
2966 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2967 // Relay inventory, but don't relay old inventory during initial block download.
2968 int nBlockEstimate = 0;
2969 if (fCheckpointsEnabled)
2970 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2971 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2972 // in a stalled download if the block file is pruned before the request.
2973 if (nLocalServices & NODE_NETWORK) {
2975 BOOST_FOREACH(CNode* pnode, vNodes)
2976 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2977 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2979 // Notify external listeners about the new tip.
2980 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2981 uiInterface.NotifyBlockTip(hashNewTip);
2982 } //else fprintf(stderr,"initial download skips propagation\n");
2983 } while(pindexMostWork != chainActive.Tip());
2986 // Write changes periodically to disk, after relay.
2987 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2994 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2995 AssertLockHeld(cs_main);
2997 // Mark the block itself as invalid.
2998 pindex->nStatus |= BLOCK_FAILED_VALID;
2999 setDirtyBlockIndex.insert(pindex);
3000 setBlockIndexCandidates.erase(pindex);
3002 while (chainActive.Contains(pindex)) {
3003 CBlockIndex *pindexWalk = chainActive.Tip();
3004 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3005 setDirtyBlockIndex.insert(pindexWalk);
3006 setBlockIndexCandidates.erase(pindexWalk);
3007 // ActivateBestChain considers blocks already in chainActive
3008 // unconditionally valid already, so force disconnect away from it.
3009 if (!DisconnectTip(state)) {
3013 //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
3015 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3017 BlockMap::iterator it = mapBlockIndex.begin();
3018 while (it != mapBlockIndex.end() && it->second != 0 ) {
3019 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3020 setBlockIndexCandidates.insert(it->second);
3025 InvalidChainFound(pindex);
3029 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
3030 AssertLockHeld(cs_main);
3032 int nHeight = pindex->nHeight;
3034 // Remove the invalidity flag from this block and all its descendants.
3035 BlockMap::iterator it = mapBlockIndex.begin();
3036 while (it != mapBlockIndex.end()) {
3037 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3038 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3039 setDirtyBlockIndex.insert(it->second);
3040 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3041 setBlockIndexCandidates.insert(it->second);
3043 if (it->second == pindexBestInvalid) {
3044 // Reset invalid block marker if it was pointing to one of those.
3045 pindexBestInvalid = NULL;
3051 // Remove the invalidity flag from all ancestors too.
3052 while (pindex != NULL) {
3053 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3054 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3055 setDirtyBlockIndex.insert(pindex);
3057 pindex = pindex->pprev;
3062 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3064 // Check for duplicate
3065 uint256 hash = block.GetHash();
3066 BlockMap::iterator it = mapBlockIndex.find(hash);
3067 if (it != mapBlockIndex.end())
3070 // Construct new block index object
3071 CBlockIndex* pindexNew = new CBlockIndex(block);
3073 // We assign the sequence id to blocks only when the full data is available,
3074 // to avoid miners withholding blocks but broadcasting headers, to get a
3075 // competitive advantage.
3076 pindexNew->nSequenceId = 0;
3077 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3078 pindexNew->phashBlock = &((*mi).first);
3079 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3080 if (miPrev != mapBlockIndex.end())
3082 pindexNew->pprev = (*miPrev).second;
3083 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3084 pindexNew->BuildSkip();
3086 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3087 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3088 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3089 pindexBestHeader = pindexNew;
3091 setDirtyBlockIndex.insert(pindexNew);
3096 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3097 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3099 pindexNew->nTx = block.vtx.size();
3100 pindexNew->nChainTx = 0;
3101 pindexNew->nFile = pos.nFile;
3102 pindexNew->nDataPos = pos.nPos;
3103 pindexNew->nUndoPos = 0;
3104 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3105 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3106 setDirtyBlockIndex.insert(pindexNew);
3108 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3109 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3110 deque<CBlockIndex*> queue;
3111 queue.push_back(pindexNew);
3113 // Recursively process any descendant blocks that now may be eligible to be connected.
3114 while (!queue.empty()) {
3115 CBlockIndex *pindex = queue.front();
3117 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3119 LOCK(cs_nBlockSequenceId);
3120 pindex->nSequenceId = nBlockSequenceId++;
3122 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3123 setBlockIndexCandidates.insert(pindex);
3125 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3126 while (range.first != range.second) {
3127 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3128 queue.push_back(it->second);
3130 mapBlocksUnlinked.erase(it);
3134 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3135 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3142 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3144 LOCK(cs_LastBlockFile);
3146 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3147 if (vinfoBlockFile.size() <= nFile) {
3148 vinfoBlockFile.resize(nFile + 1);
3152 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3154 if (vinfoBlockFile.size() <= nFile) {
3155 vinfoBlockFile.resize(nFile + 1);
3159 pos.nPos = vinfoBlockFile[nFile].nSize;
3162 if (nFile != nLastBlockFile) {
3164 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3166 FlushBlockFile(!fKnown);
3167 nLastBlockFile = nFile;
3170 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3172 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3174 vinfoBlockFile[nFile].nSize += nAddSize;
3177 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3178 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3179 if (nNewChunks > nOldChunks) {
3181 fCheckForPruning = true;
3182 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3183 FILE *file = OpenBlockFile(pos);
3185 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3186 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3191 return state.Error("out of disk space");
3195 setDirtyFileInfo.insert(nFile);
3199 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3203 LOCK(cs_LastBlockFile);
3205 unsigned int nNewSize;
3206 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3207 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3208 setDirtyFileInfo.insert(nFile);
3210 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3211 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3212 if (nNewChunks > nOldChunks) {
3214 fCheckForPruning = true;
3215 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3216 FILE *file = OpenUndoFile(pos);
3218 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3219 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3224 return state.Error("out of disk space");
3230 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW)
3232 uint8_t pubkey33[33];
3236 uint256 hash; int32_t i;
3237 hash = blockhdr.GetHash();
3238 for (i=31; i>=0; i--)
3239 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3240 fprintf(stderr," <- CheckBlockHeader\n");
3241 if ( chainActive.Tip() != 0 )
3243 hash = chainActive.Tip()->GetBlockHash();
3244 for (i=31; i>=0; i--)
3245 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3246 fprintf(stderr," <- chainTip\n");
3249 if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60)
3250 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new");
3251 // Check block version
3252 //if (block.nVersion < MIN_BLOCK_VERSION)
3253 // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low");
3255 // Check Equihash solution is valid
3256 if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) )
3257 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");
3259 // Check proof of work matches claimed amount
3260 komodo_index2pubkey33(pubkey33,pindex,height);
3261 if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) )
3262 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");
3266 int32_t komodo_check_deposit(int32_t height,const CBlock& block);
3267 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
3268 libzcash::ProofVerifier& verifier,
3269 bool fCheckPOW, bool fCheckMerkleRoot)
3271 // These are checks that are independent of context.
3273 // Check that the header is valid (particularly PoW). This is mostly
3274 // redundant with the call in AcceptBlockHeader.
3275 if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW))
3278 // Check the merkle root.
3279 if (fCheckMerkleRoot) {
3281 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3282 if (block.hashMerkleRoot != hashMerkleRoot2)
3283 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3284 REJECT_INVALID, "bad-txnmrklroot", true);
3286 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3287 // of transactions in a block without affecting the merkle root of a block,
3288 // while still invalidating it.
3290 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3291 REJECT_INVALID, "bad-txns-duplicate", true);
3294 // All potential-corruption validation must be done before we do any
3295 // transaction validation, as otherwise we may mark the header as invalid
3296 // because we receive the wrong transactions for it.
3299 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3300 return state.DoS(100, error("CheckBlock(): size limits failed"),
3301 REJECT_INVALID, "bad-blk-length");
3303 // First transaction must be coinbase, the rest must not be
3304 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3305 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3306 REJECT_INVALID, "bad-cb-missing");
3307 for (unsigned int i = 1; i < block.vtx.size(); i++)
3308 if (block.vtx[i].IsCoinBase())
3309 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3310 REJECT_INVALID, "bad-cb-multiple");
3312 // Check transactions
3313 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3315 if ( komodo_validate_interest(tx,komodo_block2height((CBlock *)&block),block.nTime,1) < 0 )
3316 return error("CheckBlock: komodo_validate_interest failed");
3317 if (!CheckTransaction(tx, state, verifier))
3318 return error("CheckBlock(): CheckTransaction failed");
3320 unsigned int nSigOps = 0;
3321 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3323 nSigOps += GetLegacySigOpCount(tx);
3325 if (nSigOps > MAX_BLOCK_SIGOPS)
3326 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3327 REJECT_INVALID, "bad-blk-sigops", true);
3328 if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block) < 0 )
3330 static uint32_t counter;
3331 if ( counter++ < 100 )
3332 fprintf(stderr,"check deposit rejection\n");
3338 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3340 const CChainParams& chainParams = Params();
3341 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3342 uint256 hash = block.GetHash();
3343 if (hash == consensusParams.hashGenesisBlock)
3348 int nHeight = pindexPrev->nHeight+1;
3350 // Check proof of work
3351 if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3353 cout << block.nBits << " block.nBits vs. calc " << GetNextWorkRequired(pindexPrev, &block, consensusParams) << endl;
3354 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3355 REJECT_INVALID, "bad-diffbits");
3358 // Check timestamp against prev
3359 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3360 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3361 REJECT_INVALID, "time-too-old");
3363 if (fCheckpointsEnabled)
3365 // Check that the block chain matches the known block chain up to a checkpoint
3366 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3367 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch");
3369 // Don't accept any forks from the main chain prior to last checkpoint
3370 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3371 int32_t notarized_height;
3372 if (pcheckpoint && (nHeight < pcheckpoint->nHeight || nHeight == 1 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight > 1) )
3373 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
3374 else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 )
3375 return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
3377 // Reject block.nVersion < 4 blocks
3378 if (block.nVersion < 4)
3379 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3380 REJECT_OBSOLETE, "bad-version");
3385 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3387 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3388 const Consensus::Params& consensusParams = Params().GetConsensus();
3390 // Check that all transactions are finalized
3391 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3392 int nLockTimeFlags = 0;
3393 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3394 ? pindexPrev->GetMedianTimePast()
3395 : block.GetBlockTime();
3396 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3397 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3401 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3402 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3403 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3404 // This rule is not applied to the genesis block, which didn't include the height
3408 CScript expect = CScript() << nHeight;
3409 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3410 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3411 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3418 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3420 const CChainParams& chainparams = Params();
3421 AssertLockHeld(cs_main);
3422 // Check for duplicate
3423 uint256 hash = block.GetHash();
3424 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3425 CBlockIndex *pindex = NULL;
3426 if (miSelf != mapBlockIndex.end()) {
3427 // Block header is already known.
3428 pindex = miSelf->second;
3431 if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK)
3432 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3436 if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state))
3439 // Get prev block index
3440 CBlockIndex* pindexPrev = NULL;
3441 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3442 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3443 if (mi == mapBlockIndex.end())
3444 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3445 pindexPrev = (*mi).second;
3446 if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) )
3447 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3449 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3452 pindex = AddToBlockIndex(block);
3458 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3460 const CChainParams& chainparams = Params();
3461 AssertLockHeld(cs_main);
3463 CBlockIndex *&pindex = *ppindex;
3464 if (!AcceptBlockHeader(block, state, &pindex))
3468 fprintf(stderr,"AcceptBlock error null pindex\n");
3471 // Try to process all requested blocks that we don't have, but only
3472 // process an unrequested block if it's new and has enough work to
3473 // advance our tip, and isn't too many blocks ahead.
3474 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3475 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3476 // Blocks that are too out-of-order needlessly limit the effectiveness of
3477 // pruning, because pruning will not delete block files that contain any
3478 // blocks which are too close in height to the tip. Apply this test
3479 // regardless of whether pruning is enabled; it should generally be safe to
3480 // not process unrequested blocks.
3481 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3483 // TODO: deal better with return value and error conditions for duplicate
3484 // and unrequested blocks.
3485 if (fAlreadyHave) return true;
3486 if (!fRequested) { // If we didn't ask for it:
3487 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3488 if (!fHasMoreWork) return true; // Don't process less-work chains
3489 if (fTooFarAhead) return true; // Block height is too high
3492 // See method docstring for why this is always disabled
3493 auto verifier = libzcash::ProofVerifier::Disabled();
3494 if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3495 if (state.IsInvalid() && !state.CorruptionPossible()) {
3496 pindex->nStatus |= BLOCK_FAILED_VALID;
3497 setDirtyBlockIndex.insert(pindex);
3502 int nHeight = pindex->nHeight;
3504 // Write block to history file
3506 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3507 CDiskBlockPos blockPos;
3510 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3511 return error("AcceptBlock(): FindBlockPos failed");
3513 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3514 AbortNode(state, "Failed to write block");
3515 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3516 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3517 } catch (const std::runtime_error& e) {
3518 return AbortNode(state, std::string("System error: ") + e.what());
3521 if (fCheckForPruning)
3522 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3527 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3529 unsigned int nFound = 0;
3530 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3532 if (pstart->nVersion >= minVersion)
3534 pstart = pstart->pprev;
3536 return (nFound >= nRequired);
3539 void komodo_currentheight_set(int32_t height);
3541 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3543 // Preliminary checks
3545 auto verifier = libzcash::ProofVerifier::Disabled();
3546 if ( chainActive.Tip() != 0 )
3547 komodo_currentheight_set(chainActive.Tip()->nHeight);
3548 if ( ASSETCHAINS_SYMBOL[0] == 0 )
3549 checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3550 else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier);
3553 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3554 fRequested |= fForceProcessing;
3557 Misbehaving(pfrom->GetId(), 1);
3558 return error("%s: CheckBlock FAILED", __func__);
3562 CBlockIndex *pindex = NULL;
3563 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3564 if (pindex && pfrom) {
3565 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3569 return error("%s: AcceptBlock FAILED", __func__);
3572 if (!ActivateBestChain(state, pblock))
3573 return error("%s: ActivateBestChain failed", __func__);
3578 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3580 AssertLockHeld(cs_main);
3581 assert(pindexPrev == chainActive.Tip());
3583 CCoinsViewCache viewNew(pcoinsTip);
3584 CBlockIndex indexDummy(block);
3585 indexDummy.pprev = pindexPrev;
3586 indexDummy.nHeight = pindexPrev->nHeight + 1;
3587 // JoinSplit proofs are verified in ConnectBlock
3588 auto verifier = libzcash::ProofVerifier::Disabled();
3590 // NOTE: CheckBlockHeader is called by CheckBlock
3591 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3593 fprintf(stderr,"TestBlockValidity failure A\n");
3596 if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3598 //fprintf(stderr,"TestBlockValidity failure B\n");
3601 if (!ContextualCheckBlock(block, state, pindexPrev))
3603 fprintf(stderr,"TestBlockValidity failure C\n");
3606 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3608 fprintf(stderr,"TestBlockValidity failure D\n");
3611 assert(state.IsValid());
3617 * BLOCK PRUNING CODE
3620 /* Calculate the amount of disk space the block & undo files currently use */
3621 uint64_t CalculateCurrentUsage()
3623 uint64_t retval = 0;
3624 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3625 retval += file.nSize + file.nUndoSize;
3630 /* Prune a block file (modify associated database entries)*/
3631 void PruneOneBlockFile(const int fileNumber)
3633 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3634 CBlockIndex* pindex = it->second;
3635 if (pindex->nFile == fileNumber) {
3636 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3637 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3639 pindex->nDataPos = 0;
3640 pindex->nUndoPos = 0;
3641 setDirtyBlockIndex.insert(pindex);
3643 // Prune from mapBlocksUnlinked -- any block we prune would have
3644 // to be downloaded again in order to consider its chain, at which
3645 // point it would be considered as a candidate for
3646 // mapBlocksUnlinked or setBlockIndexCandidates.
3647 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3648 while (range.first != range.second) {
3649 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3651 if (it->second == pindex) {
3652 mapBlocksUnlinked.erase(it);
3658 vinfoBlockFile[fileNumber].SetNull();
3659 setDirtyFileInfo.insert(fileNumber);
3663 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3665 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3666 CDiskBlockPos pos(*it, 0);
3667 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3668 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3669 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3673 /* Calculate the block/rev files that should be deleted to remain under target*/
3674 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3676 LOCK2(cs_main, cs_LastBlockFile);
3677 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3680 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3684 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3685 uint64_t nCurrentUsage = CalculateCurrentUsage();
3686 // We don't check to prune until after we've allocated new space for files
3687 // So we should leave a buffer under our target to account for another allocation
3688 // before the next pruning.
3689 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3690 uint64_t nBytesToPrune;
3693 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3694 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3695 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3697 if (vinfoBlockFile[fileNumber].nSize == 0)
3700 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3703 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3704 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3707 PruneOneBlockFile(fileNumber);
3708 // Queue up the files for removal
3709 setFilesToPrune.insert(fileNumber);
3710 nCurrentUsage -= nBytesToPrune;
3715 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3716 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3717 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3718 nLastBlockWeCanPrune, count);
3721 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3723 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3725 // Check for nMinDiskSpace bytes (currently 50MB)
3726 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3727 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3732 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3736 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3737 boost::filesystem::create_directories(path.parent_path());
3738 FILE* file = fopen(path.string().c_str(), "rb+");
3739 if (!file && !fReadOnly)
3740 file = fopen(path.string().c_str(), "wb+");
3742 LogPrintf("Unable to open file %s\n", path.string());
3746 if (fseek(file, pos.nPos, SEEK_SET)) {
3747 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3755 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3756 return OpenDiskFile(pos, "blk", fReadOnly);
3759 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3760 return OpenDiskFile(pos, "rev", fReadOnly);
3763 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3765 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3768 CBlockIndex * InsertBlockIndex(uint256 hash)
3774 BlockMap::iterator mi = mapBlockIndex.find(hash);
3775 if (mi != mapBlockIndex.end())
3776 return (*mi).second;
3779 CBlockIndex* pindexNew = new CBlockIndex();
3781 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3782 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3783 pindexNew->phashBlock = &((*mi).first);
3788 bool static LoadBlockIndexDB()
3790 const CChainParams& chainparams = Params();
3791 if (!pblocktree->LoadBlockIndexGuts())
3794 boost::this_thread::interruption_point();
3796 // Calculate nChainWork
3797 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3798 vSortedByHeight.reserve(mapBlockIndex.size());
3799 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3801 CBlockIndex* pindex = item.second;
3802 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3804 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3805 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3807 CBlockIndex* pindex = item.second;
3808 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3809 // We can link the chain of blocks for which we've received transactions at some point.
3810 // Pruned nodes may have deleted the block.
3811 if (pindex->nTx > 0) {
3812 if (pindex->pprev) {
3813 if (pindex->pprev->nChainTx) {
3814 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3816 pindex->nChainTx = 0;
3817 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3820 pindex->nChainTx = pindex->nTx;
3823 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3824 setBlockIndexCandidates.insert(pindex);
3825 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3826 pindexBestInvalid = pindex;
3828 pindex->BuildSkip();
3829 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3830 pindexBestHeader = pindex;
3833 // Load block file info
3834 pblocktree->ReadLastBlockFile(nLastBlockFile);
3835 vinfoBlockFile.resize(nLastBlockFile + 1);
3836 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3837 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3838 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3840 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3841 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3842 CBlockFileInfo info;
3843 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3844 vinfoBlockFile.push_back(info);
3850 // Check presence of blk files
3851 LogPrintf("Checking all blk files are present...\n");
3852 set<int> setBlkDataFiles;
3853 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3855 CBlockIndex* pindex = item.second;
3856 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3857 setBlkDataFiles.insert(pindex->nFile);
3860 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3862 CDiskBlockPos pos(*it, 0);
3863 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3868 // Check whether we have ever pruned block & undo files
3869 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3871 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3873 // Check whether we need to continue reindexing
3874 bool fReindexing = false;
3875 pblocktree->ReadReindexing(fReindexing);
3876 fReindex |= fReindexing;
3878 // Check whether we have a transaction index
3879 pblocktree->ReadFlag("txindex", fTxIndex);
3880 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3882 // Fill in-memory data
3883 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3885 CBlockIndex* pindex = item.second;
3886 // - This relationship will always be true even if pprev has multiple
3887 // children, because hashAnchor is technically a property of pprev,
3888 // not its children.
3889 // - This will miss chain tips; we handle the best tip below, and other
3890 // tips will be handled by ConnectTip during a re-org.
3891 if (pindex->pprev) {
3892 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3896 // Load pointer to end of best chain
3897 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3898 if (it == mapBlockIndex.end())
3900 chainActive.SetTip(it->second);
3901 // Set hashAnchorEnd for the end of best chain
3902 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3904 PruneBlockIndexCandidates();
3906 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3907 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3908 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3909 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3914 CVerifyDB::CVerifyDB()
3916 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3919 CVerifyDB::~CVerifyDB()
3921 uiInterface.ShowProgress("", 100);
3924 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3927 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3930 // Verify blocks in the best chain
3931 if (nCheckDepth <= 0)
3932 nCheckDepth = 1000000000; // suffices until the year 19000
3933 if (nCheckDepth > chainActive.Height())
3934 nCheckDepth = chainActive.Height();
3935 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3936 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3937 CCoinsViewCache coins(coinsview);
3938 CBlockIndex* pindexState = chainActive.Tip();
3939 CBlockIndex* pindexFailure = NULL;
3940 int nGoodTransactions = 0;
3941 CValidationState state;
3942 // No need to verify JoinSplits twice
3943 auto verifier = libzcash::ProofVerifier::Disabled();
3944 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3946 boost::this_thread::interruption_point();
3947 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3948 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3951 // check level 0: read from disk
3952 if (!ReadBlockFromDisk(block, pindex))
3953 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3954 // check level 1: verify block validity
3955 if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier))
3956 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3957 // check level 2: verify undo validity
3958 if (nCheckLevel >= 2 && pindex) {
3960 CDiskBlockPos pos = pindex->GetUndoPos();
3961 if (!pos.IsNull()) {
3962 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3963 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3966 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3967 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3969 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3970 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3971 pindexState = pindex->pprev;
3973 nGoodTransactions = 0;
3974 pindexFailure = pindex;
3976 nGoodTransactions += block.vtx.size();
3978 if (ShutdownRequested())
3982 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3984 // check level 4: try reconnecting blocks
3985 if (nCheckLevel >= 4) {
3986 CBlockIndex *pindex = pindexState;
3987 while (pindex != chainActive.Tip()) {
3988 boost::this_thread::interruption_point();
3989 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3990 pindex = chainActive.Next(pindex);
3992 if (!ReadBlockFromDisk(block, pindex))
3993 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3994 if (!ConnectBlock(block, state, pindex, coins))
3995 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3999 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4004 void UnloadBlockIndex()
4007 setBlockIndexCandidates.clear();
4008 chainActive.SetTip(NULL);
4009 pindexBestInvalid = NULL;
4010 pindexBestHeader = NULL;
4012 mapOrphanTransactions.clear();
4013 mapOrphanTransactionsByPrev.clear();
4015 mapBlocksUnlinked.clear();
4016 vinfoBlockFile.clear();
4018 nBlockSequenceId = 1;
4019 mapBlockSource.clear();
4020 mapBlocksInFlight.clear();
4021 nQueuedValidatedHeaders = 0;
4022 nPreferredDownload = 0;
4023 setDirtyBlockIndex.clear();
4024 setDirtyFileInfo.clear();
4025 mapNodeState.clear();
4026 recentRejects.reset(NULL);
4028 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4029 delete entry.second;
4031 mapBlockIndex.clear();
4032 fHavePruned = false;
4035 bool LoadBlockIndex()
4037 extern int32_t KOMODO_LOADINGBLOCKS;
4038 // Load block index from databases
4039 KOMODO_LOADINGBLOCKS = 1;
4040 if (!fReindex && !LoadBlockIndexDB())
4042 KOMODO_LOADINGBLOCKS = 0;
4045 KOMODO_LOADINGBLOCKS = 0;
4046 fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL);
4051 bool InitBlockIndex() {
4052 const CChainParams& chainparams = Params();
4055 // Initialize global variables that cannot be constructed at startup.
4056 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4058 // Check whether we're already initialized
4059 if (chainActive.Genesis() != NULL)
4062 // Use the provided setting for -txindex in the new database
4063 fTxIndex = GetBoolArg("-txindex", true);
4064 pblocktree->WriteFlag("txindex", fTxIndex);
4065 LogPrintf("Initializing databases...\n");
4067 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4070 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4071 // Start new block file
4072 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4073 CDiskBlockPos blockPos;
4074 CValidationState state;
4075 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4076 return error("LoadBlockIndex(): FindBlockPos failed");
4077 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4078 return error("LoadBlockIndex(): writing genesis block to disk failed");
4079 CBlockIndex *pindex = AddToBlockIndex(block);
4080 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4081 return error("LoadBlockIndex(): genesis block not accepted");
4082 if (!ActivateBestChain(state, &block))
4083 return error("LoadBlockIndex(): genesis block cannot be activated");
4084 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4085 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4086 } catch (const std::runtime_error& e) {
4087 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4096 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4098 const CChainParams& chainparams = Params();
4099 // Map of disk positions for blocks with unknown parent (only used for reindex)
4100 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4101 int64_t nStart = GetTimeMillis();
4105 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4106 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4107 uint64_t nRewind = blkdat.GetPos();
4108 while (!blkdat.eof()) {
4109 boost::this_thread::interruption_point();
4111 blkdat.SetPos(nRewind);
4112 nRewind++; // start one byte further next time, in case of failure
4113 blkdat.SetLimit(); // remove former limit
4114 unsigned int nSize = 0;
4117 unsigned char buf[MESSAGE_START_SIZE];
4118 blkdat.FindByte(Params().MessageStart()[0]);
4119 nRewind = blkdat.GetPos()+1;
4120 blkdat >> FLATDATA(buf);
4121 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4125 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4127 } catch (const std::exception&) {
4128 // no valid block header found; don't complain
4133 uint64_t nBlockPos = blkdat.GetPos();
4135 dbp->nPos = nBlockPos;
4136 blkdat.SetLimit(nBlockPos + nSize);
4137 blkdat.SetPos(nBlockPos);
4140 nRewind = blkdat.GetPos();
4142 // detect out of order blocks, and store them for later
4143 uint256 hash = block.GetHash();
4144 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4145 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4146 block.hashPrevBlock.ToString());
4148 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4152 // process in case the block isn't known yet
4153 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4154 CValidationState state;
4155 if (ProcessNewBlock(0,state, NULL, &block, true, dbp))
4157 if (state.IsError())
4159 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4160 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4163 // Recursively process earlier encountered successors of this block
4164 deque<uint256> queue;
4165 queue.push_back(hash);
4166 while (!queue.empty()) {
4167 uint256 head = queue.front();
4169 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4170 while (range.first != range.second) {
4171 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4172 if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second))
4174 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4176 CValidationState dummy;
4177 if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second))
4180 queue.push_back(block.GetHash());
4184 mapBlocksUnknownParent.erase(it);
4187 } catch (const std::exception& e) {
4188 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4191 } catch (const std::runtime_error& e) {
4192 AbortNode(std::string("System error: ") + e.what());
4195 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4199 void static CheckBlockIndex()
4201 const Consensus::Params& consensusParams = Params().GetConsensus();
4202 if (!fCheckBlockIndex) {
4208 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4209 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4210 // iterating the block tree require that chainActive has been initialized.)
4211 if (chainActive.Height() < 0) {
4212 assert(mapBlockIndex.size() <= 1);
4216 // Build forward-pointing map of the entire block tree.
4217 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4218 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4219 forward.insert(std::make_pair(it->second->pprev, it->second));
4223 assert(forward.size() == mapBlockIndex.size());
4225 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4226 CBlockIndex *pindex = rangeGenesis.first->second;
4227 rangeGenesis.first++;
4228 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4230 // Iterate over the entire block tree, using depth-first search.
4231 // Along the way, remember whether there are blocks on the path from genesis
4232 // block being explored which are the first to have certain properties.
4235 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4236 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4237 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4238 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4239 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4240 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4241 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4242 while (pindex != NULL) {
4244 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4245 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4246 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4247 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4248 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4249 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4250 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4252 // Begin: actual consistency checks.
4253 if (pindex->pprev == NULL) {
4254 // Genesis block checks.
4255 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4256 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4258 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4259 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4260 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4262 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4263 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4264 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4266 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4267 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4269 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4270 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4271 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4272 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4273 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4274 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4275 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.
4276 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4277 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4278 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4279 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4280 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4281 if (pindexFirstInvalid == NULL) {
4282 // Checks for not-invalid blocks.
4283 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4285 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4286 if (pindexFirstInvalid == NULL) {
4287 // If this block sorts at least as good as the current tip and
4288 // is valid and we have all data for its parents, it must be in
4289 // setBlockIndexCandidates. chainActive.Tip() must also be there
4290 // even if some data has been pruned.
4291 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4292 assert(setBlockIndexCandidates.count(pindex));
4294 // If some parent is missing, then it could be that this block was in
4295 // setBlockIndexCandidates but had to be removed because of the missing data.
4296 // In this case it must be in mapBlocksUnlinked -- see test below.
4298 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4299 assert(setBlockIndexCandidates.count(pindex) == 0);
4301 // Check whether this block is in mapBlocksUnlinked.
4302 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4303 bool foundInUnlinked = false;
4304 while (rangeUnlinked.first != rangeUnlinked.second) {
4305 assert(rangeUnlinked.first->first == pindex->pprev);
4306 if (rangeUnlinked.first->second == pindex) {
4307 foundInUnlinked = true;
4310 rangeUnlinked.first++;
4312 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4313 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4314 assert(foundInUnlinked);
4316 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4317 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4318 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4319 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4320 assert(fHavePruned); // We must have pruned.
4321 // This block may have entered mapBlocksUnlinked if:
4322 // - it has a descendant that at some point had more work than the
4324 // - we tried switching to that descendant but were missing
4325 // data for some intermediate block between chainActive and the
4327 // So if this block is itself better than chainActive.Tip() and it wasn't in
4328 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4329 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4330 if (pindexFirstInvalid == NULL) {
4331 assert(foundInUnlinked);
4335 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4336 // End: actual consistency checks.
4338 // Try descending into the first subnode.
4339 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4340 if (range.first != range.second) {
4341 // A subnode was found.
4342 pindex = range.first->second;
4346 // This is a leaf node.
4347 // Move upwards until we reach a node of which we have not yet visited the last child.
4349 // We are going to either move to a parent or a sibling of pindex.
4350 // If pindex was the first with a certain property, unset the corresponding variable.
4351 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4352 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4353 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4354 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4355 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4356 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4357 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4359 CBlockIndex* pindexPar = pindex->pprev;
4360 // Find which child we just visited.
4361 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4362 while (rangePar.first->second != pindex) {
4363 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4366 // Proceed to the next one.
4368 if (rangePar.first != rangePar.second) {
4369 // Move to the sibling.
4370 pindex = rangePar.first->second;
4381 // Check that we actually traversed the entire map.
4382 assert(nNodes == forward.size());
4385 //////////////////////////////////////////////////////////////////////////////
4390 std::string GetWarnings(const std::string& strFor)
4393 string strStatusBar;
4396 if (!CLIENT_VERSION_IS_RELEASE)
4397 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4399 if (GetBoolArg("-testsafemode", false))
4400 strStatusBar = strRPC = "testsafemode enabled";
4402 // Misc warnings like out of disk space and clock is wrong
4403 if (strMiscWarning != "")
4406 strStatusBar = strMiscWarning;
4409 if (fLargeWorkForkFound)
4412 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4414 else if (fLargeWorkInvalidChainFound)
4417 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.");
4423 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4425 const CAlert& alert = item.second;
4426 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4428 nPriority = alert.nPriority;
4429 strStatusBar = alert.strStatusBar;
4430 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4431 strRPC = alert.strRPCError;
4437 if (strFor == "statusbar")
4438 return strStatusBar;
4439 else if (strFor == "rpc")
4441 assert(!"GetWarnings(): invalid parameter");
4452 //////////////////////////////////////////////////////////////////////////////
4458 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4464 assert(recentRejects);
4465 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4467 // If the chain tip has changed previously rejected transactions
4468 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4469 // or a double-spend. Reset the rejects filter and give those
4470 // txs a second chance.
4471 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4472 recentRejects->reset();
4475 return recentRejects->contains(inv.hash) ||
4476 mempool.exists(inv.hash) ||
4477 mapOrphanTransactions.count(inv.hash) ||
4478 pcoinsTip->HaveCoins(inv.hash);
4481 return mapBlockIndex.count(inv.hash);
4483 // Don't know what it is, just say we already got one
4487 void static ProcessGetData(CNode* pfrom)
4489 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4491 vector<CInv> vNotFound;
4495 while (it != pfrom->vRecvGetData.end()) {
4496 // Don't bother if send buffer is too full to respond anyway
4497 if (pfrom->nSendSize >= SendBufferSize())
4500 const CInv &inv = *it;
4502 boost::this_thread::interruption_point();
4505 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4508 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4509 if (mi != mapBlockIndex.end())
4511 if (chainActive.Contains(mi->second)) {
4514 static const int nOneMonth = 30 * 24 * 60 * 60;
4515 // To prevent fingerprinting attacks, only send blocks outside of the active
4516 // chain if they are valid, and no more than a month older (both in time, and in
4517 // best equivalent proof of work) than the best header chain we know about.
4518 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4519 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4520 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4522 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4526 // Pruned nodes may have deleted the block, so check whether
4527 // it's available before trying to send.
4528 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4530 // Send block from disk
4532 if (!ReadBlockFromDisk(block, (*mi).second))
4534 assert(!"cannot load block from disk");
4538 if (inv.type == MSG_BLOCK)
4540 //uint256 hash; int32_t z;
4541 //hash = block.GetHash();
4542 //for (z=31; z>=0; z--)
4543 // fprintf(stderr,"%02x",((uint8_t *)&hash)[z]);
4544 //fprintf(stderr," send block %d\n",komodo_block2height(&block));
4545 pfrom->PushMessage("block", block);
4547 else // MSG_FILTERED_BLOCK)
4549 LOCK(pfrom->cs_filter);
4552 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4553 pfrom->PushMessage("merkleblock", merkleBlock);
4554 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4555 // This avoids hurting performance by pointlessly requiring a round-trip
4556 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4557 // they must either disconnect and retry or request the full block.
4558 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4559 // however we MUST always provide at least what the remote peer needs
4560 typedef std::pair<unsigned int, uint256> PairType;
4561 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4562 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4563 pfrom->PushMessage("tx", block.vtx[pair.first]);
4569 // Trigger the peer node to send a getblocks request for the next batch of inventory
4570 if (inv.hash == pfrom->hashContinue)
4572 // Bypass PushInventory, this must send even if redundant,
4573 // and we want it right after the last block so they don't
4574 // wait for other stuff first.
4576 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4577 pfrom->PushMessage("inv", vInv);
4578 pfrom->hashContinue.SetNull();
4582 else if (inv.IsKnownType())
4584 // Send stream from relay memory
4585 bool pushed = false;
4588 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4589 if (mi != mapRelay.end()) {
4590 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4594 if (!pushed && inv.type == MSG_TX) {
4596 if (mempool.lookup(inv.hash, tx)) {
4597 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4600 pfrom->PushMessage("tx", ss);
4605 vNotFound.push_back(inv);
4609 // Track requests for our stuff.
4610 GetMainSignals().Inventory(inv.hash);
4612 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4617 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4619 if (!vNotFound.empty()) {
4620 // Let the peer know that we didn't find what it asked for, so it doesn't
4621 // have to wait around forever. Currently only SPV clients actually care
4622 // about this message: it's needed when they are recursively walking the
4623 // dependencies of relevant unconfirmed transactions. SPV clients want to
4624 // do that because they want to know about (and store and rebroadcast and
4625 // risk analyze) the dependencies of transactions relevant to them, without
4626 // having to download the entire memory pool.
4627 pfrom->PushMessage("notfound", vNotFound);
4631 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4633 const CChainParams& chainparams = Params();
4634 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4635 //fprintf(stderr, "recv: %s peer=%d\n", SanitizeString(strCommand).c_str(), (int32_t)pfrom->GetId());
4636 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4638 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4645 if (strCommand == "version")
4647 // Each connection can only send one version message
4648 if (pfrom->nVersion != 0)
4650 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4651 Misbehaving(pfrom->GetId(), 1);
4658 uint64_t nNonce = 1;
4659 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4660 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4662 // disconnect from peers older than this proto version
4663 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4664 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4665 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4666 pfrom->fDisconnect = true;
4670 if (pfrom->nVersion == 10300)
4671 pfrom->nVersion = 300;
4673 vRecv >> addrFrom >> nNonce;
4674 if (!vRecv.empty()) {
4675 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4676 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4679 vRecv >> pfrom->nStartingHeight;
4681 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4683 pfrom->fRelayTxes = true;
4685 // Disconnect if we connected to ourself
4686 if (nNonce == nLocalHostNonce && nNonce > 1)
4688 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4689 pfrom->fDisconnect = true;
4693 pfrom->addrLocal = addrMe;
4694 if (pfrom->fInbound && addrMe.IsRoutable())
4699 // Be shy and don't send version until we hear
4700 if (pfrom->fInbound)
4701 pfrom->PushVersion();
4703 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4705 // Potentially mark this peer as a preferred download peer.
4706 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4709 pfrom->PushMessage("verack");
4710 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4712 if (!pfrom->fInbound)
4714 // Advertise our address
4715 if (fListen && !IsInitialBlockDownload())
4717 CAddress addr = GetLocalAddress(&pfrom->addr);
4718 if (addr.IsRoutable())
4720 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4721 pfrom->PushAddress(addr);
4722 } else if (IsPeerAddrLocalGood(pfrom)) {
4723 addr.SetIP(pfrom->addrLocal);
4724 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4725 pfrom->PushAddress(addr);
4729 // Get recent addresses
4730 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4732 pfrom->PushMessage("getaddr");
4733 pfrom->fGetAddr = true;
4735 addrman.Good(pfrom->addr);
4737 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4739 addrman.Add(addrFrom, addrFrom);
4740 addrman.Good(addrFrom);
4747 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4748 item.second.RelayTo(pfrom);
4751 pfrom->fSuccessfullyConnected = true;
4755 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4757 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4758 pfrom->cleanSubVer, pfrom->nVersion,
4759 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4762 int64_t nTimeOffset = nTime - GetTime();
4763 pfrom->nTimeOffset = nTimeOffset;
4764 AddTimeData(pfrom->addr, nTimeOffset);
4768 else if (pfrom->nVersion == 0)
4770 // Must have a version message before anything else
4771 Misbehaving(pfrom->GetId(), 1);
4776 else if (strCommand == "verack")
4778 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4780 // Mark this node as currently connected, so we update its timestamp later.
4781 if (pfrom->fNetworkNode) {
4783 State(pfrom->GetId())->fCurrentlyConnected = true;
4788 else if (strCommand == "addr")
4790 vector<CAddress> vAddr;
4793 // Don't want addr from older versions unless seeding
4794 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4796 if (vAddr.size() > 1000)
4798 Misbehaving(pfrom->GetId(), 20);
4799 return error("message addr size() = %u", vAddr.size());
4802 // Store the new addresses
4803 vector<CAddress> vAddrOk;
4804 int64_t nNow = GetAdjustedTime();
4805 int64_t nSince = nNow - 10 * 60;
4806 BOOST_FOREACH(CAddress& addr, vAddr)
4808 boost::this_thread::interruption_point();
4810 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4811 addr.nTime = nNow - 5 * 24 * 60 * 60;
4812 pfrom->AddAddressKnown(addr);
4813 bool fReachable = IsReachable(addr);
4814 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4816 // Relay to a limited number of other nodes
4819 // Use deterministic randomness to send to the same nodes for 24 hours
4820 // at a time so the addrKnowns of the chosen nodes prevent repeats
4821 static uint256 hashSalt;
4822 if (hashSalt.IsNull())
4823 hashSalt = GetRandHash();
4824 uint64_t hashAddr = addr.GetHash();
4825 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4826 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4827 multimap<uint256, CNode*> mapMix;
4828 BOOST_FOREACH(CNode* pnode, vNodes)
4830 if (pnode->nVersion < CADDR_TIME_VERSION)
4832 unsigned int nPointer;
4833 memcpy(&nPointer, &pnode, sizeof(nPointer));
4834 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4835 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4836 mapMix.insert(make_pair(hashKey, pnode));
4838 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4839 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4840 ((*mi).second)->PushAddress(addr);
4843 // Do not store addresses outside our network
4845 vAddrOk.push_back(addr);
4847 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4848 if (vAddr.size() < 1000)
4849 pfrom->fGetAddr = false;
4850 if (pfrom->fOneShot)
4851 pfrom->fDisconnect = true;
4855 else if (strCommand == "inv")
4859 if (vInv.size() > MAX_INV_SZ)
4861 Misbehaving(pfrom->GetId(), 20);
4862 return error("message inv size() = %u", vInv.size());
4867 std::vector<CInv> vToFetch;
4869 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4871 const CInv &inv = vInv[nInv];
4873 boost::this_thread::interruption_point();
4874 pfrom->AddInventoryKnown(inv);
4876 bool fAlreadyHave = AlreadyHave(inv);
4877 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4879 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4882 if (inv.type == MSG_BLOCK) {
4883 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4884 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4885 // First request the headers preceding the announced block. In the normal fully-synced
4886 // case where a new block is announced that succeeds the current tip (no reorganization),
4887 // there are no such headers.
4888 // Secondly, and only when we are close to being synced, we request the announced block directly,
4889 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4890 // time the block arrives, the header chain leading up to it is already validated. Not
4891 // doing this will result in the received block being rejected as an orphan in case it is
4892 // not a direct successor.
4893 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4894 CNodeState *nodestate = State(pfrom->GetId());
4895 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4896 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4897 vToFetch.push_back(inv);
4898 // Mark block as in flight already, even though the actual "getdata" message only goes out
4899 // later (within the same cs_main lock, though).
4900 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4902 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4906 // Track requests for our stuff
4907 GetMainSignals().Inventory(inv.hash);
4909 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4910 Misbehaving(pfrom->GetId(), 50);
4911 return error("send buffer size() = %u", pfrom->nSendSize);
4915 if (!vToFetch.empty())
4916 pfrom->PushMessage("getdata", vToFetch);
4920 else if (strCommand == "getdata")
4924 if (vInv.size() > MAX_INV_SZ)
4926 Misbehaving(pfrom->GetId(), 20);
4927 return error("message getdata size() = %u", vInv.size());
4930 if (fDebug || (vInv.size() != 1))
4931 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4933 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4934 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4936 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4937 ProcessGetData(pfrom);
4941 else if (strCommand == "getblocks")
4943 CBlockLocator locator;
4945 vRecv >> locator >> hashStop;
4949 // Find the last block the caller has in the main chain
4950 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4952 // Send the rest of the chain
4954 pindex = chainActive.Next(pindex);
4956 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4957 for (; pindex; pindex = chainActive.Next(pindex))
4959 if (pindex->GetBlockHash() == hashStop)
4961 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4964 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4967 // When this block is requested, we'll send an inv that'll
4968 // trigger the peer to getblocks the next batch of inventory.
4969 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4970 pfrom->hashContinue = pindex->GetBlockHash();
4977 else if (strCommand == "getheaders")
4979 CBlockLocator locator;
4981 vRecv >> locator >> hashStop;
4985 if (IsInitialBlockDownload())
4988 CBlockIndex* pindex = NULL;
4989 if (locator.IsNull())
4991 // If locator is null, return the hashStop block
4992 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4993 if (mi == mapBlockIndex.end())
4995 pindex = (*mi).second;
4999 // Find the last block the caller has in the main chain
5000 pindex = FindForkInGlobalIndex(chainActive, locator);
5002 pindex = chainActive.Next(pindex);
5005 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5006 vector<CBlock> vHeaders;
5007 int nLimit = MAX_HEADERS_RESULTS;
5008 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5009 if ( pfrom->lasthdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pfrom->lasthdrsreq != (int32_t)(pindex ? pindex->nHeight : -1) )
5011 pfrom->lasthdrsreq = (int32_t)(pindex ? pindex->nHeight : -1);
5012 for (; pindex; pindex = chainActive.Next(pindex))
5014 vHeaders.push_back(pindex->GetBlockHeader());
5015 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5018 pfrom->PushMessage("headers", vHeaders);
5020 else if ( NOTARY_PUBKEY33[0] != 0 )
5022 static uint32_t counter;
5023 if ( counter++ < 3 )
5024 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);
5029 else if (strCommand == "tx")
5031 vector<uint256> vWorkQueue;
5032 vector<uint256> vEraseQueue;
5036 CInv inv(MSG_TX, tx.GetHash());
5037 pfrom->AddInventoryKnown(inv);
5041 bool fMissingInputs = false;
5042 CValidationState state;
5044 pfrom->setAskFor.erase(inv.hash);
5045 mapAlreadyAskedFor.erase(inv);
5047 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5049 mempool.check(pcoinsTip);
5050 RelayTransaction(tx);
5051 vWorkQueue.push_back(inv.hash);
5053 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5054 pfrom->id, pfrom->cleanSubVer,
5055 tx.GetHash().ToString(),
5056 mempool.mapTx.size());
5058 // Recursively process any orphan transactions that depended on this one
5059 set<NodeId> setMisbehaving;
5060 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5062 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5063 if (itByPrev == mapOrphanTransactionsByPrev.end())
5065 for (set<uint256>::iterator mi = itByPrev->second.begin();
5066 mi != itByPrev->second.end();
5069 const uint256& orphanHash = *mi;
5070 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5071 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5072 bool fMissingInputs2 = false;
5073 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5074 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5075 // anyone relaying LegitTxX banned)
5076 CValidationState stateDummy;
5079 if (setMisbehaving.count(fromPeer))
5081 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5083 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5084 RelayTransaction(orphanTx);
5085 vWorkQueue.push_back(orphanHash);
5086 vEraseQueue.push_back(orphanHash);
5088 else if (!fMissingInputs2)
5091 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5093 // Punish peer that gave us an invalid orphan tx
5094 Misbehaving(fromPeer, nDos);
5095 setMisbehaving.insert(fromPeer);
5096 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5098 // Has inputs but not accepted to mempool
5099 // Probably non-standard or insufficient fee/priority
5100 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5101 vEraseQueue.push_back(orphanHash);
5102 assert(recentRejects);
5103 recentRejects->insert(orphanHash);
5105 mempool.check(pcoinsTip);
5109 BOOST_FOREACH(uint256 hash, vEraseQueue)
5110 EraseOrphanTx(hash);
5112 // TODO: currently, prohibit joinsplits from entering mapOrphans
5113 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5115 AddOrphanTx(tx, pfrom->GetId());
5117 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5118 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5119 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5121 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5123 assert(recentRejects);
5124 recentRejects->insert(tx.GetHash());
5126 if (pfrom->fWhitelisted) {
5127 // Always relay transactions received from whitelisted peers, even
5128 // if they were already in the mempool or rejected from it due
5129 // to policy, allowing the node to function as a gateway for
5130 // nodes hidden behind it.
5132 // Never relay transactions that we would assign a non-zero DoS
5133 // score for, as we expect peers to do the same with us in that
5136 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5137 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5138 RelayTransaction(tx);
5140 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5141 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5146 if (state.IsInvalid(nDoS))
5148 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5149 pfrom->id, pfrom->cleanSubVer,
5150 state.GetRejectReason());
5151 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5152 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5154 Misbehaving(pfrom->GetId(), nDoS);
5159 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5161 std::vector<CBlockHeader> headers;
5163 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5164 unsigned int nCount = ReadCompactSize(vRecv);
5165 if (nCount > MAX_HEADERS_RESULTS) {
5166 Misbehaving(pfrom->GetId(), 20);
5167 return error("headers message size = %u", nCount);
5169 headers.resize(nCount);
5170 for (unsigned int n = 0; n < nCount; n++) {
5171 vRecv >> headers[n];
5172 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5178 // Nothing interesting. Stop asking this peers for more headers.
5182 CBlockIndex *pindexLast = NULL;
5183 BOOST_FOREACH(const CBlockHeader& header, headers) {
5184 CValidationState state;
5185 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5186 Misbehaving(pfrom->GetId(), 20);
5187 return error("non-continuous headers sequence");
5189 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5191 if (state.IsInvalid(nDoS)) {
5193 Misbehaving(pfrom->GetId(), nDoS/nDoS);
5194 return error("invalid header received");
5200 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5202 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5203 // Headers message had its maximum size; the peer may have more headers.
5204 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5205 // from there instead.
5206 if ( pfrom->sendhdrsreq >= chainActive.Height()-MAX_HEADERS_RESULTS || pindexLast->nHeight != pfrom->sendhdrsreq )
5208 pfrom->sendhdrsreq = (int32_t)pindexLast->nHeight;
5209 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5210 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5217 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5222 CInv inv(MSG_BLOCK, block.GetHash());
5223 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5225 pfrom->AddInventoryKnown(inv);
5227 CValidationState state;
5228 // Process all blocks from whitelisted peers, even if not requested,
5229 // unless we're still syncing with the network.
5230 // Such an unrequested block may still be processed, subject to the
5231 // conditions in AcceptBlock().
5232 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5233 ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL);
5235 if (state.IsInvalid(nDoS)) {
5236 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5237 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5240 Misbehaving(pfrom->GetId(), nDoS);
5247 // This asymmetric behavior for inbound and outbound connections was introduced
5248 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5249 // to users' AddrMan and later request them by sending getaddr messages.
5250 // Making nodes which are behind NAT and can only make outgoing connections ignore
5251 // the getaddr message mitigates the attack.
5252 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5254 // Only send one GetAddr response per connection to reduce resource waste
5255 // and discourage addr stamping of INV announcements.
5256 if (pfrom->fSentAddr) {
5257 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5260 pfrom->fSentAddr = true;
5262 pfrom->vAddrToSend.clear();
5263 vector<CAddress> vAddr = addrman.GetAddr();
5264 BOOST_FOREACH(const CAddress &addr, vAddr)
5265 pfrom->PushAddress(addr);
5269 else if (strCommand == "mempool")
5271 LOCK2(cs_main, pfrom->cs_filter);
5273 std::vector<uint256> vtxid;
5274 mempool.queryHashes(vtxid);
5276 BOOST_FOREACH(uint256& hash, vtxid) {
5277 CInv inv(MSG_TX, hash);
5279 bool fInMemPool = mempool.lookup(hash, tx);
5280 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5281 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5283 vInv.push_back(inv);
5284 if (vInv.size() == MAX_INV_SZ) {
5285 pfrom->PushMessage("inv", vInv);
5289 if (vInv.size() > 0)
5290 pfrom->PushMessage("inv", vInv);
5294 else if (strCommand == "ping")
5296 if (pfrom->nVersion > BIP0031_VERSION)
5300 // Echo the message back with the nonce. This allows for two useful features:
5302 // 1) A remote node can quickly check if the connection is operational
5303 // 2) Remote nodes can measure the latency of the network thread. If this node
5304 // is overloaded it won't respond to pings quickly and the remote node can
5305 // avoid sending us more work, like chain download requests.
5307 // The nonce stops the remote getting confused between different pings: without
5308 // it, if the remote node sends a ping once per second and this node takes 5
5309 // seconds to respond to each, the 5th ping the remote sends would appear to
5310 // return very quickly.
5311 pfrom->PushMessage("pong", nonce);
5316 else if (strCommand == "pong")
5318 int64_t pingUsecEnd = nTimeReceived;
5320 size_t nAvail = vRecv.in_avail();
5321 bool bPingFinished = false;
5322 std::string sProblem;
5324 if (nAvail >= sizeof(nonce)) {
5327 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5328 if (pfrom->nPingNonceSent != 0) {
5329 if (nonce == pfrom->nPingNonceSent) {
5330 // Matching pong received, this ping is no longer outstanding
5331 bPingFinished = true;
5332 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5333 if (pingUsecTime > 0) {
5334 // Successful ping time measurement, replace previous
5335 pfrom->nPingUsecTime = pingUsecTime;
5336 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5338 // This should never happen
5339 sProblem = "Timing mishap";
5342 // Nonce mismatches are normal when pings are overlapping
5343 sProblem = "Nonce mismatch";
5345 // This is most likely a bug in another implementation somewhere; cancel this ping
5346 bPingFinished = true;
5347 sProblem = "Nonce zero";
5351 sProblem = "Unsolicited pong without ping";
5354 // This is most likely a bug in another implementation somewhere; cancel this ping
5355 bPingFinished = true;
5356 sProblem = "Short payload";
5359 if (!(sProblem.empty())) {
5360 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5364 pfrom->nPingNonceSent,
5368 if (bPingFinished) {
5369 pfrom->nPingNonceSent = 0;
5374 else if (fAlerts && strCommand == "alert")
5379 uint256 alertHash = alert.GetHash();
5380 if (pfrom->setKnown.count(alertHash) == 0)
5382 if (alert.ProcessAlert(Params().AlertKey()))
5385 pfrom->setKnown.insert(alertHash);
5388 BOOST_FOREACH(CNode* pnode, vNodes)
5389 alert.RelayTo(pnode);
5393 // Small DoS penalty so peers that send us lots of
5394 // duplicate/expired/invalid-signature/whatever alerts
5395 // eventually get banned.
5396 // This isn't a Misbehaving(100) (immediate ban) because the
5397 // peer might be an older or different implementation with
5398 // a different signature key, etc.
5399 Misbehaving(pfrom->GetId(), 10);
5405 else if (strCommand == "filterload")
5407 CBloomFilter filter;
5410 if (!filter.IsWithinSizeConstraints())
5411 // There is no excuse for sending a too-large filter
5412 Misbehaving(pfrom->GetId(), 100);
5415 LOCK(pfrom->cs_filter);
5416 delete pfrom->pfilter;
5417 pfrom->pfilter = new CBloomFilter(filter);
5418 pfrom->pfilter->UpdateEmptyFull();
5420 pfrom->fRelayTxes = true;
5424 else if (strCommand == "filteradd")
5426 vector<unsigned char> vData;
5429 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5430 // and thus, the maximum size any matched object can have) in a filteradd message
5431 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5433 Misbehaving(pfrom->GetId(), 100);
5435 LOCK(pfrom->cs_filter);
5437 pfrom->pfilter->insert(vData);
5439 Misbehaving(pfrom->GetId(), 100);
5444 else if (strCommand == "filterclear")
5446 LOCK(pfrom->cs_filter);
5447 delete pfrom->pfilter;
5448 pfrom->pfilter = new CBloomFilter();
5449 pfrom->fRelayTxes = true;
5453 else if (strCommand == "reject")
5457 string strMsg; unsigned char ccode; string strReason;
5458 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5461 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5463 if (strMsg == "block" || strMsg == "tx")
5467 ss << ": hash " << hash.ToString();
5469 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5470 } catch (const std::ios_base::failure&) {
5471 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5472 LogPrint("net", "Unparseable reject message received\n");
5476 else if (strCommand == "notfound") {
5477 // We do not care about the NOTFOUND message, but logging an Unknown Command
5478 // message would be undesirable as we transmit it ourselves.
5482 // Ignore unknown commands for extensibility
5483 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5491 // requires LOCK(cs_vRecvMsg)
5492 bool ProcessMessages(CNode* pfrom)
5495 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5499 // (4) message start
5507 if (!pfrom->vRecvGetData.empty())
5508 ProcessGetData(pfrom);
5510 // this maintains the order of responses
5511 if (!pfrom->vRecvGetData.empty()) return fOk;
5513 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5514 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5515 // Don't bother if send buffer is too full to respond anyway
5516 if (pfrom->nSendSize >= SendBufferSize())
5520 CNetMessage& msg = *it;
5523 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5524 // msg.hdr.nMessageSize, msg.vRecv.size(),
5525 // msg.complete() ? "Y" : "N");
5527 // end, if an incomplete message is found
5528 if (!msg.complete())
5531 // at this point, any failure means we can delete the current message
5534 // Scan for message start
5535 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5536 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5542 CMessageHeader& hdr = msg.hdr;
5543 if (!hdr.IsValid(Params().MessageStart()))
5545 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5548 string strCommand = hdr.GetCommand();
5551 unsigned int nMessageSize = hdr.nMessageSize;
5554 CDataStream& vRecv = msg.vRecv;
5555 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5556 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5557 if (nChecksum != hdr.nChecksum)
5559 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5560 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5568 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5569 boost::this_thread::interruption_point();
5571 catch (const std::ios_base::failure& e)
5573 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5574 if (strstr(e.what(), "end of data"))
5576 // Allow exceptions from under-length message on vRecv
5577 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());
5579 else if (strstr(e.what(), "size too large"))
5581 // Allow exceptions from over-long size
5582 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5586 //PrintExceptionContinue(&e, "ProcessMessages()");
5589 catch (const boost::thread_interrupted&) {
5592 catch (const std::exception& e) {
5593 PrintExceptionContinue(&e, "ProcessMessages()");
5595 PrintExceptionContinue(NULL, "ProcessMessages()");
5599 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5604 // In case the connection got shut down, its receive buffer was wiped
5605 if (!pfrom->fDisconnect)
5606 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5612 bool SendMessages(CNode* pto, bool fSendTrickle)
5614 const Consensus::Params& consensusParams = Params().GetConsensus();
5616 // Don't send anything until we get its version message
5617 if (pto->nVersion == 0)
5623 bool pingSend = false;
5624 if (pto->fPingQueued) {
5625 // RPC ping request by user
5628 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5629 // Ping automatically sent as a latency probe & keepalive.
5634 while (nonce == 0) {
5635 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5637 pto->fPingQueued = false;
5638 pto->nPingUsecStart = GetTimeMicros();
5639 if (pto->nVersion > BIP0031_VERSION) {
5640 pto->nPingNonceSent = nonce;
5641 pto->PushMessage("ping", nonce);
5643 // Peer is too old to support ping command with nonce, pong will never arrive.
5644 pto->nPingNonceSent = 0;
5645 pto->PushMessage("ping");
5649 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5653 // Address refresh broadcast
5654 static int64_t nLastRebroadcast;
5655 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5658 BOOST_FOREACH(CNode* pnode, vNodes)
5660 // Periodically clear addrKnown to allow refresh broadcasts
5661 if (nLastRebroadcast)
5662 pnode->addrKnown.reset();
5664 // Rebroadcast our address
5665 AdvertizeLocal(pnode);
5667 if (!vNodes.empty())
5668 nLastRebroadcast = GetTime();
5676 vector<CAddress> vAddr;
5677 vAddr.reserve(pto->vAddrToSend.size());
5678 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5680 if (!pto->addrKnown.contains(addr.GetKey()))
5682 pto->addrKnown.insert(addr.GetKey());
5683 vAddr.push_back(addr);
5684 // receiver rejects addr messages larger than 1000
5685 if (vAddr.size() >= 1000)
5687 pto->PushMessage("addr", vAddr);
5692 pto->vAddrToSend.clear();
5694 pto->PushMessage("addr", vAddr);
5697 CNodeState &state = *State(pto->GetId());
5698 if (state.fShouldBan) {
5699 if (pto->fWhitelisted)
5700 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5702 pto->fDisconnect = true;
5703 if (pto->addr.IsLocal())
5704 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5707 CNode::Ban(pto->addr);
5710 state.fShouldBan = false;
5713 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5714 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5715 state.rejects.clear();
5718 if (pindexBestHeader == NULL)
5719 pindexBestHeader = chainActive.Tip();
5720 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.
5721 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5722 // Only actively request headers from a single peer, unless we're close to today.
5723 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5724 state.fSyncStarted = true;
5726 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5727 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5728 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5732 // Resend wallet transactions that haven't gotten in a block yet
5733 // Except during reindex, importing and IBD, when old wallet
5734 // transactions become unconfirmed and spams other nodes.
5735 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5737 GetMainSignals().Broadcast(nTimeBestReceived);
5741 // Message: inventory
5744 vector<CInv> vInvWait;
5746 LOCK(pto->cs_inventory);
5747 vInv.reserve(pto->vInventoryToSend.size());
5748 vInvWait.reserve(pto->vInventoryToSend.size());
5749 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5751 if (pto->setInventoryKnown.count(inv))
5754 // trickle out tx inv to protect privacy
5755 if (inv.type == MSG_TX && !fSendTrickle)
5757 // 1/4 of tx invs blast to all immediately
5758 static uint256 hashSalt;
5759 if (hashSalt.IsNull())
5760 hashSalt = GetRandHash();
5761 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5762 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5763 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5767 vInvWait.push_back(inv);
5772 // returns true if wasn't already contained in the set
5773 if (pto->setInventoryKnown.insert(inv).second)
5775 vInv.push_back(inv);
5776 if (vInv.size() >= 1000)
5778 pto->PushMessage("inv", vInv);
5783 pto->vInventoryToSend = vInvWait;
5786 pto->PushMessage("inv", vInv);
5788 // Detect whether we're stalling
5789 int64_t nNow = GetTimeMicros();
5790 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5791 // Stalling only triggers when the block download window cannot move. During normal steady state,
5792 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5793 // should only happen during initial block download.
5794 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5795 pto->fDisconnect = true;
5797 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5798 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5799 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5800 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5801 // to unreasonably increase our timeout.
5802 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5803 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5804 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5805 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5806 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5807 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5808 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5809 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5810 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5811 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5812 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5814 if (queuedBlock.nTimeDisconnect < nNow) {
5815 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5816 pto->fDisconnect = true;
5821 // Message: getdata (blocks)
5823 vector<CInv> vGetData;
5824 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5825 vector<CBlockIndex*> vToDownload;
5826 NodeId staller = -1;
5827 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5828 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5829 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5830 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5831 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5832 pindex->nHeight, pto->id);
5834 if (state.nBlocksInFlight == 0 && staller != -1) {
5835 if (State(staller)->nStallingSince == 0) {
5836 State(staller)->nStallingSince = nNow;
5837 LogPrint("net", "Stall started peer=%d\n", staller);
5843 // Message: getdata (non-blocks)
5845 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5847 const CInv& inv = (*pto->mapAskFor.begin()).second;
5848 if (!AlreadyHave(inv))
5851 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5852 vGetData.push_back(inv);
5853 if (vGetData.size() >= 1000)
5855 pto->PushMessage("getdata", vGetData);
5859 //If we're not going to ask, don't expect a response.
5860 pto->setAskFor.erase(inv.hash);
5862 pto->mapAskFor.erase(pto->mapAskFor.begin());
5864 if (!vGetData.empty())
5865 pto->PushMessage("getdata", vGetData);
5871 std::string CBlockFileInfo::ToString() const {
5872 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));
5883 BlockMap::iterator it1 = mapBlockIndex.begin();
5884 for (; it1 != mapBlockIndex.end(); it1++)
5885 delete (*it1).second;
5886 mapBlockIndex.clear();
5888 // orphan transactions
5889 mapOrphanTransactions.clear();
5890 mapOrphanTransactionsByPrev.clear();
5892 } instance_of_cmaincleanup;
5894 extern "C" const char* getDataDir()
5896 return GetDataDir().string().c_str();