1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "chainparams.h"
11 #include "checkpoints.h"
12 #include "checkqueue.h"
17 #include "txmempool.h"
18 #include "ui_interface.h"
20 #include "utilmoneystr.h"
24 #include <boost/algorithm/string/replace.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/filesystem/fstream.hpp>
27 #include <boost/thread.hpp>
29 using namespace boost;
33 # error "Bitcoin cannot be compiled without assertions."
40 CCriticalSection cs_main;
42 BlockMap mapBlockIndex;
44 CBlockIndex *pindexBestHeader = NULL;
45 int64_t nTimeBestReceived = 0;
46 CWaitableCriticalSection csBestBlock;
47 CConditionVariable cvBlockChange;
48 int nScriptCheckThreads = 0;
49 bool fImporting = false;
50 bool fReindex = false;
51 bool fTxIndex = false;
52 bool fIsBareMultisigStd = true;
53 unsigned int nCoinCacheSize = 5000;
56 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
57 CFeeRate minRelayTxFee = CFeeRate(1000);
59 CTxMemPool mempool(::minRelayTxFee);
65 map<uint256, COrphanTx> mapOrphanTransactions;
66 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
67 void EraseOrphansFor(NodeId peer);
69 // Constant stuff for coinbase transactions we create:
70 CScript COINBASE_FLAGS;
72 const string strMessageMagic = "Bitcoin Signed Message:\n";
77 struct CBlockIndexWorkComparator
79 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
80 // First sort by most total work, ...
81 if (pa->nChainWork > pb->nChainWork) return false;
82 if (pa->nChainWork < pb->nChainWork) return true;
84 // ... then by earliest time received, ...
85 if (pa->nSequenceId < pb->nSequenceId) return false;
86 if (pa->nSequenceId > pb->nSequenceId) return true;
88 // Use pointer address as tie breaker (should only happen with blocks
89 // loaded from disk, as those all have id 0).
90 if (pa < pb) return false;
91 if (pa > pb) return true;
98 CBlockIndex *pindexBestInvalid;
100 // The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS or better that are at least
101 // as good as our current tip. Entries may be failed, though.
102 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
103 // Number of nodes with fSyncStarted.
104 int nSyncStarted = 0;
105 // All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
106 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
108 CCriticalSection cs_LastBlockFile;
109 CBlockFileInfo infoLastBlockFile;
110 int nLastBlockFile = 0;
112 // Every received block is assigned a unique and increasing identifier, so we
113 // know which one to give priority in case of a fork.
114 CCriticalSection cs_nBlockSequenceId;
115 // Blocks loaded from disk are assigned id 0, so start the counter at 1.
116 uint32_t nBlockSequenceId = 1;
118 // Sources of received blocks, to be able to send them reject messages or ban
119 // them, if processing happens afterwards. Protected by cs_main.
120 map<uint256, NodeId> mapBlockSource;
122 // Blocks that are in flight, and that are in the queue to be downloaded.
123 // Protected by cs_main.
126 CBlockIndex *pindex; // Optional.
127 int64_t nTime; // Time of "getdata" request in microseconds.
129 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
133 //////////////////////////////////////////////////////////////////////////////
135 // dispatching functions
138 // These functions dispatch to one or all registered wallets
142 struct CMainSignals {
143 // Notifies listeners of updated transaction data (transaction, and optionally the block it is found in.
144 boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
145 // Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
146 boost::signals2::signal<void (const uint256 &)> EraseTransaction;
147 // Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
148 boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
149 // Notifies listeners of a new active block chain.
150 boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
151 // Notifies listeners about an inventory item being seen on the network.
152 boost::signals2::signal<void (const uint256 &)> Inventory;
153 // Tells listeners to broadcast their data.
154 boost::signals2::signal<void ()> Broadcast;
159 void RegisterValidationInterface(CValidationInterface* pwalletIn) {
160 g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
161 g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
162 g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
163 g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
164 g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
165 g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
168 void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
169 g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
170 g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
171 g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
172 g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
173 g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
174 g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
177 void UnregisterAllValidationInterfaces() {
178 g_signals.Broadcast.disconnect_all_slots();
179 g_signals.Inventory.disconnect_all_slots();
180 g_signals.SetBestChain.disconnect_all_slots();
181 g_signals.UpdatedTransaction.disconnect_all_slots();
182 g_signals.EraseTransaction.disconnect_all_slots();
183 g_signals.SyncTransaction.disconnect_all_slots();
186 void SyncWithWallets(const CTransaction &tx, const CBlock *pblock) {
187 g_signals.SyncTransaction(tx, pblock);
190 //////////////////////////////////////////////////////////////////////////////
192 // Registration of network node signals.
197 struct CBlockReject {
198 unsigned char chRejectCode;
199 string strRejectReason;
203 // Maintain validation-specific state about nodes, protected by cs_main, instead
204 // by CNode's own locks. This simplifies asynchronous operation, where
205 // processing of incoming data is done after the ProcessMessage call returns,
206 // and we're no longer holding the node's locks.
208 // Accumulated misbehaviour score for this peer.
210 // Whether this peer should be disconnected and banned (unless whitelisted).
212 // String name of this peer (debugging/logging purposes).
214 // List of asynchronously-determined block rejections to notify this peer about.
215 std::vector<CBlockReject> rejects;
216 // The best known block we know this peer has announced.
217 CBlockIndex *pindexBestKnownBlock;
218 // The hash of the last unknown block this peer has announced.
219 uint256 hashLastUnknownBlock;
220 // The last full block we both have.
221 CBlockIndex *pindexLastCommonBlock;
222 // Whether we've started headers synchronization with this peer.
224 // Since when we're stalling block download progress (in microseconds), or 0.
225 int64_t nStallingSince;
226 list<QueuedBlock> vBlocksInFlight;
232 pindexBestKnownBlock = NULL;
233 hashLastUnknownBlock = uint256(0);
234 pindexLastCommonBlock = NULL;
235 fSyncStarted = false;
241 // Map maintaining per-node state. Requires cs_main.
242 map<NodeId, CNodeState> mapNodeState;
245 CNodeState *State(NodeId pnode) {
246 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
247 if (it == mapNodeState.end())
255 return chainActive.Height();
258 void InitializeNode(NodeId nodeid, const CNode *pnode) {
260 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
261 state.name = pnode->addrName;
264 void FinalizeNode(NodeId nodeid) {
266 CNodeState *state = State(nodeid);
268 if (state->fSyncStarted)
271 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
272 mapBlocksInFlight.erase(entry.hash);
273 EraseOrphansFor(nodeid);
275 mapNodeState.erase(nodeid);
279 void MarkBlockAsReceived(const uint256& hash) {
280 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
281 if (itInFlight != mapBlocksInFlight.end()) {
282 CNodeState *state = State(itInFlight->second.first);
283 state->vBlocksInFlight.erase(itInFlight->second.second);
284 state->nBlocksInFlight--;
285 state->nStallingSince = 0;
286 mapBlocksInFlight.erase(itInFlight);
291 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
292 CNodeState *state = State(nodeid);
293 assert(state != NULL);
295 // Make sure it's not listed somewhere already.
296 MarkBlockAsReceived(hash);
298 QueuedBlock newentry = {hash, pindex, GetTimeMicros()};
299 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
300 state->nBlocksInFlight++;
301 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
304 /** Check whether the last unknown block a peer advertized is not yet known. */
305 void ProcessBlockAvailability(NodeId nodeid) {
306 CNodeState *state = State(nodeid);
307 assert(state != NULL);
309 if (state->hashLastUnknownBlock != 0) {
310 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
311 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
312 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
313 state->pindexBestKnownBlock = itOld->second;
314 state->hashLastUnknownBlock = uint256(0);
319 /** Update tracking information about which blocks a peer is assumed to have. */
320 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
321 CNodeState *state = State(nodeid);
322 assert(state != NULL);
324 ProcessBlockAvailability(nodeid);
326 BlockMap::iterator it = mapBlockIndex.find(hash);
327 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
328 // An actually better block was announced.
329 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
330 state->pindexBestKnownBlock = it->second;
332 // An unknown block was announced; just assume that the latest one is the best one.
333 state->hashLastUnknownBlock = hash;
337 /** Find the last common ancestor two blocks have.
338 * Both pa and pb must be non-NULL. */
339 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
340 if (pa->nHeight > pb->nHeight) {
341 pa = pa->GetAncestor(pb->nHeight);
342 } else if (pb->nHeight > pa->nHeight) {
343 pb = pb->GetAncestor(pa->nHeight);
346 while (pa != pb && pa && pb) {
351 // Eventually all chain branches meet at the genesis block.
356 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
357 * at most count entries. */
358 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
362 vBlocks.reserve(vBlocks.size() + count);
363 CNodeState *state = State(nodeid);
364 assert(state != NULL);
366 // Make sure pindexBestKnownBlock is up to date, we'll need it.
367 ProcessBlockAvailability(nodeid);
369 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
370 // This peer has nothing interesting.
374 if (state->pindexLastCommonBlock == NULL) {
375 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
376 // Guessing wrong in either direction is not a problem.
377 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
380 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
381 // of their current tip anymore. Go back enough to fix that.
382 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
383 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
386 std::vector<CBlockIndex*> vToFetch;
387 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
388 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
389 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
390 // download that next block if the window were 1 larger.
391 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
392 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
393 NodeId waitingfor = -1;
394 while (pindexWalk->nHeight < nMaxHeight) {
395 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
396 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
397 // as iterating over ~100 CBlockIndex* entries anyway.
398 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
399 vToFetch.resize(nToFetch);
400 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
401 vToFetch[nToFetch - 1] = pindexWalk;
402 for (unsigned int i = nToFetch - 1; i > 0; i--) {
403 vToFetch[i - 1] = vToFetch[i]->pprev;
406 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
407 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
408 // pindexLastCommonBlock as long as all ancestors are already downloaded.
409 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
410 if (pindex->nStatus & BLOCK_HAVE_DATA) {
411 if (pindex->nChainTx)
412 state->pindexLastCommonBlock = pindex;
413 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
414 // The block is not already downloaded, and not yet in flight.
415 if (pindex->nHeight > nWindowEnd) {
416 // We reached the end of the window.
417 if (vBlocks.size() == 0 && waitingfor != nodeid) {
418 // We aren't able to fetch anything, but we would be if the download window was one larger.
419 nodeStaller = waitingfor;
423 vBlocks.push_back(pindex);
424 if (vBlocks.size() == count) {
427 } else if (waitingfor == -1) {
428 // This is the first already-in-flight block.
429 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
437 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
439 CNodeState *state = State(nodeid);
442 stats.nMisbehavior = state->nMisbehavior;
443 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
444 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
445 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
447 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
452 void RegisterNodeSignals(CNodeSignals& nodeSignals)
454 nodeSignals.GetHeight.connect(&GetHeight);
455 nodeSignals.ProcessMessages.connect(&ProcessMessages);
456 nodeSignals.SendMessages.connect(&SendMessages);
457 nodeSignals.InitializeNode.connect(&InitializeNode);
458 nodeSignals.FinalizeNode.connect(&FinalizeNode);
461 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
463 nodeSignals.GetHeight.disconnect(&GetHeight);
464 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
465 nodeSignals.SendMessages.disconnect(&SendMessages);
466 nodeSignals.InitializeNode.disconnect(&InitializeNode);
467 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
470 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
472 // Find the first block the caller has in the main chain
473 BOOST_FOREACH(const uint256& hash, locator.vHave) {
474 BlockMap::iterator mi = mapBlockIndex.find(hash);
475 if (mi != mapBlockIndex.end())
477 CBlockIndex* pindex = (*mi).second;
478 if (chain.Contains(pindex))
482 return chain.Genesis();
485 CCoinsViewCache *pcoinsTip = NULL;
486 CBlockTreeDB *pblocktree = NULL;
488 //////////////////////////////////////////////////////////////////////////////
490 // mapOrphanTransactions
493 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
495 uint256 hash = tx.GetHash();
496 if (mapOrphanTransactions.count(hash))
499 // Ignore big transactions, to avoid a
500 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
501 // large transaction with a missing parent then we assume
502 // it will rebroadcast it later, after the parent transaction(s)
503 // have been mined or received.
504 // 10,000 orphans, each of which is at most 5,000 bytes big is
505 // at most 500 megabytes of orphans:
506 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
509 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
513 mapOrphanTransactions[hash].tx = tx;
514 mapOrphanTransactions[hash].fromPeer = peer;
515 BOOST_FOREACH(const CTxIn& txin, tx.vin)
516 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
518 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
519 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
523 void static EraseOrphanTx(uint256 hash)
525 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
526 if (it == mapOrphanTransactions.end())
528 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
530 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
531 if (itPrev == mapOrphanTransactionsByPrev.end())
533 itPrev->second.erase(hash);
534 if (itPrev->second.empty())
535 mapOrphanTransactionsByPrev.erase(itPrev);
537 mapOrphanTransactions.erase(it);
540 void EraseOrphansFor(NodeId peer)
543 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
544 while (iter != mapOrphanTransactions.end())
546 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
547 if (maybeErase->second.fromPeer == peer)
549 EraseOrphanTx(maybeErase->second.tx.GetHash());
553 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
557 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
559 unsigned int nEvicted = 0;
560 while (mapOrphanTransactions.size() > nMaxOrphans)
562 // Evict a random orphan:
563 uint256 randomhash = GetRandHash();
564 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
565 if (it == mapOrphanTransactions.end())
566 it = mapOrphanTransactions.begin();
567 EraseOrphanTx(it->first);
579 bool IsStandardTx(const CTransaction& tx, string& reason)
581 AssertLockHeld(cs_main);
582 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
587 // Treat non-final transactions as non-standard to prevent a specific type
588 // of double-spend attack, as well as DoS attacks. (if the transaction
589 // can't be mined, the attacker isn't expending resources broadcasting it)
590 // Basically we don't want to propagate transactions that can't be included in
593 // However, IsFinalTx() is confusing... Without arguments, it uses
594 // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
595 // is set to the value of nHeight in the block. However, when IsFinalTx()
596 // is called within CBlock::AcceptBlock(), the height of the block *being*
597 // evaluated is what is used. Thus if we want to know if a transaction can
598 // be part of the *next* block, we need to call IsFinalTx() with one more
599 // than chainActive.Height().
601 // Timestamps on the other hand don't get any special treatment, because we
602 // can't know what timestamp the next block will have, and there aren't
603 // timestamp applications where it matters.
604 if (!IsFinalTx(tx, chainActive.Height() + 1)) {
605 reason = "non-final";
609 // Extremely large transactions with lots of inputs can cost the network
610 // almost as much to process as they cost the sender in fees, because
611 // computing signature hashes is O(ninputs*txsize). Limiting transactions
612 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
613 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
614 if (sz >= MAX_STANDARD_TX_SIZE) {
619 BOOST_FOREACH(const CTxIn& txin, tx.vin)
621 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
622 // keys. (remember the 520 byte limit on redeemScript size) That works
623 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
624 // bytes of scriptSig, which we round off to 1650 bytes for some minor
625 // future-proofing. That's also enough to spend a 20-of-20
626 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
627 // considered standard)
628 if (txin.scriptSig.size() > 1650) {
629 reason = "scriptsig-size";
632 if (!txin.scriptSig.IsPushOnly()) {
633 reason = "scriptsig-not-pushonly";
636 if (!txin.scriptSig.HasCanonicalPushes()) {
637 reason = "scriptsig-non-canonical-push";
642 unsigned int nDataOut = 0;
643 txnouttype whichType;
644 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
645 if (!::IsStandard(txout.scriptPubKey, whichType)) {
646 reason = "scriptpubkey";
650 if (whichType == TX_NULL_DATA)
652 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
653 reason = "bare-multisig";
655 } else if (txout.IsDust(::minRelayTxFee)) {
661 // only one OP_RETURN txout is permitted
663 reason = "multi-op-return";
670 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
672 AssertLockHeld(cs_main);
673 // Time based nLockTime implemented in 0.1.6
674 if (tx.nLockTime == 0)
676 if (nBlockHeight == 0)
677 nBlockHeight = chainActive.Height();
679 nBlockTime = GetAdjustedTime();
680 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
682 BOOST_FOREACH(const CTxIn& txin, tx.vin)
689 // Check transaction inputs to mitigate two
690 // potential denial-of-service attacks:
692 // 1. scriptSigs with extra data stuffed into them,
693 // not consumed by scriptPubKey (or P2SH script)
694 // 2. P2SH scripts with a crazy number of expensive
695 // CHECKSIG/CHECKMULTISIG operations
697 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
700 return true; // Coinbases don't use vin normally
702 for (unsigned int i = 0; i < tx.vin.size(); i++)
704 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
706 vector<vector<unsigned char> > vSolutions;
707 txnouttype whichType;
708 // get the scriptPubKey corresponding to this input:
709 const CScript& prevScript = prev.scriptPubKey;
710 if (!Solver(prevScript, whichType, vSolutions))
712 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
713 if (nArgsExpected < 0)
716 // Transactions with extra stuff in their scriptSigs are
717 // non-standard. Note that this EvalScript() call will
718 // be quick, because if there are any operations
719 // beside "push data" in the scriptSig
720 // IsStandard() will have already returned false
721 // and this method isn't called.
722 vector<vector<unsigned char> > stack;
723 if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker()))
726 if (whichType == TX_SCRIPTHASH)
730 CScript subscript(stack.back().begin(), stack.back().end());
731 vector<vector<unsigned char> > vSolutions2;
732 txnouttype whichType2;
733 if (Solver(subscript, whichType2, vSolutions2))
735 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
738 nArgsExpected += tmpExpected;
742 // Any other Script with less than 15 sigops OK:
743 unsigned int sigops = subscript.GetSigOpCount(true);
744 // ... extra data left on the stack after execution is OK, too:
745 return (sigops <= MAX_P2SH_SIGOPS);
749 if (stack.size() != (unsigned int)nArgsExpected)
756 unsigned int GetLegacySigOpCount(const CTransaction& tx)
758 unsigned int nSigOps = 0;
759 BOOST_FOREACH(const CTxIn& txin, tx.vin)
761 nSigOps += txin.scriptSig.GetSigOpCount(false);
763 BOOST_FOREACH(const CTxOut& txout, tx.vout)
765 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
770 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
775 unsigned int nSigOps = 0;
776 for (unsigned int i = 0; i < tx.vin.size(); i++)
778 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
779 if (prevout.scriptPubKey.IsPayToScriptHash())
780 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
792 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
794 // Basic checks that don't depend on any context
796 return state.DoS(10, error("CheckTransaction() : vin empty"),
797 REJECT_INVALID, "bad-txns-vin-empty");
799 return state.DoS(10, error("CheckTransaction() : vout empty"),
800 REJECT_INVALID, "bad-txns-vout-empty");
802 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
803 return state.DoS(100, error("CheckTransaction() : size limits failed"),
804 REJECT_INVALID, "bad-txns-oversize");
806 // Check for negative or overflow output values
807 CAmount nValueOut = 0;
808 BOOST_FOREACH(const CTxOut& txout, tx.vout)
810 if (txout.nValue < 0)
811 return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
812 REJECT_INVALID, "bad-txns-vout-negative");
813 if (txout.nValue > MAX_MONEY)
814 return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
815 REJECT_INVALID, "bad-txns-vout-toolarge");
816 nValueOut += txout.nValue;
817 if (!MoneyRange(nValueOut))
818 return state.DoS(100, error("CheckTransaction() : txout total out of range"),
819 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
822 // Check for duplicate inputs
823 set<COutPoint> vInOutPoints;
824 BOOST_FOREACH(const CTxIn& txin, tx.vin)
826 if (vInOutPoints.count(txin.prevout))
827 return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
828 REJECT_INVALID, "bad-txns-inputs-duplicate");
829 vInOutPoints.insert(txin.prevout);
834 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
835 return state.DoS(100, error("CheckTransaction() : coinbase script size"),
836 REJECT_INVALID, "bad-cb-length");
840 BOOST_FOREACH(const CTxIn& txin, tx.vin)
841 if (txin.prevout.IsNull())
842 return state.DoS(10, error("CheckTransaction() : prevout is null"),
843 REJECT_INVALID, "bad-txns-prevout-null");
849 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
853 uint256 hash = tx.GetHash();
854 double dPriorityDelta = 0;
855 CAmount nFeeDelta = 0;
856 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
857 if (dPriorityDelta > 0 || nFeeDelta > 0)
861 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
865 // There is a free transaction area in blocks created by most miners,
866 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
867 // to be considered to fall into this category. We don't want to encourage sending
868 // multiple transactions instead of one big transaction to avoid fees.
869 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
873 if (!MoneyRange(nMinFee))
879 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
880 bool* pfMissingInputs, bool fRejectInsaneFee)
882 AssertLockHeld(cs_main);
884 *pfMissingInputs = false;
886 if (!CheckTransaction(tx, state))
887 return error("AcceptToMemoryPool: : CheckTransaction failed");
889 // Coinbase is only valid in a block, not as a loose transaction
891 return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
892 REJECT_INVALID, "coinbase");
894 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
896 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
898 error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
899 REJECT_NONSTANDARD, reason);
901 // is it already in the memory pool?
902 uint256 hash = tx.GetHash();
903 if (pool.exists(hash))
906 // Check for conflicts with in-memory transactions
908 LOCK(pool.cs); // protect pool.mapNextTx
909 for (unsigned int i = 0; i < tx.vin.size(); i++)
911 COutPoint outpoint = tx.vin[i].prevout;
912 if (pool.mapNextTx.count(outpoint))
914 // Disable replacement feature for now
922 CCoinsViewCache view(&dummy);
924 CAmount nValueIn = 0;
927 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
928 view.SetBackend(viewMemPool);
930 // do we already have it?
931 if (view.HaveCoins(hash))
934 // do all inputs exist?
935 // Note that this does not check for the presence of actual outputs (see the next check for that),
936 // only helps filling in pfMissingInputs (to determine missing vs spent).
937 BOOST_FOREACH(const CTxIn txin, tx.vin) {
938 if (!view.HaveCoins(txin.prevout.hash)) {
940 *pfMissingInputs = true;
945 // are the actual inputs available?
946 if (!view.HaveInputs(tx))
947 return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
948 REJECT_DUPLICATE, "bad-txns-inputs-spent");
950 // Bring the best block into scope
953 nValueIn = view.GetValueIn(tx);
955 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
956 view.SetBackend(dummy);
959 // Check for non-standard pay-to-script-hash in inputs
960 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
961 return error("AcceptToMemoryPool: : nonstandard transaction input");
963 // Check that the transaction doesn't have an excessive number of
964 // sigops, making it impossible to mine. Since the coinbase transaction
965 // itself can contain sigops MAX_TX_SIGOPS is less than
966 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
967 // merely non-standard transaction.
968 unsigned int nSigOps = GetLegacySigOpCount(tx);
969 nSigOps += GetP2SHSigOpCount(tx, view);
970 if (nSigOps > MAX_TX_SIGOPS)
972 error("AcceptToMemoryPool : too many sigops %s, %d > %d",
973 hash.ToString(), nSigOps, MAX_TX_SIGOPS),
974 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
976 CAmount nValueOut = tx.GetValueOut();
977 CAmount nFees = nValueIn-nValueOut;
978 double dPriority = view.GetPriority(tx, chainActive.Height());
980 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
981 unsigned int nSize = entry.GetTxSize();
983 // Don't accept it if it can't get into a block
984 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
985 if (fLimitFree && nFees < txMinFee)
986 return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d",
987 hash.ToString(), nFees, txMinFee),
988 REJECT_INSUFFICIENTFEE, "insufficient fee");
990 // Continuously rate-limit free (really, very-low-fee)transactions
991 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
992 // be annoying or make others' transactions take longer to confirm.
993 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
995 static CCriticalSection csFreeLimiter;
996 static double dFreeCount;
997 static int64_t nLastTime;
998 int64_t nNow = GetTime();
1000 LOCK(csFreeLimiter);
1002 // Use an exponentially decaying ~10-minute window:
1003 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1005 // -limitfreerelay unit is thousand-bytes-per-minute
1006 // At default rate it would take over a month to fill 1GB
1007 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1008 return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
1009 REJECT_INSUFFICIENTFEE, "insufficient priority");
1010 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1011 dFreeCount += nSize;
1014 if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1015 return error("AcceptToMemoryPool: : insane fees %s, %d > %d",
1017 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1019 // Check against previous transactions
1020 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1021 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1023 return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
1025 // Store transaction in memory
1026 pool.addUnchecked(hash, entry);
1029 SyncWithWallets(tx, NULL);
1034 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
1035 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1037 CBlockIndex *pindexSlow = NULL;
1041 if (mempool.lookup(hash, txOut))
1049 if (pblocktree->ReadTxIndex(hash, postx)) {
1050 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1051 CBlockHeader header;
1054 fseek(file, postx.nTxOffset, SEEK_CUR);
1056 } catch (std::exception &e) {
1057 return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1059 hashBlock = header.GetHash();
1060 if (txOut.GetHash() != hash)
1061 return error("%s : txid mismatch", __func__);
1066 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1069 CCoinsViewCache &view = *pcoinsTip;
1070 const CCoins* coins = view.AccessCoins(hash);
1072 nHeight = coins->nHeight;
1075 pindexSlow = chainActive[nHeight];
1081 if (ReadBlockFromDisk(block, pindexSlow)) {
1082 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1083 if (tx.GetHash() == hash) {
1085 hashBlock = pindexSlow->GetBlockHash();
1100 //////////////////////////////////////////////////////////////////////////////
1102 // CBlock and CBlockIndex
1105 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1107 // Open history file to append
1108 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1110 return error("WriteBlockToDisk : OpenBlockFile failed");
1112 // Write index header
1113 unsigned int nSize = fileout.GetSerializeSize(block);
1114 fileout << FLATDATA(Params().MessageStart()) << nSize;
1117 long fileOutPos = ftell(fileout);
1119 return error("WriteBlockToDisk : ftell failed");
1120 pos.nPos = (unsigned int)fileOutPos;
1123 // Flush stdio buffers and commit to disk before returning
1125 if (!IsInitialBlockDownload())
1126 FileCommit(fileout);
1131 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1135 // Open history file to read
1136 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1138 return error("ReadBlockFromDisk : OpenBlockFile failed");
1144 catch (std::exception &e) {
1145 return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1149 if (!CheckProofOfWork(block.GetHash(), block.nBits))
1150 return error("ReadBlockFromDisk : Errors in block header");
1155 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1157 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1159 if (block.GetHash() != pindex->GetBlockHash())
1160 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1164 CAmount GetBlockValue(int nHeight, const CAmount& nFees)
1166 int64_t nSubsidy = 50 * COIN;
1167 int halvings = nHeight / Params().SubsidyHalvingInterval();
1169 // Force block reward to zero when right shift is undefined.
1173 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1174 nSubsidy >>= halvings;
1176 return nSubsidy + nFees;
1179 bool IsInitialBlockDownload()
1182 if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1184 static int64_t nLastUpdate;
1185 static CBlockIndex* pindexLastBest;
1186 if (chainActive.Tip() != pindexLastBest)
1188 pindexLastBest = chainActive.Tip();
1189 nLastUpdate = GetTime();
1191 return (GetTime() - nLastUpdate < 10 &&
1192 chainActive.Tip()->GetBlockTime() < GetTime() - 24 * 60 * 60);
1195 bool fLargeWorkForkFound = false;
1196 bool fLargeWorkInvalidChainFound = false;
1197 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1199 void CheckForkWarningConditions()
1201 AssertLockHeld(cs_main);
1202 // Before we get past initial download, we cannot reliably alert about forks
1203 // (we assume we don't get stuck on a fork before the last checkpoint)
1204 if (IsInitialBlockDownload())
1207 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1208 // of our head, drop it
1209 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1210 pindexBestForkTip = NULL;
1212 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (chainActive.Tip()->GetBlockWork() * 6)))
1214 if (!fLargeWorkForkFound)
1216 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1217 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1218 CAlert::Notify(warning, true);
1220 if (pindexBestForkTip)
1222 LogPrintf("CheckForkWarningConditions: 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",
1223 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1224 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1225 fLargeWorkForkFound = true;
1229 LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1230 fLargeWorkInvalidChainFound = true;
1235 fLargeWorkForkFound = false;
1236 fLargeWorkInvalidChainFound = false;
1240 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1242 AssertLockHeld(cs_main);
1243 // If we are on a fork that is sufficiently large, set a warning flag
1244 CBlockIndex* pfork = pindexNewForkTip;
1245 CBlockIndex* plonger = chainActive.Tip();
1246 while (pfork && pfork != plonger)
1248 while (plonger && plonger->nHeight > pfork->nHeight)
1249 plonger = plonger->pprev;
1250 if (pfork == plonger)
1252 pfork = pfork->pprev;
1255 // We define a condition which we should warn the user about as a fork of at least 7 blocks
1256 // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1257 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1258 // hash rate operating on the fork.
1259 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1260 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1261 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1262 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1263 pindexNewForkTip->nChainWork - pfork->nChainWork > (pfork->GetBlockWork() * 7) &&
1264 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1266 pindexBestForkTip = pindexNewForkTip;
1267 pindexBestForkBase = pfork;
1270 CheckForkWarningConditions();
1273 // Requires cs_main.
1274 void Misbehaving(NodeId pnode, int howmuch)
1279 CNodeState *state = State(pnode);
1283 state->nMisbehavior += howmuch;
1284 int banscore = GetArg("-banscore", 100);
1285 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1287 LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1288 state->fShouldBan = true;
1290 LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1293 void static InvalidChainFound(CBlockIndex* pindexNew)
1295 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1296 pindexBestInvalid = pindexNew;
1298 LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1299 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1300 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1301 pindexNew->GetBlockTime()));
1302 LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1303 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1304 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1305 CheckForkWarningConditions();
1308 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1310 if (state.IsInvalid(nDoS)) {
1311 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1312 if (it != mapBlockSource.end() && State(it->second)) {
1313 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason(), pindex->GetBlockHash()};
1314 State(it->second)->rejects.push_back(reject);
1316 Misbehaving(it->second, nDoS);
1319 if (!state.CorruptionPossible()) {
1320 pindex->nStatus |= BLOCK_FAILED_VALID;
1321 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1322 setBlockIndexCandidates.erase(pindex);
1323 InvalidChainFound(pindex);
1327 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1329 // mark inputs spent
1330 if (!tx.IsCoinBase()) {
1331 txundo.vprevout.reserve(tx.vin.size());
1332 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1333 txundo.vprevout.push_back(CTxInUndo());
1334 bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back());
1340 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1343 bool CScriptCheck::operator()() const {
1344 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1345 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingSignatureChecker(*ptxTo, nIn, cacheStore)))
1346 return error("CScriptCheck() : %s:%d VerifySignature failed", ptxTo->GetHash().ToString(), nIn);
1350 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1352 if (!tx.IsCoinBase())
1355 pvChecks->reserve(tx.vin.size());
1357 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1358 // for an attacker to attempt to split the network.
1359 if (!inputs.HaveInputs(tx))
1360 return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
1362 // While checking, GetBestBlock() refers to the parent block.
1363 // This is also true for mempool checks.
1364 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1365 int nSpendHeight = pindexPrev->nHeight + 1;
1366 CAmount nValueIn = 0;
1368 for (unsigned int i = 0; i < tx.vin.size(); i++)
1370 const COutPoint &prevout = tx.vin[i].prevout;
1371 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1374 // If prev is coinbase, check that it's matured
1375 if (coins->IsCoinBase()) {
1376 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1377 return state.Invalid(
1378 error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1379 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1382 // Check for negative or overflow input values
1383 nValueIn += coins->vout[prevout.n].nValue;
1384 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1385 return state.DoS(100, error("CheckInputs() : txin values out of range"),
1386 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1390 if (nValueIn < tx.GetValueOut())
1391 return state.DoS(100, error("CheckInputs() : %s value in (%s) < value out (%s)",
1392 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1393 REJECT_INVALID, "bad-txns-in-belowout");
1395 // Tally transaction fees
1396 CAmount nTxFee = nValueIn - tx.GetValueOut();
1398 return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
1399 REJECT_INVALID, "bad-txns-fee-negative");
1401 if (!MoneyRange(nFees))
1402 return state.DoS(100, error("CheckInputs() : nFees out of range"),
1403 REJECT_INVALID, "bad-txns-fee-outofrange");
1405 // The first loop above does all the inexpensive checks.
1406 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1407 // Helps prevent CPU exhaustion attacks.
1409 // Skip ECDSA signature verification when connecting blocks
1410 // before the last block chain checkpoint. This is safe because block merkle hashes are
1411 // still computed and checked, and any change will be caught at the next checkpoint.
1412 if (fScriptChecks) {
1413 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1414 const COutPoint &prevout = tx.vin[i].prevout;
1415 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1419 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1421 pvChecks->push_back(CScriptCheck());
1422 check.swap(pvChecks->back());
1423 } else if (!check()) {
1424 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1425 // Check whether the failure was caused by a
1426 // non-mandatory script verification check, such as
1427 // non-standard DER encodings or non-null dummy
1428 // arguments; if so, don't trigger DoS protection to
1429 // avoid splitting the network between upgraded and
1430 // non-upgraded nodes.
1431 CScriptCheck check(*coins, tx, i,
1432 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1434 return state.Invalid(false, REJECT_NONSTANDARD, "non-mandatory-script-verify-flag");
1436 // Failures of other flags indicate a transaction that is
1437 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1438 // such nodes as they are not following the protocol. That
1439 // said during an upgrade careful thought should be taken
1440 // as to the correct behavior - we may want to continue
1441 // peering with non-upgraded nodes even after a soft-fork
1442 // super-majority vote has passed.
1443 return state.DoS(100,false, REJECT_INVALID, "mandatory-script-verify-flag-failed");
1454 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1456 assert(pindex->GetBlockHash() == view.GetBestBlock());
1463 CBlockUndo blockUndo;
1464 CDiskBlockPos pos = pindex->GetUndoPos();
1466 return error("DisconnectBlock() : no undo data available");
1467 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1468 return error("DisconnectBlock() : failure reading undo data");
1470 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1471 return error("DisconnectBlock() : block and undo data inconsistent");
1473 // undo transactions in reverse order
1474 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1475 const CTransaction &tx = block.vtx[i];
1476 uint256 hash = tx.GetHash();
1478 // Check that all outputs are available and match the outputs in the block itself
1479 // exactly. Note that transactions with only provably unspendable outputs won't
1480 // have outputs available even in the block itself, so we handle that case
1481 // specially with outsEmpty.
1484 CCoinsModifier outs = view.ModifyCoins(hash);
1485 outs->ClearUnspendable();
1487 CCoins outsBlock(tx, pindex->nHeight);
1488 // The CCoins serialization does not serialize negative numbers.
1489 // No network rules currently depend on the version here, so an inconsistency is harmless
1490 // but it must be corrected before txout nversion ever influences a network rule.
1491 if (outsBlock.nVersion < 0)
1492 outs->nVersion = outsBlock.nVersion;
1493 if (*outs != outsBlock)
1494 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1501 if (i > 0) { // not coinbases
1502 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1503 if (txundo.vprevout.size() != tx.vin.size())
1504 return error("DisconnectBlock() : transaction and undo data inconsistent");
1505 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1506 const COutPoint &out = tx.vin[j].prevout;
1507 const CTxInUndo &undo = txundo.vprevout[j];
1508 CCoinsModifier coins = view.ModifyCoins(out.hash);
1509 if (undo.nHeight != 0) {
1510 // undo data contains height: this is the last output of the prevout tx being spent
1511 if (!coins->IsPruned())
1512 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1514 coins->fCoinBase = undo.fCoinBase;
1515 coins->nHeight = undo.nHeight;
1516 coins->nVersion = undo.nVersion;
1518 if (coins->IsPruned())
1519 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1521 if (coins->IsAvailable(out.n))
1522 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1523 if (coins->vout.size() < out.n+1)
1524 coins->vout.resize(out.n+1);
1525 coins->vout[out.n] = undo.txout;
1530 // move best block pointer to prevout block
1531 view.SetBestBlock(pindex->pprev->GetBlockHash());
1541 void static FlushBlockFile(bool fFinalize = false)
1543 LOCK(cs_LastBlockFile);
1545 CDiskBlockPos posOld(nLastBlockFile, 0);
1547 FILE *fileOld = OpenBlockFile(posOld);
1550 TruncateFile(fileOld, infoLastBlockFile.nSize);
1551 FileCommit(fileOld);
1555 fileOld = OpenUndoFile(posOld);
1558 TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
1559 FileCommit(fileOld);
1564 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1566 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1568 void ThreadScriptCheck() {
1569 RenameThread("bitcoin-scriptch");
1570 scriptcheckqueue.Thread();
1573 static int64_t nTimeVerify = 0;
1574 static int64_t nTimeConnect = 0;
1575 static int64_t nTimeIndex = 0;
1576 static int64_t nTimeCallbacks = 0;
1577 static int64_t nTimeTotal = 0;
1579 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1581 AssertLockHeld(cs_main);
1582 // Check it again in case a previous version let a bad block in
1583 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1586 // verify that the view's current state corresponds to the previous block
1587 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
1588 assert(hashPrevBlock == view.GetBestBlock());
1590 // Special case for the genesis block, skipping connection of its transactions
1591 // (its coinbase is unspendable)
1592 if (block.GetHash() == Params().HashGenesisBlock()) {
1593 view.SetBestBlock(pindex->GetBlockHash());
1597 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1599 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1600 // unless those are already completely spent.
1601 // If such overwrites are allowed, coinbases and transactions depending upon those
1602 // can be duplicated to remove the ability to spend the first instance -- even after
1603 // being sent to another address.
1604 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1605 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1606 // already refuses previously-known transaction ids entirely.
1607 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1608 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1609 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1610 // initial block download.
1611 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1612 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1613 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1614 if (fEnforceBIP30) {
1615 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1616 const CCoins* coins = view.AccessCoins(tx.GetHash());
1617 if (coins && !coins->IsPruned())
1618 return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
1619 REJECT_INVALID, "bad-txns-BIP30");
1623 // BIP16 didn't become active until Apr 1 2012
1624 int64_t nBIP16SwitchTime = 1333238400;
1625 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1627 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1629 CBlockUndo blockundo;
1631 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1633 int64_t nTimeStart = GetTimeMicros();
1636 unsigned int nSigOps = 0;
1637 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1638 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1639 vPos.reserve(block.vtx.size());
1640 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1641 for (unsigned int i = 0; i < block.vtx.size(); i++)
1643 const CTransaction &tx = block.vtx[i];
1645 nInputs += tx.vin.size();
1646 nSigOps += GetLegacySigOpCount(tx);
1647 if (nSigOps > MAX_BLOCK_SIGOPS)
1648 return state.DoS(100, error("ConnectBlock() : too many sigops"),
1649 REJECT_INVALID, "bad-blk-sigops");
1651 if (!tx.IsCoinBase())
1653 if (!view.HaveInputs(tx))
1654 return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
1655 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1657 if (fStrictPayToScriptHash)
1659 // Add in sigops done by pay-to-script-hash inputs;
1660 // this is to prevent a "rogue miner" from creating
1661 // an incredibly-expensive-to-validate block.
1662 nSigOps += GetP2SHSigOpCount(tx, view);
1663 if (nSigOps > MAX_BLOCK_SIGOPS)
1664 return state.DoS(100, error("ConnectBlock() : too many sigops"),
1665 REJECT_INVALID, "bad-blk-sigops");
1668 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1670 std::vector<CScriptCheck> vChecks;
1671 if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1673 control.Add(vChecks);
1678 blockundo.vtxundo.push_back(CTxUndo());
1680 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1682 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1683 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1685 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1686 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);
1688 if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1689 return state.DoS(100,
1690 error("ConnectBlock() : coinbase pays too much (actual=%d vs limit=%d)",
1691 block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
1692 REJECT_INVALID, "bad-cb-amount");
1694 if (!control.Wait())
1695 return state.DoS(100, false);
1696 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1697 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);
1702 // Write undo information to disk
1703 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1705 if (pindex->GetUndoPos().IsNull()) {
1707 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1708 return error("ConnectBlock() : FindUndoPos failed");
1709 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1710 return state.Abort("Failed to write undo data");
1712 // update nUndoPos in block index
1713 pindex->nUndoPos = pos.nPos;
1714 pindex->nStatus |= BLOCK_HAVE_UNDO;
1717 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1719 CDiskBlockIndex blockindex(pindex);
1720 if (!pblocktree->WriteBlockIndex(blockindex))
1721 return state.Abort("Failed to write block index");
1725 if (!pblocktree->WriteTxIndex(vPos))
1726 return state.Abort("Failed to write transaction index");
1728 // add this block to the view's block chain
1729 view.SetBestBlock(pindex->GetBlockHash());
1731 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1732 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1734 // Watch for changes to the previous coinbase transaction.
1735 static uint256 hashPrevBestCoinBase;
1736 g_signals.UpdatedTransaction(hashPrevBestCoinBase);
1737 hashPrevBestCoinBase = block.vtx[0].GetHash();
1739 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1740 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1745 // Update the on-disk chain state.
1746 bool static WriteChainState(CValidationState &state) {
1747 static int64_t nLastWrite = 0;
1748 if (pcoinsTip->GetCacheSize() > nCoinCacheSize || (!IsInitialBlockDownload() && GetTimeMicros() > nLastWrite + 600*1000000)) {
1749 // Typical CCoins structures on disk are around 100 bytes in size.
1750 // Pushing a new one to the database can cause it to be written
1751 // twice (once in the log, and once in the tables). This is already
1752 // an overestimation, as most will delete an existing entry or
1753 // overwrite one. Still, use a conservative safety factor of 2.
1754 if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1755 return state.Error("out of disk space");
1758 if (!pcoinsTip->Flush())
1759 return state.Abort("Failed to write to coin database");
1760 nLastWrite = GetTimeMicros();
1765 // Update chainActive and related internal data structures.
1766 void static UpdateTip(CBlockIndex *pindexNew) {
1767 chainActive.SetTip(pindexNew);
1770 nTimeBestReceived = GetTime();
1771 mempool.AddTransactionsUpdated(1);
1773 LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n",
1774 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1775 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1776 Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
1778 cvBlockChange.notify_all();
1780 // Check the version of the last 100 blocks to see if we need to upgrade:
1781 static bool fWarned = false;
1782 if (!IsInitialBlockDownload() && !fWarned)
1785 const CBlockIndex* pindex = chainActive.Tip();
1786 for (int i = 0; i < 100 && pindex != NULL; i++)
1788 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1790 pindex = pindex->pprev;
1793 LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
1794 if (nUpgraded > 100/2)
1796 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1797 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1798 CAlert::Notify(strMiscWarning, true);
1804 // Disconnect chainActive's tip.
1805 bool static DisconnectTip(CValidationState &state) {
1806 CBlockIndex *pindexDelete = chainActive.Tip();
1807 assert(pindexDelete);
1808 mempool.check(pcoinsTip);
1809 // Read block from disk.
1811 if (!ReadBlockFromDisk(block, pindexDelete))
1812 return state.Abort("Failed to read block");
1813 // Apply the block atomically to the chain state.
1814 int64_t nStart = GetTimeMicros();
1816 CCoinsViewCache view(pcoinsTip);
1817 if (!DisconnectBlock(block, state, pindexDelete, view))
1818 return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1819 assert(view.Flush());
1821 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1822 // Write the chain state to disk, if necessary.
1823 if (!WriteChainState(state))
1825 // Resurrect mempool transactions from the disconnected block.
1826 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1827 // ignore validation errors in resurrected transactions
1828 list<CTransaction> removed;
1829 CValidationState stateDummy;
1830 if (!tx.IsCoinBase())
1831 if (!AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
1832 mempool.remove(tx, removed, true);
1834 mempool.check(pcoinsTip);
1835 // Update chainActive and related variables.
1836 UpdateTip(pindexDelete->pprev);
1837 // Let wallets know transactions went from 1-confirmed to
1838 // 0-confirmed or conflicted:
1839 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1840 SyncWithWallets(tx, NULL);
1845 static int64_t nTimeReadFromDisk = 0;
1846 static int64_t nTimeConnectTotal = 0;
1847 static int64_t nTimeFlush = 0;
1848 static int64_t nTimeChainState = 0;
1849 static int64_t nTimePostConnect = 0;
1851 // Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
1852 // corresponding to pindexNew, to bypass loading it again from disk.
1853 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
1854 assert(pindexNew->pprev == chainActive.Tip());
1855 mempool.check(pcoinsTip);
1856 // Read block from disk.
1857 int64_t nTime1 = GetTimeMicros();
1860 if (!ReadBlockFromDisk(block, pindexNew))
1861 return state.Abort("Failed to read block");
1864 // Apply the block atomically to the chain state.
1865 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
1867 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
1869 CCoinsViewCache view(pcoinsTip);
1870 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
1871 if (!ConnectBlock(*pblock, state, pindexNew, view)) {
1872 if (state.IsInvalid())
1873 InvalidBlockFound(pindexNew, state);
1874 return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
1876 mapBlockSource.erase(inv.hash);
1877 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
1878 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
1879 assert(view.Flush());
1881 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
1882 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
1883 // Write the chain state to disk, if necessary.
1884 if (!WriteChainState(state))
1886 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
1887 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
1888 // Remove conflicting transactions from the mempool.
1889 list<CTransaction> txConflicted;
1890 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
1891 mempool.check(pcoinsTip);
1892 // Update chainActive & related variables.
1893 UpdateTip(pindexNew);
1894 // Tell wallet about transactions that went from mempool
1896 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
1897 SyncWithWallets(tx, NULL);
1899 // ... and about transactions that got confirmed:
1900 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
1901 SyncWithWallets(tx, pblock);
1903 // Update best block in wallet (so we can detect restored wallets)
1904 // Emit this signal after the SyncWithWallets signals as the wallet relies on that everything up to this point has been synced
1905 if ((chainActive.Height() % 20160) == 0 || ((chainActive.Height() % 144) == 0 && !IsInitialBlockDownload()))
1906 g_signals.SetBestChain(chainActive.GetLocator());
1908 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
1909 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
1910 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
1914 // Return the tip of the chain with the most work in it, that isn't
1915 // known to be invalid (it's however far from certain to be valid).
1916 static CBlockIndex* FindMostWorkChain() {
1918 CBlockIndex *pindexNew = NULL;
1920 // Find the best candidate header.
1922 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
1923 if (it == setBlockIndexCandidates.rend())
1928 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
1929 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
1930 CBlockIndex *pindexTest = pindexNew;
1931 bool fInvalidAncestor = false;
1932 while (pindexTest && !chainActive.Contains(pindexTest)) {
1933 assert(pindexTest->nStatus & BLOCK_HAVE_DATA);
1934 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
1935 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1936 // Candidate has an invalid ancestor, remove entire chain from the set.
1937 if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1938 pindexBestInvalid = pindexNew;
1939 CBlockIndex *pindexFailed = pindexNew;
1940 while (pindexTest != pindexFailed) {
1941 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1942 setBlockIndexCandidates.erase(pindexFailed);
1943 pindexFailed = pindexFailed->pprev;
1945 setBlockIndexCandidates.erase(pindexTest);
1946 fInvalidAncestor = true;
1949 pindexTest = pindexTest->pprev;
1951 if (!fInvalidAncestor)
1956 // Try to make some progress towards making pindexMostWork the active block.
1957 // pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
1958 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
1959 AssertLockHeld(cs_main);
1960 bool fInvalidFound = false;
1961 const CBlockIndex *pindexOldTip = chainActive.Tip();
1962 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
1964 // Disconnect active blocks which are no longer in the best chain.
1965 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
1966 if (!DisconnectTip(state))
1970 // Build list of new blocks to connect.
1971 std::vector<CBlockIndex*> vpindexToConnect;
1972 bool fContinue = true;
1973 int nHeight = pindexFork ? pindexFork->nHeight : -1;
1974 while (fContinue && nHeight != pindexMostWork->nHeight) {
1975 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
1976 // a few blocks along the way.
1977 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
1978 vpindexToConnect.clear();
1979 vpindexToConnect.reserve(nTargetHeight - nHeight);
1980 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
1981 while (pindexIter && pindexIter->nHeight != nHeight) {
1982 vpindexToConnect.push_back(pindexIter);
1983 pindexIter = pindexIter->pprev;
1985 nHeight = nTargetHeight;
1987 // Connect new blocks.
1988 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
1989 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
1990 if (state.IsInvalid()) {
1991 // The block violates a consensus rule.
1992 if (!state.CorruptionPossible())
1993 InvalidChainFound(vpindexToConnect.back());
1994 state = CValidationState();
1995 fInvalidFound = true;
1999 // A system error occurred (disk space, database error, ...).
2003 // Delete all entries in setBlockIndexCandidates that are worse than our new current block.
2004 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2005 // reorganization to a better block fails.
2006 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2007 while (setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2008 setBlockIndexCandidates.erase(it++);
2010 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2011 assert(!setBlockIndexCandidates.empty());
2012 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2013 // We're in a better position than we were. Return temporarily to release the lock.
2021 // Callbacks/notifications for a new best chain.
2023 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2025 CheckForkWarningConditions();
2027 if (!pblocktree->Flush())
2028 return state.Abort("Failed to sync block index");
2033 // Make the best chain active, in multiple steps. The result is either failure
2034 // or an activated best chain. pblock is either NULL or a pointer to a block
2035 // that is already loaded (to avoid loading it again from disk).
2036 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2037 CBlockIndex *pindexNewTip = NULL;
2038 CBlockIndex *pindexMostWork = NULL;
2040 boost::this_thread::interruption_point();
2042 bool fInitialDownload;
2045 pindexMostWork = FindMostWorkChain();
2047 // Whether we have anything to do at all.
2048 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2051 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2054 pindexNewTip = chainActive.Tip();
2055 fInitialDownload = IsInitialBlockDownload();
2057 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2059 // Notifications/callbacks that can run without cs_main
2060 if (!fInitialDownload) {
2061 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2062 // Relay inventory, but don't relay old inventory during initial block download.
2063 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2066 BOOST_FOREACH(CNode* pnode, vNodes)
2067 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2068 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2071 uiInterface.NotifyBlockTip(hashNewTip);
2073 } while(pindexMostWork != chainActive.Tip());
2078 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2080 // Check for duplicate
2081 uint256 hash = block.GetHash();
2082 BlockMap::iterator it = mapBlockIndex.find(hash);
2083 if (it != mapBlockIndex.end())
2086 // Construct new block index object
2087 CBlockIndex* pindexNew = new CBlockIndex(block);
2089 // We assign the sequence id to blocks only when the full data is available,
2090 // to avoid miners withholding blocks but broadcasting headers, to get a
2091 // competitive advantage.
2092 pindexNew->nSequenceId = 0;
2093 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2094 pindexNew->phashBlock = &((*mi).first);
2095 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2096 if (miPrev != mapBlockIndex.end())
2098 pindexNew->pprev = (*miPrev).second;
2099 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2100 pindexNew->BuildSkip();
2102 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork();
2103 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2104 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2105 pindexBestHeader = pindexNew;
2107 // Ok if it fails, we'll download the header again next time.
2108 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
2113 // Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
2114 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2116 pindexNew->nTx = block.vtx.size();
2117 pindexNew->nChainTx = 0;
2118 pindexNew->nFile = pos.nFile;
2119 pindexNew->nDataPos = pos.nPos;
2120 pindexNew->nUndoPos = 0;
2121 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2122 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2124 LOCK(cs_nBlockSequenceId);
2125 pindexNew->nSequenceId = nBlockSequenceId++;
2128 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2129 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2130 deque<CBlockIndex*> queue;
2131 queue.push_back(pindexNew);
2133 // Recursively process any descendant blocks that now may be eligible to be connected.
2134 while (!queue.empty()) {
2135 CBlockIndex *pindex = queue.front();
2137 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2138 setBlockIndexCandidates.insert(pindex);
2139 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2140 while (range.first != range.second) {
2141 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2142 queue.push_back(it->second);
2144 mapBlocksUnlinked.erase(it);
2146 if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)))
2147 return state.Abort("Failed to write block index");
2150 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2151 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2153 if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
2154 return state.Abort("Failed to write block index");
2160 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2162 bool fUpdatedLast = false;
2164 LOCK(cs_LastBlockFile);
2167 if (nLastBlockFile != pos.nFile) {
2168 nLastBlockFile = pos.nFile;
2169 infoLastBlockFile.SetNull();
2170 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
2171 fUpdatedLast = true;
2174 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2175 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString());
2176 FlushBlockFile(true);
2178 infoLastBlockFile.SetNull();
2179 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2180 fUpdatedLast = true;
2182 pos.nFile = nLastBlockFile;
2183 pos.nPos = infoLastBlockFile.nSize;
2186 infoLastBlockFile.nSize += nAddSize;
2187 infoLastBlockFile.AddBlock(nHeight, nTime);
2190 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2191 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2192 if (nNewChunks > nOldChunks) {
2193 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2194 FILE *file = OpenBlockFile(pos);
2196 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2197 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2202 return state.Error("out of disk space");
2206 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2207 return state.Abort("Failed to write file info");
2209 pblocktree->WriteLastBlockFile(nLastBlockFile);
2214 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2218 LOCK(cs_LastBlockFile);
2220 unsigned int nNewSize;
2221 if (nFile == nLastBlockFile) {
2222 pos.nPos = infoLastBlockFile.nUndoSize;
2223 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2224 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2225 return state.Abort("Failed to write block info");
2227 CBlockFileInfo info;
2228 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2229 return state.Abort("Failed to read block info");
2230 pos.nPos = info.nUndoSize;
2231 nNewSize = (info.nUndoSize += nAddSize);
2232 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2233 return state.Abort("Failed to write block info");
2236 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2237 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2238 if (nNewChunks > nOldChunks) {
2239 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2240 FILE *file = OpenUndoFile(pos);
2242 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2243 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2248 return state.Error("out of disk space");
2254 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2256 // Check proof of work matches claimed amount
2257 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2258 return state.DoS(50, error("CheckBlockHeader() : proof of work failed"),
2259 REJECT_INVALID, "high-hash");
2262 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2263 return state.Invalid(error("CheckBlockHeader() : block timestamp too far in the future"),
2264 REJECT_INVALID, "time-too-new");
2269 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2271 // These are checks that are independent of context.
2273 if (!CheckBlockHeader(block, state, fCheckPOW))
2276 // Check the merkle root.
2277 if (fCheckMerkleRoot) {
2279 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2280 if (block.hashMerkleRoot != hashMerkleRoot2)
2281 return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
2282 REJECT_INVALID, "bad-txnmrklroot", true);
2284 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2285 // of transactions in a block without affecting the merkle root of a block,
2286 // while still invalidating it.
2288 return state.DoS(100, error("CheckBlock() : duplicate transaction"),
2289 REJECT_INVALID, "bad-txns-duplicate", true);
2292 // All potential-corruption validation must be done before we do any
2293 // transaction validation, as otherwise we may mark the header as invalid
2294 // because we receive the wrong transactions for it.
2297 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2298 return state.DoS(100, error("CheckBlock() : size limits failed"),
2299 REJECT_INVALID, "bad-blk-length");
2301 // First transaction must be coinbase, the rest must not be
2302 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2303 return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
2304 REJECT_INVALID, "bad-cb-missing");
2305 for (unsigned int i = 1; i < block.vtx.size(); i++)
2306 if (block.vtx[i].IsCoinBase())
2307 return state.DoS(100, error("CheckBlock() : more than one coinbase"),
2308 REJECT_INVALID, "bad-cb-multiple");
2310 // Check transactions
2311 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2312 if (!CheckTransaction(tx, state))
2313 return error("CheckBlock() : CheckTransaction failed");
2315 unsigned int nSigOps = 0;
2316 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2318 nSigOps += GetLegacySigOpCount(tx);
2320 if (nSigOps > MAX_BLOCK_SIGOPS)
2321 return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
2322 REJECT_INVALID, "bad-blk-sigops", true);
2327 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2329 AssertLockHeld(cs_main);
2330 // Check for duplicate
2331 uint256 hash = block.GetHash();
2332 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2333 CBlockIndex *pindex = NULL;
2334 if (miSelf != mapBlockIndex.end()) {
2335 // Block header is already known.
2336 pindex = miSelf->second;
2339 if (pindex->nStatus & BLOCK_FAILED_MASK)
2340 return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate");
2344 // Get prev block index
2345 CBlockIndex* pindexPrev = NULL;
2347 if (hash != Params().HashGenesisBlock()) {
2348 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2349 if (mi == mapBlockIndex.end())
2350 return state.DoS(10, error("%s : prev block not found", __func__), 0, "bad-prevblk");
2351 pindexPrev = (*mi).second;
2352 nHeight = pindexPrev->nHeight+1;
2354 // Check proof of work
2355 if ((!Params().SkipProofOfWorkCheck()) &&
2356 (block.nBits != GetNextWorkRequired(pindexPrev, &block)))
2357 return state.DoS(100, error("%s : incorrect proof of work", __func__),
2358 REJECT_INVALID, "bad-diffbits");
2360 // Check timestamp against prev
2361 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2362 return state.Invalid(error("%s : block's timestamp is too early", __func__),
2363 REJECT_INVALID, "time-too-old");
2365 // Check that the block chain matches the known block chain up to a checkpoint
2366 if (!Checkpoints::CheckBlock(nHeight, hash))
2367 return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
2368 REJECT_CHECKPOINT, "checkpoint mismatch");
2370 // Don't accept any forks from the main chain prior to last checkpoint
2371 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
2372 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2373 return state.DoS(100, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
2375 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2376 if (block.nVersion < 2 &&
2377 CBlockIndex::IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
2379 return state.Invalid(error("%s : rejected nVersion=1 block", __func__),
2380 REJECT_OBSOLETE, "bad-version");
2385 pindex = AddToBlockIndex(block);
2393 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2395 AssertLockHeld(cs_main);
2397 CBlockIndex *&pindex = *ppindex;
2399 if (!AcceptBlockHeader(block, state, &pindex))
2402 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2403 // TODO: deal better with duplicate blocks.
2404 // return state.DoS(20, error("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2408 if (!CheckBlock(block, state)) {
2409 if (state.IsInvalid() && !state.CorruptionPossible()) {
2410 pindex->nStatus |= BLOCK_FAILED_VALID;
2415 int nHeight = pindex->nHeight;
2417 // Check that all transactions are finalized
2418 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2419 if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2420 pindex->nStatus |= BLOCK_FAILED_VALID;
2421 return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"),
2422 REJECT_INVALID, "bad-txns-nonfinal");
2425 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2426 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2427 if (block.nVersion >= 2 &&
2428 CBlockIndex::IsSuperMajority(2, pindex->pprev, Params().EnforceBlockUpgradeMajority()))
2430 CScript expect = CScript() << nHeight;
2431 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2432 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2433 pindex->nStatus |= BLOCK_FAILED_VALID;
2434 return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"), REJECT_INVALID, "bad-cb-height");
2438 // Write block to history file
2440 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2441 CDiskBlockPos blockPos;
2444 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2445 return error("AcceptBlock() : FindBlockPos failed");
2447 if (!WriteBlockToDisk(block, blockPos))
2448 return state.Abort("Failed to write block");
2449 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2450 return error("AcceptBlock() : ReceivedBlockTransactions failed");
2451 } catch(std::runtime_error &e) {
2452 return state.Abort(std::string("System error: ") + e.what());
2458 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
2460 unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
2461 unsigned int nFound = 0;
2462 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2464 if (pstart->nVersion >= minVersion)
2466 pstart = pstart->pprev;
2468 return (nFound >= nRequired);
2471 /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
2472 int static inline InvertLowestOne(int n) { return n & (n - 1); }
2474 /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
2475 int static inline GetSkipHeight(int height) {
2479 // Determine which height to jump back to. Any number strictly lower than height is acceptable,
2480 // but the following expression seems to perform well in simulations (max 110 steps to go back
2481 // up to 2**18 blocks).
2482 return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
2485 CBlockIndex* CBlockIndex::GetAncestor(int height)
2487 if (height > nHeight || height < 0)
2490 CBlockIndex* pindexWalk = this;
2491 int heightWalk = nHeight;
2492 while (heightWalk > height) {
2493 int heightSkip = GetSkipHeight(heightWalk);
2494 int heightSkipPrev = GetSkipHeight(heightWalk - 1);
2495 if (heightSkip == height ||
2496 (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
2497 heightSkipPrev >= height))) {
2498 // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
2499 pindexWalk = pindexWalk->pskip;
2500 heightWalk = heightSkip;
2502 pindexWalk = pindexWalk->pprev;
2509 const CBlockIndex* CBlockIndex::GetAncestor(int height) const
2511 return const_cast<CBlockIndex*>(this)->GetAncestor(height);
2514 void CBlockIndex::BuildSkip()
2517 pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
2520 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2522 // Preliminary checks
2523 bool checked = CheckBlock(*pblock, state);
2527 MarkBlockAsReceived(pblock->GetHash());
2529 return error("ProcessBlock() : CheckBlock FAILED");
2533 CBlockIndex *pindex = NULL;
2534 bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2535 if (pindex && pfrom) {
2536 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2539 return error("ProcessBlock() : AcceptBlock FAILED");
2542 if (!ActivateBestChain(state, pblock))
2543 return error("ProcessBlock() : ActivateBestChain failed");
2555 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2557 header = block.GetBlockHeader();
2559 vector<bool> vMatch;
2560 vector<uint256> vHashes;
2562 vMatch.reserve(block.vtx.size());
2563 vHashes.reserve(block.vtx.size());
2565 for (unsigned int i = 0; i < block.vtx.size(); i++)
2567 const uint256& hash = block.vtx[i].GetHash();
2568 if (filter.IsRelevantAndUpdate(block.vtx[i]))
2570 vMatch.push_back(true);
2571 vMatchedTxn.push_back(make_pair(i, hash));
2574 vMatch.push_back(false);
2575 vHashes.push_back(hash);
2578 txn = CPartialMerkleTree(vHashes, vMatch);
2588 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2590 // hash at height 0 is the txids themself
2593 // calculate left hash
2594 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2595 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2596 if (pos*2+1 < CalcTreeWidth(height-1))
2597 right = CalcHash(height-1, pos*2+1, vTxid);
2600 // combine subhashes
2601 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2605 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2606 // determine whether this node is the parent of at least one matched txid
2607 bool fParentOfMatch = false;
2608 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2609 fParentOfMatch |= vMatch[p];
2610 // store as flag bit
2611 vBits.push_back(fParentOfMatch);
2612 if (height==0 || !fParentOfMatch) {
2613 // if at height 0, or nothing interesting below, store hash and stop
2614 vHash.push_back(CalcHash(height, pos, vTxid));
2616 // otherwise, don't store any hash, but descend into the subtrees
2617 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2618 if (pos*2+1 < CalcTreeWidth(height-1))
2619 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2623 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2624 if (nBitsUsed >= vBits.size()) {
2625 // overflowed the bits array - failure
2629 bool fParentOfMatch = vBits[nBitsUsed++];
2630 if (height==0 || !fParentOfMatch) {
2631 // if at height 0, or nothing interesting below, use stored hash and do not descend
2632 if (nHashUsed >= vHash.size()) {
2633 // overflowed the hash array - failure
2637 const uint256 &hash = vHash[nHashUsed++];
2638 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2639 vMatch.push_back(hash);
2642 // otherwise, descend into the subtrees to extract matched txids and hashes
2643 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2644 if (pos*2+1 < CalcTreeWidth(height-1))
2645 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2648 // and combine them before returning
2649 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2653 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2658 // calculate height of tree
2660 while (CalcTreeWidth(nHeight) > 1)
2663 // traverse the partial tree
2664 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2667 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2669 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2671 // An empty set will not work
2672 if (nTransactions == 0)
2674 // check for excessively high numbers of transactions
2675 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2677 // there can never be more hashes provided than one for every txid
2678 if (vHash.size() > nTransactions)
2680 // there must be at least one bit per node in the partial tree, and at least one node per hash
2681 if (vBits.size() < vHash.size())
2683 // calculate height of tree
2685 while (CalcTreeWidth(nHeight) > 1)
2687 // traverse the partial tree
2688 unsigned int nBitsUsed = 0, nHashUsed = 0;
2689 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2690 // verify that no problems occured during the tree traversal
2693 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2694 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2696 // verify that all hashes were consumed
2697 if (nHashUsed != vHash.size())
2699 return hashMerkleRoot;
2708 bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
2709 strMiscWarning = strMessage;
2710 LogPrintf("*** %s\n", strMessage);
2711 uiInterface.ThreadSafeMessageBox(
2712 userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
2713 "", CClientUIInterface::MSG_ERROR);
2718 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2720 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2722 // Check for nMinDiskSpace bytes (currently 50MB)
2723 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2724 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
2729 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2733 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
2734 boost::filesystem::create_directories(path.parent_path());
2735 FILE* file = fopen(path.string().c_str(), "rb+");
2736 if (!file && !fReadOnly)
2737 file = fopen(path.string().c_str(), "wb+");
2739 LogPrintf("Unable to open file %s\n", path.string());
2743 if (fseek(file, pos.nPos, SEEK_SET)) {
2744 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
2752 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2753 return OpenDiskFile(pos, "blk", fReadOnly);
2756 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2757 return OpenDiskFile(pos, "rev", fReadOnly);
2760 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
2762 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2765 CBlockIndex * InsertBlockIndex(uint256 hash)
2771 BlockMap::iterator mi = mapBlockIndex.find(hash);
2772 if (mi != mapBlockIndex.end())
2773 return (*mi).second;
2776 CBlockIndex* pindexNew = new CBlockIndex();
2778 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2779 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2780 pindexNew->phashBlock = &((*mi).first);
2785 bool static LoadBlockIndexDB()
2787 if (!pblocktree->LoadBlockIndexGuts())
2790 boost::this_thread::interruption_point();
2792 // Calculate nChainWork
2793 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2794 vSortedByHeight.reserve(mapBlockIndex.size());
2795 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2797 CBlockIndex* pindex = item.second;
2798 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2800 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2801 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2803 CBlockIndex* pindex = item.second;
2804 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork();
2805 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2806 if (pindex->pprev) {
2807 if (pindex->pprev->nChainTx) {
2808 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
2810 pindex->nChainTx = 0;
2811 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
2814 pindex->nChainTx = pindex->nTx;
2817 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
2818 setBlockIndexCandidates.insert(pindex);
2819 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
2820 pindexBestInvalid = pindex;
2822 pindex->BuildSkip();
2823 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
2824 pindexBestHeader = pindex;
2827 // Load block file info
2828 pblocktree->ReadLastBlockFile(nLastBlockFile);
2829 LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2830 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2831 LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString());
2833 // Check presence of blk files
2834 LogPrintf("Checking all blk files are present...\n");
2835 set<int> setBlkDataFiles;
2836 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2838 CBlockIndex* pindex = item.second;
2839 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2840 setBlkDataFiles.insert(pindex->nFile);
2843 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
2845 CDiskBlockPos pos(*it, 0);
2846 if (!CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION)) {
2851 // Check whether we need to continue reindexing
2852 bool fReindexing = false;
2853 pblocktree->ReadReindexing(fReindexing);
2854 fReindex |= fReindexing;
2856 // Check whether we have a transaction index
2857 pblocktree->ReadFlag("txindex", fTxIndex);
2858 LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2860 // Load pointer to end of best chain
2861 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
2862 if (it == mapBlockIndex.end())
2864 chainActive.SetTip(it->second);
2865 LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
2866 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
2867 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2868 Checkpoints::GuessVerificationProgress(chainActive.Tip()));
2873 CVerifyDB::CVerifyDB()
2875 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
2878 CVerifyDB::~CVerifyDB()
2880 uiInterface.ShowProgress("", 100);
2883 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
2886 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
2889 // Verify blocks in the best chain
2890 if (nCheckDepth <= 0)
2891 nCheckDepth = 1000000000; // suffices until the year 19000
2892 if (nCheckDepth > chainActive.Height())
2893 nCheckDepth = chainActive.Height();
2894 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2895 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2896 CCoinsViewCache coins(coinsview);
2897 CBlockIndex* pindexState = chainActive.Tip();
2898 CBlockIndex* pindexFailure = NULL;
2899 int nGoodTransactions = 0;
2900 CValidationState state;
2901 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2903 boost::this_thread::interruption_point();
2904 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
2905 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2908 // check level 0: read from disk
2909 if (!ReadBlockFromDisk(block, pindex))
2910 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2911 // check level 1: verify block validity
2912 if (nCheckLevel >= 1 && !CheckBlock(block, state))
2913 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2914 // check level 2: verify undo validity
2915 if (nCheckLevel >= 2 && pindex) {
2917 CDiskBlockPos pos = pindex->GetUndoPos();
2918 if (!pos.IsNull()) {
2919 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2920 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2923 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2924 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
2926 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
2927 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2928 pindexState = pindex->pprev;
2930 nGoodTransactions = 0;
2931 pindexFailure = pindex;
2933 nGoodTransactions += block.vtx.size();
2937 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
2939 // check level 4: try reconnecting blocks
2940 if (nCheckLevel >= 4) {
2941 CBlockIndex *pindex = pindexState;
2942 while (pindex != chainActive.Tip()) {
2943 boost::this_thread::interruption_point();
2944 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
2945 pindex = chainActive.Next(pindex);
2947 if (!ReadBlockFromDisk(block, pindex))
2948 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2949 if (!ConnectBlock(block, state, pindex, coins))
2950 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2954 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
2959 void UnloadBlockIndex()
2961 mapBlockIndex.clear();
2962 setBlockIndexCandidates.clear();
2963 chainActive.SetTip(NULL);
2964 pindexBestInvalid = NULL;
2967 bool LoadBlockIndex()
2969 // Load block index from databases
2970 if (!fReindex && !LoadBlockIndexDB())
2976 bool InitBlockIndex() {
2978 // Check whether we're already initialized
2979 if (chainActive.Genesis() != NULL)
2982 // Use the provided setting for -txindex in the new database
2983 fTxIndex = GetBoolArg("-txindex", false);
2984 pblocktree->WriteFlag("txindex", fTxIndex);
2985 LogPrintf("Initializing databases...\n");
2987 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2990 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
2991 // Start new block file
2992 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2993 CDiskBlockPos blockPos;
2994 CValidationState state;
2995 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
2996 return error("LoadBlockIndex() : FindBlockPos failed");
2997 if (!WriteBlockToDisk(block, blockPos))
2998 return error("LoadBlockIndex() : writing genesis block to disk failed");
2999 CBlockIndex *pindex = AddToBlockIndex(block);
3000 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3001 return error("LoadBlockIndex() : genesis block not accepted");
3002 if (!ActivateBestChain(state, &block))
3003 return error("LoadBlockIndex() : genesis block cannot be activated");
3004 } catch(std::runtime_error &e) {
3005 return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
3014 void PrintBlockTree()
3016 AssertLockHeld(cs_main);
3017 // pre-compute tree structure
3018 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
3019 for (BlockMap::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
3021 CBlockIndex* pindex = (*mi).second;
3022 mapNext[pindex->pprev].push_back(pindex);
3024 //while (rand() % 3 == 0)
3025 // mapNext[pindex->pprev].push_back(pindex);
3028 vector<pair<int, CBlockIndex*> > vStack;
3029 vStack.push_back(make_pair(0, chainActive.Genesis()));
3032 while (!vStack.empty())
3034 int nCol = vStack.back().first;
3035 CBlockIndex* pindex = vStack.back().second;
3038 // print split or gap
3039 if (nCol > nPrevCol)
3041 for (int i = 0; i < nCol-1; i++)
3045 else if (nCol < nPrevCol)
3047 for (int i = 0; i < nCol; i++)
3054 for (int i = 0; i < nCol; i++)
3059 ReadBlockFromDisk(block, pindex);
3060 LogPrintf("%d (blk%05u.dat:0x%x) %s tx %u\n",
3062 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
3063 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()),
3066 // put the main time-chain first
3067 vector<CBlockIndex*>& vNext = mapNext[pindex];
3068 for (unsigned int i = 0; i < vNext.size(); i++)
3070 if (chainActive.Next(vNext[i]))
3072 swap(vNext[0], vNext[i]);
3078 for (unsigned int i = 0; i < vNext.size(); i++)
3079 vStack.push_back(make_pair(nCol+i, vNext[i]));
3083 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3085 // Map of disk positions for blocks with unknown parent (only used for reindex)
3086 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3087 int64_t nStart = GetTimeMillis();
3091 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3092 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3093 uint64_t nRewind = blkdat.GetPos();
3094 while (!blkdat.eof()) {
3095 boost::this_thread::interruption_point();
3097 blkdat.SetPos(nRewind);
3098 nRewind++; // start one byte further next time, in case of failure
3099 blkdat.SetLimit(); // remove former limit
3100 unsigned int nSize = 0;
3103 unsigned char buf[MESSAGE_START_SIZE];
3104 blkdat.FindByte(Params().MessageStart()[0]);
3105 nRewind = blkdat.GetPos()+1;
3106 blkdat >> FLATDATA(buf);
3107 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3111 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3113 } catch (const std::exception &) {
3114 // no valid block header found; don't complain
3119 uint64_t nBlockPos = blkdat.GetPos();
3121 dbp->nPos = nBlockPos;
3122 blkdat.SetLimit(nBlockPos + nSize);
3123 blkdat.SetPos(nBlockPos);
3126 nRewind = blkdat.GetPos();
3128 // detect out of order blocks, and store them for later
3129 uint256 hash = block.GetHash();
3130 if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3131 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3132 block.hashPrevBlock.ToString());
3134 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3138 // process in case the block isn't known yet
3139 if (mapBlockIndex.count(hash) == 0) {
3140 CValidationState state;
3141 if (ProcessBlock(state, NULL, &block, dbp))
3143 if (state.IsError())
3147 // Recursively process earlier encountered successors of this block
3148 deque<uint256> queue;
3149 queue.push_back(hash);
3150 while (!queue.empty()) {
3151 uint256 head = queue.front();
3153 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3154 while (range.first != range.second) {
3155 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3156 if (ReadBlockFromDisk(block, it->second))
3158 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3160 CValidationState dummy;
3161 if (ProcessBlock(dummy, NULL, &block, &it->second))
3164 queue.push_back(block.GetHash());
3168 mapBlocksUnknownParent.erase(it);
3171 } catch (std::exception &e) {
3172 LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what());
3175 } catch(std::runtime_error &e) {
3176 AbortNode(std::string("System error: ") + e.what());
3179 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3183 //////////////////////////////////////////////////////////////////////////////
3188 string GetWarnings(string strFor)
3191 string strStatusBar;
3194 if (GetBoolArg("-testsafemode", false))
3197 if (!CLIENT_VERSION_IS_RELEASE)
3198 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3200 // Misc warnings like out of disk space and clock is wrong
3201 if (strMiscWarning != "")
3204 strStatusBar = strMiscWarning;
3207 if (fLargeWorkForkFound)
3210 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3212 else if (fLargeWorkInvalidChainFound)
3215 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.");
3221 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3223 const CAlert& alert = item.second;
3224 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3226 nPriority = alert.nPriority;
3227 strStatusBar = alert.strStatusBar;
3232 if (strFor == "statusbar")
3233 return strStatusBar;
3234 else if (strFor == "rpc")
3236 assert(!"GetWarnings() : invalid parameter");
3247 //////////////////////////////////////////////////////////////////////////////
3253 bool static AlreadyHave(const CInv& inv)
3259 bool txInMap = false;
3260 txInMap = mempool.exists(inv.hash);
3261 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3262 pcoinsTip->HaveCoins(inv.hash);
3265 return mapBlockIndex.count(inv.hash);
3267 // Don't know what it is, just say we already got one
3272 void static ProcessGetData(CNode* pfrom)
3274 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3276 vector<CInv> vNotFound;
3280 while (it != pfrom->vRecvGetData.end()) {
3281 // Don't bother if send buffer is too full to respond anyway
3282 if (pfrom->nSendSize >= SendBufferSize())
3285 const CInv &inv = *it;
3287 boost::this_thread::interruption_point();
3290 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3293 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3294 if (mi != mapBlockIndex.end())
3296 // If the requested block is at a height below our last
3297 // checkpoint, only serve it if it's in the checkpointed chain
3298 int nHeight = mi->second->nHeight;
3299 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
3300 if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3301 if (!chainActive.Contains(mi->second))
3303 LogPrintf("ProcessGetData(): ignoring request for old block that isn't in the main chain\n");
3313 // Send block from disk
3315 if (!ReadBlockFromDisk(block, (*mi).second))
3316 assert(!"cannot load block from disk");
3317 if (inv.type == MSG_BLOCK)
3318 pfrom->PushMessage("block", block);
3319 else // MSG_FILTERED_BLOCK)
3321 LOCK(pfrom->cs_filter);
3324 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3325 pfrom->PushMessage("merkleblock", merkleBlock);
3326 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3327 // This avoids hurting performance by pointlessly requiring a round-trip
3328 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3329 // they must either disconnect and retry or request the full block.
3330 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3331 // however we MUST always provide at least what the remote peer needs
3332 typedef std::pair<unsigned int, uint256> PairType;
3333 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3334 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3335 pfrom->PushMessage("tx", block.vtx[pair.first]);
3341 // Trigger them to send a getblocks request for the next batch of inventory
3342 if (inv.hash == pfrom->hashContinue)
3344 // Bypass PushInventory, this must send even if redundant,
3345 // and we want it right after the last block so they don't
3346 // wait for other stuff first.
3348 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3349 pfrom->PushMessage("inv", vInv);
3350 pfrom->hashContinue = 0;
3354 else if (inv.IsKnownType())
3356 // Send stream from relay memory
3357 bool pushed = false;
3360 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3361 if (mi != mapRelay.end()) {
3362 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3366 if (!pushed && inv.type == MSG_TX) {
3368 if (mempool.lookup(inv.hash, tx)) {
3369 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3372 pfrom->PushMessage("tx", ss);
3377 vNotFound.push_back(inv);
3381 // Track requests for our stuff.
3382 g_signals.Inventory(inv.hash);
3384 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3389 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3391 if (!vNotFound.empty()) {
3392 // Let the peer know that we didn't find what it asked for, so it doesn't
3393 // have to wait around forever. Currently only SPV clients actually care
3394 // about this message: it's needed when they are recursively walking the
3395 // dependencies of relevant unconfirmed transactions. SPV clients want to
3396 // do that because they want to know about (and store and rebroadcast and
3397 // risk analyze) the dependencies of transactions relevant to them, without
3398 // having to download the entire memory pool.
3399 pfrom->PushMessage("notfound", vNotFound);
3403 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3405 RandAddSeedPerfmon();
3406 LogPrint("net", "received: %s (%u bytes) peer=%d\n", strCommand, vRecv.size(), pfrom->id);
3407 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3409 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3416 if (strCommand == "version")
3418 // Each connection can only send one version message
3419 if (pfrom->nVersion != 0)
3421 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3422 Misbehaving(pfrom->GetId(), 1);
3429 uint64_t nNonce = 1;
3430 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3431 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3433 // disconnect from peers older than this proto version
3434 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3435 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3436 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3437 pfrom->fDisconnect = true;
3441 if (pfrom->nVersion == 10300)
3442 pfrom->nVersion = 300;
3444 vRecv >> addrFrom >> nNonce;
3445 if (!vRecv.empty()) {
3446 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3447 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3450 vRecv >> pfrom->nStartingHeight;
3452 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3454 pfrom->fRelayTxes = true;
3456 if (pfrom->fInbound && addrMe.IsRoutable())
3458 pfrom->addrLocal = addrMe;
3462 // Disconnect if we connected to ourself
3463 if (nNonce == nLocalHostNonce && nNonce > 1)
3465 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3466 pfrom->fDisconnect = true;
3470 // Be shy and don't send version until we hear
3471 if (pfrom->fInbound)
3472 pfrom->PushVersion();
3474 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3478 pfrom->PushMessage("verack");
3479 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3481 if (!pfrom->fInbound)
3483 // Advertise our address
3484 if (fListen && !IsInitialBlockDownload())
3486 CAddress addr = GetLocalAddress(&pfrom->addr);
3487 if (addr.IsRoutable())
3488 pfrom->PushAddress(addr);
3491 // Get recent addresses
3492 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3494 pfrom->PushMessage("getaddr");
3495 pfrom->fGetAddr = true;
3497 addrman.Good(pfrom->addr);
3499 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3501 addrman.Add(addrFrom, addrFrom);
3502 addrman.Good(addrFrom);
3509 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3510 item.second.RelayTo(pfrom);
3513 pfrom->fSuccessfullyConnected = true;
3517 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
3519 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
3520 pfrom->cleanSubVer, pfrom->nVersion,
3521 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
3524 AddTimeData(pfrom->addr, nTime);
3528 else if (pfrom->nVersion == 0)
3530 // Must have a version message before anything else
3531 Misbehaving(pfrom->GetId(), 1);
3536 else if (strCommand == "verack")
3538 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3542 else if (strCommand == "addr")
3544 vector<CAddress> vAddr;
3547 // Don't want addr from older versions unless seeding
3548 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3550 if (vAddr.size() > 1000)
3552 Misbehaving(pfrom->GetId(), 20);
3553 return error("message addr size() = %u", vAddr.size());
3556 // Store the new addresses
3557 vector<CAddress> vAddrOk;
3558 int64_t nNow = GetAdjustedTime();
3559 int64_t nSince = nNow - 10 * 60;
3560 BOOST_FOREACH(CAddress& addr, vAddr)
3562 boost::this_thread::interruption_point();
3564 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3565 addr.nTime = nNow - 5 * 24 * 60 * 60;
3566 pfrom->AddAddressKnown(addr);
3567 bool fReachable = IsReachable(addr);
3568 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3570 // Relay to a limited number of other nodes
3573 // Use deterministic randomness to send to the same nodes for 24 hours
3574 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3575 static uint256 hashSalt;
3577 hashSalt = GetRandHash();
3578 uint64_t hashAddr = addr.GetHash();
3579 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3580 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3581 multimap<uint256, CNode*> mapMix;
3582 BOOST_FOREACH(CNode* pnode, vNodes)
3584 if (pnode->nVersion < CADDR_TIME_VERSION)
3586 unsigned int nPointer;
3587 memcpy(&nPointer, &pnode, sizeof(nPointer));
3588 uint256 hashKey = hashRand ^ nPointer;
3589 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3590 mapMix.insert(make_pair(hashKey, pnode));
3592 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3593 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3594 ((*mi).second)->PushAddress(addr);
3597 // Do not store addresses outside our network
3599 vAddrOk.push_back(addr);
3601 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3602 if (vAddr.size() < 1000)
3603 pfrom->fGetAddr = false;
3604 if (pfrom->fOneShot)
3605 pfrom->fDisconnect = true;
3609 else if (strCommand == "inv")
3613 if (vInv.size() > MAX_INV_SZ)
3615 Misbehaving(pfrom->GetId(), 20);
3616 return error("message inv size() = %u", vInv.size());
3621 std::vector<CInv> vToFetch;
3623 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3625 const CInv &inv = vInv[nInv];
3627 boost::this_thread::interruption_point();
3628 pfrom->AddInventoryKnown(inv);
3630 bool fAlreadyHave = AlreadyHave(inv);
3631 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
3633 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
3636 if (inv.type == MSG_BLOCK) {
3637 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
3638 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
3639 // First request the headers preceeding the announced block. In the normal fully-synced
3640 // case where a new block is announced that succeeds the current tip (no reorganization),
3641 // there are no such headers.
3642 // Secondly, and only when we are close to being synced, we request the announced block directly,
3643 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
3644 // time the block arrives, the header chain leading up to it is already validated. Not
3645 // doing this will result in the received block being rejected as an orphan in case it is
3646 // not a direct successor.
3647 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
3648 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - Params().TargetSpacing() * 20) {
3649 vToFetch.push_back(inv);
3650 // Mark block as in flight already, even though the actual "getdata" message only goes out
3651 // later (within the same cs_main lock, though).
3652 MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
3654 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
3658 // Track requests for our stuff
3659 g_signals.Inventory(inv.hash);
3661 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
3662 Misbehaving(pfrom->GetId(), 50);
3663 return error("send buffer size() = %u", pfrom->nSendSize);
3667 if (!vToFetch.empty())
3668 pfrom->PushMessage("getdata", vToFetch);
3672 else if (strCommand == "getdata")
3676 if (vInv.size() > MAX_INV_SZ)
3678 Misbehaving(pfrom->GetId(), 20);
3679 return error("message getdata size() = %u", vInv.size());
3682 if (fDebug || (vInv.size() != 1))
3683 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
3685 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
3686 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
3688 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3689 ProcessGetData(pfrom);
3693 else if (strCommand == "getblocks")
3695 CBlockLocator locator;
3697 vRecv >> locator >> hashStop;
3701 // Find the last block the caller has in the main chain
3702 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
3704 // Send the rest of the chain
3706 pindex = chainActive.Next(pindex);
3708 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop==uint256(0) ? "end" : hashStop.ToString(), nLimit, pfrom->id);
3709 for (; pindex; pindex = chainActive.Next(pindex))
3711 if (pindex->GetBlockHash() == hashStop)
3713 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3716 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3719 // When this block is requested, we'll send an inv that'll make them
3720 // getblocks the next batch of inventory.
3721 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3722 pfrom->hashContinue = pindex->GetBlockHash();
3729 else if (strCommand == "getheaders")
3731 CBlockLocator locator;
3733 vRecv >> locator >> hashStop;
3737 CBlockIndex* pindex = NULL;
3738 if (locator.IsNull())
3740 // If locator is null, return the hashStop block
3741 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
3742 if (mi == mapBlockIndex.end())
3744 pindex = (*mi).second;
3748 // Find the last block the caller has in the main chain
3749 pindex = FindForkInGlobalIndex(chainActive, locator);
3751 pindex = chainActive.Next(pindex);
3754 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3755 vector<CBlock> vHeaders;
3756 int nLimit = MAX_HEADERS_RESULTS;
3757 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
3758 for (; pindex; pindex = chainActive.Next(pindex))
3760 vHeaders.push_back(pindex->GetBlockHeader());
3761 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3764 pfrom->PushMessage("headers", vHeaders);
3768 else if (strCommand == "tx")
3770 vector<uint256> vWorkQueue;
3771 vector<uint256> vEraseQueue;
3775 CInv inv(MSG_TX, tx.GetHash());
3776 pfrom->AddInventoryKnown(inv);
3780 bool fMissingInputs = false;
3781 CValidationState state;
3783 mapAlreadyAskedFor.erase(inv);
3785 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
3787 mempool.check(pcoinsTip);
3788 RelayTransaction(tx);
3789 vWorkQueue.push_back(inv.hash);
3790 vEraseQueue.push_back(inv.hash);
3792 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n",
3793 pfrom->id, pfrom->cleanSubVer,
3794 tx.GetHash().ToString(),
3795 mempool.mapTx.size());
3797 // Recursively process any orphan transactions that depended on this one
3798 set<NodeId> setMisbehaving;
3799 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3801 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3802 if (itByPrev == mapOrphanTransactionsByPrev.end())
3804 for (set<uint256>::iterator mi = itByPrev->second.begin();
3805 mi != itByPrev->second.end();
3808 const uint256& orphanHash = *mi;
3809 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3810 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3811 bool fMissingInputs2 = false;
3812 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3813 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3814 // anyone relaying LegitTxX banned)
3815 CValidationState stateDummy;
3817 vEraseQueue.push_back(orphanHash);
3819 if (setMisbehaving.count(fromPeer))
3821 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
3823 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
3824 RelayTransaction(orphanTx);
3825 vWorkQueue.push_back(orphanHash);
3827 else if (!fMissingInputs2)
3830 if (stateDummy.IsInvalid(nDos) && nDos > 0)
3832 // Punish peer that gave us an invalid orphan tx
3833 Misbehaving(fromPeer, nDos);
3834 setMisbehaving.insert(fromPeer);
3835 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
3837 // too-little-fee orphan
3838 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
3840 mempool.check(pcoinsTip);
3844 BOOST_FOREACH(uint256 hash, vEraseQueue)
3845 EraseOrphanTx(hash);
3847 else if (fMissingInputs)
3849 AddOrphanTx(tx, pfrom->GetId());
3851 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3852 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3853 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
3855 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3856 } else if (pfrom->fWhitelisted) {
3857 // Always relay transactions received from whitelisted peers, even
3858 // if they are already in the mempool (allowing the node to function
3859 // as a gateway for nodes hidden behind it).
3860 RelayTransaction(tx);
3863 if (state.IsInvalid(nDoS))
3865 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3866 pfrom->id, pfrom->cleanSubVer,
3867 state.GetRejectReason());
3868 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3869 state.GetRejectReason(), inv.hash);
3871 Misbehaving(pfrom->GetId(), nDoS);
3876 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
3878 std::vector<CBlockHeader> headers;
3880 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3881 unsigned int nCount = ReadCompactSize(vRecv);
3882 if (nCount > MAX_HEADERS_RESULTS) {
3883 Misbehaving(pfrom->GetId(), 20);
3884 return error("headers message size = %u", nCount);
3886 headers.resize(nCount);
3887 for (unsigned int n = 0; n < nCount; n++) {
3888 vRecv >> headers[n];
3889 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
3895 // Nothing interesting. Stop asking this peers for more headers.
3899 CBlockIndex *pindexLast = NULL;
3900 BOOST_FOREACH(const CBlockHeader& header, headers) {
3901 CValidationState state;
3902 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
3903 Misbehaving(pfrom->GetId(), 20);
3904 return error("non-continuous headers sequence");
3906 if (!AcceptBlockHeader(header, state, &pindexLast)) {
3908 if (state.IsInvalid(nDoS)) {
3910 Misbehaving(pfrom->GetId(), nDoS);
3911 return error("invalid header received");
3917 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
3919 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
3920 // Headers message had its maximum size; the peer may have more headers.
3921 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
3922 // from there instead.
3923 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
3924 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256(0));
3928 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3933 CInv inv(MSG_BLOCK, block.GetHash());
3934 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
3936 pfrom->AddInventoryKnown(inv);
3938 CValidationState state;
3939 ProcessBlock(state, pfrom, &block);
3941 if (state.IsInvalid(nDoS)) {
3942 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3943 state.GetRejectReason(), inv.hash);
3946 Misbehaving(pfrom->GetId(), nDoS);
3953 else if (strCommand == "getaddr")
3955 pfrom->vAddrToSend.clear();
3956 vector<CAddress> vAddr = addrman.GetAddr();
3957 BOOST_FOREACH(const CAddress &addr, vAddr)
3958 pfrom->PushAddress(addr);
3962 else if (strCommand == "mempool")
3964 LOCK2(cs_main, pfrom->cs_filter);
3966 std::vector<uint256> vtxid;
3967 mempool.queryHashes(vtxid);
3969 BOOST_FOREACH(uint256& hash, vtxid) {
3970 CInv inv(MSG_TX, hash);
3972 bool fInMemPool = mempool.lookup(hash, tx);
3973 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
3974 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
3976 vInv.push_back(inv);
3977 if (vInv.size() == MAX_INV_SZ) {
3978 pfrom->PushMessage("inv", vInv);
3982 if (vInv.size() > 0)
3983 pfrom->PushMessage("inv", vInv);
3987 else if (strCommand == "ping")
3989 if (pfrom->nVersion > BIP0031_VERSION)
3993 // Echo the message back with the nonce. This allows for two useful features:
3995 // 1) A remote node can quickly check if the connection is operational
3996 // 2) Remote nodes can measure the latency of the network thread. If this node
3997 // is overloaded it won't respond to pings quickly and the remote node can
3998 // avoid sending us more work, like chain download requests.
4000 // The nonce stops the remote getting confused between different pings: without
4001 // it, if the remote node sends a ping once per second and this node takes 5
4002 // seconds to respond to each, the 5th ping the remote sends would appear to
4003 // return very quickly.
4004 pfrom->PushMessage("pong", nonce);
4009 else if (strCommand == "pong")
4011 int64_t pingUsecEnd = nTimeReceived;
4013 size_t nAvail = vRecv.in_avail();
4014 bool bPingFinished = false;
4015 std::string sProblem;
4017 if (nAvail >= sizeof(nonce)) {
4020 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4021 if (pfrom->nPingNonceSent != 0) {
4022 if (nonce == pfrom->nPingNonceSent) {
4023 // Matching pong received, this ping is no longer outstanding
4024 bPingFinished = true;
4025 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4026 if (pingUsecTime > 0) {
4027 // Successful ping time measurement, replace previous
4028 pfrom->nPingUsecTime = pingUsecTime;
4030 // This should never happen
4031 sProblem = "Timing mishap";
4034 // Nonce mismatches are normal when pings are overlapping
4035 sProblem = "Nonce mismatch";
4037 // This is most likely a bug in another implementation somewhere, cancel this ping
4038 bPingFinished = true;
4039 sProblem = "Nonce zero";
4043 sProblem = "Unsolicited pong without ping";
4046 // This is most likely a bug in another implementation somewhere, cancel this ping
4047 bPingFinished = true;
4048 sProblem = "Short payload";
4051 if (!(sProblem.empty())) {
4052 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4056 pfrom->nPingNonceSent,
4060 if (bPingFinished) {
4061 pfrom->nPingNonceSent = 0;
4066 else if (strCommand == "alert")
4071 uint256 alertHash = alert.GetHash();
4072 if (pfrom->setKnown.count(alertHash) == 0)
4074 if (alert.ProcessAlert())
4077 pfrom->setKnown.insert(alertHash);
4080 BOOST_FOREACH(CNode* pnode, vNodes)
4081 alert.RelayTo(pnode);
4085 // Small DoS penalty so peers that send us lots of
4086 // duplicate/expired/invalid-signature/whatever alerts
4087 // eventually get banned.
4088 // This isn't a Misbehaving(100) (immediate ban) because the
4089 // peer might be an older or different implementation with
4090 // a different signature key, etc.
4091 Misbehaving(pfrom->GetId(), 10);
4097 else if (strCommand == "filterload")
4099 CBloomFilter filter;
4102 if (!filter.IsWithinSizeConstraints())
4103 // There is no excuse for sending a too-large filter
4104 Misbehaving(pfrom->GetId(), 100);
4107 LOCK(pfrom->cs_filter);
4108 delete pfrom->pfilter;
4109 pfrom->pfilter = new CBloomFilter(filter);
4110 pfrom->pfilter->UpdateEmptyFull();
4112 pfrom->fRelayTxes = true;
4116 else if (strCommand == "filteradd")
4118 vector<unsigned char> vData;
4121 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4122 // and thus, the maximum size any matched object can have) in a filteradd message
4123 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4125 Misbehaving(pfrom->GetId(), 100);
4127 LOCK(pfrom->cs_filter);
4129 pfrom->pfilter->insert(vData);
4131 Misbehaving(pfrom->GetId(), 100);
4136 else if (strCommand == "filterclear")
4138 LOCK(pfrom->cs_filter);
4139 delete pfrom->pfilter;
4140 pfrom->pfilter = new CBloomFilter();
4141 pfrom->fRelayTxes = true;
4145 else if (strCommand == "reject")
4149 string strMsg; unsigned char ccode; string strReason;
4150 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, 111);
4153 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4155 if (strMsg == "block" || strMsg == "tx")
4159 ss << ": hash " << hash.ToString();
4161 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4162 } catch (std::ios_base::failure& e) {
4163 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4164 LogPrint("net", "Unparseable reject message received\n");
4171 // Ignore unknown commands for extensibility
4172 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4176 // Update the last seen time for this node's address
4177 if (pfrom->fNetworkNode)
4178 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
4179 AddressCurrentlyConnected(pfrom->addr);
4185 // requires LOCK(cs_vRecvMsg)
4186 bool ProcessMessages(CNode* pfrom)
4189 // LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
4193 // (4) message start
4201 if (!pfrom->vRecvGetData.empty())
4202 ProcessGetData(pfrom);
4204 // this maintains the order of responses
4205 if (!pfrom->vRecvGetData.empty()) return fOk;
4207 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4208 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4209 // Don't bother if send buffer is too full to respond anyway
4210 if (pfrom->nSendSize >= SendBufferSize())
4214 CNetMessage& msg = *it;
4217 // LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
4218 // msg.hdr.nMessageSize, msg.vRecv.size(),
4219 // msg.complete() ? "Y" : "N");
4221 // end, if an incomplete message is found
4222 if (!msg.complete())
4225 // at this point, any failure means we can delete the current message
4228 // Scan for message start
4229 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4230 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", msg.hdr.GetCommand(), pfrom->id);
4236 CMessageHeader& hdr = msg.hdr;
4239 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", hdr.GetCommand(), pfrom->id);
4242 string strCommand = hdr.GetCommand();
4245 unsigned int nMessageSize = hdr.nMessageSize;
4248 CDataStream& vRecv = msg.vRecv;
4249 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4250 unsigned int nChecksum = 0;
4251 memcpy(&nChecksum, &hash, sizeof(nChecksum));
4252 if (nChecksum != hdr.nChecksum)
4254 LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4255 strCommand, nMessageSize, nChecksum, hdr.nChecksum);
4263 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4264 boost::this_thread::interruption_point();
4266 catch (std::ios_base::failure& e)
4268 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4269 if (strstr(e.what(), "end of data"))
4271 // Allow exceptions from under-length message on vRecv
4272 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
4274 else if (strstr(e.what(), "size too large"))
4276 // Allow exceptions from over-long size
4277 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
4281 PrintExceptionContinue(&e, "ProcessMessages()");
4284 catch (boost::thread_interrupted) {
4287 catch (std::exception& e) {
4288 PrintExceptionContinue(&e, "ProcessMessages()");
4290 PrintExceptionContinue(NULL, "ProcessMessages()");
4294 LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", strCommand, nMessageSize, pfrom->id);
4299 // In case the connection got shut down, its receive buffer was wiped
4300 if (!pfrom->fDisconnect)
4301 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4307 bool SendMessages(CNode* pto, bool fSendTrickle)
4310 // Don't send anything until we get their version message
4311 if (pto->nVersion == 0)
4317 bool pingSend = false;
4318 if (pto->fPingQueued) {
4319 // RPC ping request by user
4322 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4323 // Ping automatically sent as a latency probe & keepalive.
4328 while (nonce == 0) {
4329 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4331 pto->fPingQueued = false;
4332 pto->nPingUsecStart = GetTimeMicros();
4333 if (pto->nVersion > BIP0031_VERSION) {
4334 pto->nPingNonceSent = nonce;
4335 pto->PushMessage("ping", nonce);
4337 // Peer is too old to support ping command with nonce, pong will never arrive.
4338 pto->nPingNonceSent = 0;
4339 pto->PushMessage("ping");
4343 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4347 // Address refresh broadcast
4348 static int64_t nLastRebroadcast;
4349 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4353 BOOST_FOREACH(CNode* pnode, vNodes)
4355 // Periodically clear setAddrKnown to allow refresh broadcasts
4356 if (nLastRebroadcast)
4357 pnode->setAddrKnown.clear();
4359 // Rebroadcast our address
4362 CAddress addr = GetLocalAddress(&pnode->addr);
4363 if (addr.IsRoutable())
4364 pnode->PushAddress(addr);
4368 nLastRebroadcast = GetTime();
4376 vector<CAddress> vAddr;
4377 vAddr.reserve(pto->vAddrToSend.size());
4378 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4380 // returns true if wasn't already contained in the set
4381 if (pto->setAddrKnown.insert(addr).second)
4383 vAddr.push_back(addr);
4384 // receiver rejects addr messages larger than 1000
4385 if (vAddr.size() >= 1000)
4387 pto->PushMessage("addr", vAddr);
4392 pto->vAddrToSend.clear();
4394 pto->PushMessage("addr", vAddr);
4397 CNodeState &state = *State(pto->GetId());
4398 if (state.fShouldBan) {
4399 if (pto->fWhitelisted)
4400 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4402 pto->fDisconnect = true;
4403 if (pto->addr.IsLocal())
4404 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4407 CNode::Ban(pto->addr);
4410 state.fShouldBan = false;
4413 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4414 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4415 state.rejects.clear();
4418 if (pindexBestHeader == NULL)
4419 pindexBestHeader = chainActive.Tip();
4420 bool fFetch = !pto->fInbound || (pindexBestHeader && (state.pindexLastCommonBlock ? state.pindexLastCommonBlock->nHeight : 0) + 144 > pindexBestHeader->nHeight);
4421 if (!state.fSyncStarted && !pto->fClient && fFetch && !fImporting && !fReindex) {
4422 // Only actively request headers from a single peer, unless we're close to today.
4423 if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4424 state.fSyncStarted = true;
4426 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4427 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4428 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256(0));
4432 // Resend wallet transactions that haven't gotten in a block yet
4433 // Except during reindex, importing and IBD, when old wallet
4434 // transactions become unconfirmed and spams other nodes.
4435 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4437 g_signals.Broadcast();
4441 // Message: inventory
4444 vector<CInv> vInvWait;
4446 LOCK(pto->cs_inventory);
4447 vInv.reserve(pto->vInventoryToSend.size());
4448 vInvWait.reserve(pto->vInventoryToSend.size());
4449 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4451 if (pto->setInventoryKnown.count(inv))
4454 // trickle out tx inv to protect privacy
4455 if (inv.type == MSG_TX && !fSendTrickle)
4457 // 1/4 of tx invs blast to all immediately
4458 static uint256 hashSalt;
4460 hashSalt = GetRandHash();
4461 uint256 hashRand = inv.hash ^ hashSalt;
4462 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4463 bool fTrickleWait = ((hashRand & 3) != 0);
4467 vInvWait.push_back(inv);
4472 // returns true if wasn't already contained in the set
4473 if (pto->setInventoryKnown.insert(inv).second)
4475 vInv.push_back(inv);
4476 if (vInv.size() >= 1000)
4478 pto->PushMessage("inv", vInv);
4483 pto->vInventoryToSend = vInvWait;
4486 pto->PushMessage("inv", vInv);
4488 // Detect whether we're stalling
4489 int64_t nNow = GetTimeMicros();
4490 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4491 // Stalling only triggers when the block download window cannot move. During normal steady state,
4492 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4493 // should only happen during initial block download.
4494 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
4495 pto->fDisconnect = true;
4499 // Message: getdata (blocks)
4501 vector<CInv> vGetData;
4502 if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4503 vector<CBlockIndex*> vToDownload;
4504 NodeId staller = -1;
4505 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4506 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
4507 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4508 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
4509 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4510 pindex->nHeight, pto->id);
4512 if (state.nBlocksInFlight == 0 && staller != -1) {
4513 if (State(staller)->nStallingSince == 0) {
4514 State(staller)->nStallingSince = nNow;
4515 LogPrint("net", "Stall started peer=%d\n", staller);
4521 // Message: getdata (non-blocks)
4523 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4525 const CInv& inv = (*pto->mapAskFor.begin()).second;
4526 if (!AlreadyHave(inv))
4529 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
4530 vGetData.push_back(inv);
4531 if (vGetData.size() >= 1000)
4533 pto->PushMessage("getdata", vGetData);
4537 pto->mapAskFor.erase(pto->mapAskFor.begin());
4539 if (!vGetData.empty())
4540 pto->PushMessage("getdata", vGetData);
4547 bool CBlockUndo::WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
4549 // Open history file to append
4550 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
4552 return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
4554 // Write index header
4555 unsigned int nSize = fileout.GetSerializeSize(*this);
4556 fileout << FLATDATA(Params().MessageStart()) << nSize;
4559 long fileOutPos = ftell(fileout);
4561 return error("CBlockUndo::WriteToDisk : ftell failed");
4562 pos.nPos = (unsigned int)fileOutPos;
4565 // calculate & write checksum
4566 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
4567 hasher << hashBlock;
4569 fileout << hasher.GetHash();
4571 // Flush stdio buffers and commit to disk before returning
4573 if (!IsInitialBlockDownload())
4574 FileCommit(fileout);
4579 bool CBlockUndo::ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
4581 // Open history file to read
4582 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
4584 return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
4587 uint256 hashChecksum;
4590 filein >> hashChecksum;
4592 catch (std::exception &e) {
4593 return error("%s : Deserialize or I/O error - %s", __func__, e.what());
4597 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
4598 hasher << hashBlock;
4600 if (hashChecksum != hasher.GetHash())
4601 return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
4606 std::string CBlockFileInfo::ToString() const {
4607 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));
4618 BlockMap::iterator it1 = mapBlockIndex.begin();
4619 for (; it1 != mapBlockIndex.end(); it1++)
4620 delete (*it1).second;
4621 mapBlockIndex.clear();
4623 // orphan transactions
4624 mapOrphanTransactions.clear();
4625 mapOrphanTransactionsByPrev.clear();
4627 } instance_of_cmaincleanup;