]> Git Repo - VerusCoin.git/blob - src/main.cpp
Merge pull request #5890
[VerusCoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "main.h"
7
8 #include "arith_uint256.h"
9 #include "addrman.h"
10 #include "alert.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "init.h"
15 #include "merkleblock.h"
16 #include "net.h"
17 #include "pow.h"
18 #include "txdb.h"
19 #include "txmempool.h"
20 #include "ui_interface.h"
21 #include "undo.h"
22 #include "util.h"
23 #include "utilmoneystr.h"
24
25 #include <sstream>
26
27 #include <boost/algorithm/string/replace.hpp>
28 #include <boost/filesystem.hpp>
29 #include <boost/filesystem/fstream.hpp>
30 #include <boost/thread.hpp>
31
32 using namespace std;
33
34 #if defined(NDEBUG)
35 # error "Bitcoin cannot be compiled without assertions."
36 #endif
37
38 /**
39  * Global state
40  */
41
42 CCriticalSection cs_main;
43
44 BlockMap mapBlockIndex;
45 CChain chainActive;
46 CBlockIndex *pindexBestHeader = NULL;
47 int64_t nTimeBestReceived = 0;
48 CWaitableCriticalSection csBestBlock;
49 CConditionVariable cvBlockChange;
50 int nScriptCheckThreads = 0;
51 bool fImporting = false;
52 bool fReindex = false;
53 bool fTxIndex = false;
54 bool fIsBareMultisigStd = true;
55 unsigned int nCoinCacheSize = 5000;
56
57 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
58 CFeeRate minRelayTxFee = CFeeRate(1000);
59
60 CTxMemPool mempool(::minRelayTxFee);
61
62 struct COrphanTx {
63     CTransaction tx;
64     NodeId fromPeer;
65 };
66 map<uint256, COrphanTx> mapOrphanTransactions;
67 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
68 void EraseOrphansFor(NodeId peer);
69
70 /**
71  * Returns true if there are nRequired or more blocks of minVersion or above
72  * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart 
73  * and going backwards.
74  */
75 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
76
77 /** Constant stuff for coinbase transactions we create: */
78 CScript COINBASE_FLAGS;
79
80 const string strMessageMagic = "Bitcoin Signed Message:\n";
81
82 // Internal stuff
83 namespace {
84
85     struct CBlockIndexWorkComparator
86     {
87         bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
88             // First sort by most total work, ...
89             if (pa->nChainWork > pb->nChainWork) return false;
90             if (pa->nChainWork < pb->nChainWork) return true;
91
92             // ... then by earliest time received, ...
93             if (pa->nSequenceId < pb->nSequenceId) return false;
94             if (pa->nSequenceId > pb->nSequenceId) return true;
95
96             // Use pointer address as tie breaker (should only happen with blocks
97             // loaded from disk, as those all have id 0).
98             if (pa < pb) return false;
99             if (pa > pb) return true;
100
101             // Identical blocks.
102             return false;
103         }
104     };
105
106     CBlockIndex *pindexBestInvalid;
107
108     /**
109      * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS or better that are at least
110      * as good as our current tip. Entries may be failed, though.
111      */
112     set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
113     /** Number of nodes with fSyncStarted. */
114     int nSyncStarted = 0;
115     /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
116     multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
117
118     CCriticalSection cs_LastBlockFile;
119     std::vector<CBlockFileInfo> vinfoBlockFile;
120     int nLastBlockFile = 0;
121
122     /**
123      * Every received block is assigned a unique and increasing identifier, so we
124      * know which one to give priority in case of a fork.
125      */
126     CCriticalSection cs_nBlockSequenceId;
127     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
128     uint32_t nBlockSequenceId = 1;
129
130     /**
131      * Sources of received blocks, to be able to send them reject messages or ban
132      * them, if processing happens afterwards. Protected by cs_main.
133      */
134     map<uint256, NodeId> mapBlockSource;
135
136     /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
137     struct QueuedBlock {
138         uint256 hash;
139         CBlockIndex *pindex;  //! Optional.
140         int64_t nTime;  //! Time of "getdata" request in microseconds.
141         int nValidatedQueuedBefore;  //! Number of blocks queued with validated headers (globally) at the time this one is requested.
142         bool fValidatedHeaders;  //! Whether this block has validated headers at the time of request.
143     };
144     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
145
146     /** Number of blocks in flight with validated headers. */
147     int nQueuedValidatedHeaders = 0;
148
149     /** Number of preferable block download peers. */
150     int nPreferredDownload = 0;
151
152     /** Dirty block index entries. */
153     set<CBlockIndex*> setDirtyBlockIndex;
154
155     /** Dirty block file entries. */
156     set<int> setDirtyFileInfo;
157 } // anon namespace
158
159 //////////////////////////////////////////////////////////////////////////////
160 //
161 // dispatching functions
162 //
163
164 // These functions dispatch to one or all registered wallets
165
166 namespace {
167
168 struct CMainSignals {
169     /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
170     boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
171     /** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
172     boost::signals2::signal<void (const uint256 &)> EraseTransaction;
173     /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
174     boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
175     /** Notifies listeners of a new active block chain. */
176     boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
177     /** Notifies listeners about an inventory item being seen on the network. */
178     boost::signals2::signal<void (const uint256 &)> Inventory;
179     /** Tells listeners to broadcast their data. */
180     boost::signals2::signal<void ()> Broadcast;
181     /** Notifies listeners of a block validation result */
182     boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
183 } g_signals;
184
185 } // anon namespace
186
187 void RegisterValidationInterface(CValidationInterface* pwalletIn) {
188     g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
189     g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
190     g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
191     g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
192     g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
193     g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
194     g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
195 }
196
197 void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
198     g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
199     g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
200     g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
201     g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
202     g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
203     g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
204     g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
205 }
206
207 void UnregisterAllValidationInterfaces() {
208     g_signals.BlockChecked.disconnect_all_slots();
209     g_signals.Broadcast.disconnect_all_slots();
210     g_signals.Inventory.disconnect_all_slots();
211     g_signals.SetBestChain.disconnect_all_slots();
212     g_signals.UpdatedTransaction.disconnect_all_slots();
213     g_signals.EraseTransaction.disconnect_all_slots();
214     g_signals.SyncTransaction.disconnect_all_slots();
215 }
216
217 void SyncWithWallets(const CTransaction &tx, const CBlock *pblock) {
218     g_signals.SyncTransaction(tx, pblock);
219 }
220
221 //////////////////////////////////////////////////////////////////////////////
222 //
223 // Registration of network node signals.
224 //
225
226 namespace {
227
228 struct CBlockReject {
229     unsigned char chRejectCode;
230     string strRejectReason;
231     uint256 hashBlock;
232 };
233
234 /**
235  * Maintain validation-specific state about nodes, protected by cs_main, instead
236  * by CNode's own locks. This simplifies asynchronous operation, where
237  * processing of incoming data is done after the ProcessMessage call returns,
238  * and we're no longer holding the node's locks.
239  */
240 struct CNodeState {
241     //! The peer's address
242     CService address;
243     //! Whether we have a fully established connection.
244     bool fCurrentlyConnected;
245     //! Accumulated misbehaviour score for this peer.
246     int nMisbehavior;
247     //! Whether this peer should be disconnected and banned (unless whitelisted).
248     bool fShouldBan;
249     //! String name of this peer (debugging/logging purposes).
250     std::string name;
251     //! List of asynchronously-determined block rejections to notify this peer about.
252     std::vector<CBlockReject> rejects;
253     //! The best known block we know this peer has announced.
254     CBlockIndex *pindexBestKnownBlock;
255     //! The hash of the last unknown block this peer has announced.
256     uint256 hashLastUnknownBlock;
257     //! The last full block we both have.
258     CBlockIndex *pindexLastCommonBlock;
259     //! Whether we've started headers synchronization with this peer.
260     bool fSyncStarted;
261     //! Since when we're stalling block download progress (in microseconds), or 0.
262     int64_t nStallingSince;
263     list<QueuedBlock> vBlocksInFlight;
264     int nBlocksInFlight;
265     //! Whether we consider this a preferred download peer.
266     bool fPreferredDownload;
267
268     CNodeState() {
269         fCurrentlyConnected = false;
270         nMisbehavior = 0;
271         fShouldBan = false;
272         pindexBestKnownBlock = NULL;
273         hashLastUnknownBlock.SetNull();
274         pindexLastCommonBlock = NULL;
275         fSyncStarted = false;
276         nStallingSince = 0;
277         nBlocksInFlight = 0;
278         fPreferredDownload = false;
279     }
280 };
281
282 /** Map maintaining per-node state. Requires cs_main. */
283 map<NodeId, CNodeState> mapNodeState;
284
285 // Requires cs_main.
286 CNodeState *State(NodeId pnode) {
287     map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
288     if (it == mapNodeState.end())
289         return NULL;
290     return &it->second;
291 }
292
293 int GetHeight()
294 {
295     LOCK(cs_main);
296     return chainActive.Height();
297 }
298
299 void UpdatePreferredDownload(CNode* node, CNodeState* state)
300 {
301     nPreferredDownload -= state->fPreferredDownload;
302
303     // Whether this node should be marked as a preferred download node.
304     state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
305
306     nPreferredDownload += state->fPreferredDownload;
307 }
308
309 void InitializeNode(NodeId nodeid, const CNode *pnode) {
310     LOCK(cs_main);
311     CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
312     state.name = pnode->addrName;
313     state.address = pnode->addr;
314 }
315
316 void FinalizeNode(NodeId nodeid) {
317     LOCK(cs_main);
318     CNodeState *state = State(nodeid);
319
320     if (state->fSyncStarted)
321         nSyncStarted--;
322
323     if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
324         AddressCurrentlyConnected(state->address);
325     }
326
327     BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
328         mapBlocksInFlight.erase(entry.hash);
329     EraseOrphansFor(nodeid);
330     nPreferredDownload -= state->fPreferredDownload;
331
332     mapNodeState.erase(nodeid);
333 }
334
335 // Requires cs_main.
336 void MarkBlockAsReceived(const uint256& hash) {
337     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
338     if (itInFlight != mapBlocksInFlight.end()) {
339         CNodeState *state = State(itInFlight->second.first);
340         nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
341         state->vBlocksInFlight.erase(itInFlight->second.second);
342         state->nBlocksInFlight--;
343         state->nStallingSince = 0;
344         mapBlocksInFlight.erase(itInFlight);
345     }
346 }
347
348 // Requires cs_main.
349 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
350     CNodeState *state = State(nodeid);
351     assert(state != NULL);
352
353     // Make sure it's not listed somewhere already.
354     MarkBlockAsReceived(hash);
355
356     QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
357     nQueuedValidatedHeaders += newentry.fValidatedHeaders;
358     list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
359     state->nBlocksInFlight++;
360     mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
361 }
362
363 /** Check whether the last unknown block a peer advertized is not yet known. */
364 void ProcessBlockAvailability(NodeId nodeid) {
365     CNodeState *state = State(nodeid);
366     assert(state != NULL);
367
368     if (!state->hashLastUnknownBlock.IsNull()) {
369         BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
370         if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
371             if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
372                 state->pindexBestKnownBlock = itOld->second;
373             state->hashLastUnknownBlock.SetNull();
374         }
375     }
376 }
377
378 /** Update tracking information about which blocks a peer is assumed to have. */
379 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
380     CNodeState *state = State(nodeid);
381     assert(state != NULL);
382
383     ProcessBlockAvailability(nodeid);
384
385     BlockMap::iterator it = mapBlockIndex.find(hash);
386     if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
387         // An actually better block was announced.
388         if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
389             state->pindexBestKnownBlock = it->second;
390     } else {
391         // An unknown block was announced; just assume that the latest one is the best one.
392         state->hashLastUnknownBlock = hash;
393     }
394 }
395
396 /** Find the last common ancestor two blocks have.
397  *  Both pa and pb must be non-NULL. */
398 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
399     if (pa->nHeight > pb->nHeight) {
400         pa = pa->GetAncestor(pb->nHeight);
401     } else if (pb->nHeight > pa->nHeight) {
402         pb = pb->GetAncestor(pa->nHeight);
403     }
404
405     while (pa != pb && pa && pb) {
406         pa = pa->pprev;
407         pb = pb->pprev;
408     }
409
410     // Eventually all chain branches meet at the genesis block.
411     assert(pa == pb);
412     return pa;
413 }
414
415 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
416  *  at most count entries. */
417 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
418     if (count == 0)
419         return;
420
421     vBlocks.reserve(vBlocks.size() + count);
422     CNodeState *state = State(nodeid);
423     assert(state != NULL);
424
425     // Make sure pindexBestKnownBlock is up to date, we'll need it.
426     ProcessBlockAvailability(nodeid);
427
428     if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
429         // This peer has nothing interesting.
430         return;
431     }
432
433     if (state->pindexLastCommonBlock == NULL) {
434         // Bootstrap quickly by guessing a parent of our best tip is the forking point.
435         // Guessing wrong in either direction is not a problem.
436         state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
437     }
438
439     // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
440     // of their current tip anymore. Go back enough to fix that.
441     state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
442     if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
443         return;
444
445     std::vector<CBlockIndex*> vToFetch;
446     CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
447     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
448     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
449     // download that next block if the window were 1 larger.
450     int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
451     int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
452     NodeId waitingfor = -1;
453     while (pindexWalk->nHeight < nMaxHeight) {
454         // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
455         // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
456         // as iterating over ~100 CBlockIndex* entries anyway.
457         int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
458         vToFetch.resize(nToFetch);
459         pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
460         vToFetch[nToFetch - 1] = pindexWalk;
461         for (unsigned int i = nToFetch - 1; i > 0; i--) {
462             vToFetch[i - 1] = vToFetch[i]->pprev;
463         }
464
465         // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
466         // are not yet downloaded and not in flight to vBlocks. In the mean time, update
467         // pindexLastCommonBlock as long as all ancestors are already downloaded.
468         BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
469             if (!pindex->IsValid(BLOCK_VALID_TREE)) {
470                 // We consider the chain that this peer is on invalid.
471                 return;
472             }
473             if (pindex->nStatus & BLOCK_HAVE_DATA) {
474                 if (pindex->nChainTx)
475                     state->pindexLastCommonBlock = pindex;
476             } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
477                 // The block is not already downloaded, and not yet in flight.
478                 if (pindex->nHeight > nWindowEnd) {
479                     // We reached the end of the window.
480                     if (vBlocks.size() == 0 && waitingfor != nodeid) {
481                         // We aren't able to fetch anything, but we would be if the download window was one larger.
482                         nodeStaller = waitingfor;
483                     }
484                     return;
485                 }
486                 vBlocks.push_back(pindex);
487                 if (vBlocks.size() == count) {
488                     return;
489                 }
490             } else if (waitingfor == -1) {
491                 // This is the first already-in-flight block.
492                 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
493             }
494         }
495     }
496 }
497
498 } // anon namespace
499
500 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
501     LOCK(cs_main);
502     CNodeState *state = State(nodeid);
503     if (state == NULL)
504         return false;
505     stats.nMisbehavior = state->nMisbehavior;
506     stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
507     stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
508     BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
509         if (queue.pindex)
510             stats.vHeightInFlight.push_back(queue.pindex->nHeight);
511     }
512     return true;
513 }
514
515 void RegisterNodeSignals(CNodeSignals& nodeSignals)
516 {
517     nodeSignals.GetHeight.connect(&GetHeight);
518     nodeSignals.ProcessMessages.connect(&ProcessMessages);
519     nodeSignals.SendMessages.connect(&SendMessages);
520     nodeSignals.InitializeNode.connect(&InitializeNode);
521     nodeSignals.FinalizeNode.connect(&FinalizeNode);
522 }
523
524 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
525 {
526     nodeSignals.GetHeight.disconnect(&GetHeight);
527     nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
528     nodeSignals.SendMessages.disconnect(&SendMessages);
529     nodeSignals.InitializeNode.disconnect(&InitializeNode);
530     nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
531 }
532
533 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
534 {
535     // Find the first block the caller has in the main chain
536     BOOST_FOREACH(const uint256& hash, locator.vHave) {
537         BlockMap::iterator mi = mapBlockIndex.find(hash);
538         if (mi != mapBlockIndex.end())
539         {
540             CBlockIndex* pindex = (*mi).second;
541             if (chain.Contains(pindex))
542                 return pindex;
543         }
544     }
545     return chain.Genesis();
546 }
547
548 CCoinsViewCache *pcoinsTip = NULL;
549 CBlockTreeDB *pblocktree = NULL;
550
551 //////////////////////////////////////////////////////////////////////////////
552 //
553 // mapOrphanTransactions
554 //
555
556 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
557 {
558     uint256 hash = tx.GetHash();
559     if (mapOrphanTransactions.count(hash))
560         return false;
561
562     // Ignore big transactions, to avoid a
563     // send-big-orphans memory exhaustion attack. If a peer has a legitimate
564     // large transaction with a missing parent then we assume
565     // it will rebroadcast it later, after the parent transaction(s)
566     // have been mined or received.
567     // 10,000 orphans, each of which is at most 5,000 bytes big is
568     // at most 500 megabytes of orphans:
569     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
570     if (sz > 5000)
571     {
572         LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
573         return false;
574     }
575
576     mapOrphanTransactions[hash].tx = tx;
577     mapOrphanTransactions[hash].fromPeer = peer;
578     BOOST_FOREACH(const CTxIn& txin, tx.vin)
579         mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
580
581     LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
582              mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
583     return true;
584 }
585
586 void static EraseOrphanTx(uint256 hash)
587 {
588     map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
589     if (it == mapOrphanTransactions.end())
590         return;
591     BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
592     {
593         map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
594         if (itPrev == mapOrphanTransactionsByPrev.end())
595             continue;
596         itPrev->second.erase(hash);
597         if (itPrev->second.empty())
598             mapOrphanTransactionsByPrev.erase(itPrev);
599     }
600     mapOrphanTransactions.erase(it);
601 }
602
603 void EraseOrphansFor(NodeId peer)
604 {
605     int nErased = 0;
606     map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
607     while (iter != mapOrphanTransactions.end())
608     {
609         map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
610         if (maybeErase->second.fromPeer == peer)
611         {
612             EraseOrphanTx(maybeErase->second.tx.GetHash());
613             ++nErased;
614         }
615     }
616     if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
617 }
618
619
620 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
621 {
622     unsigned int nEvicted = 0;
623     while (mapOrphanTransactions.size() > nMaxOrphans)
624     {
625         // Evict a random orphan:
626         uint256 randomhash = GetRandHash();
627         map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
628         if (it == mapOrphanTransactions.end())
629             it = mapOrphanTransactions.begin();
630         EraseOrphanTx(it->first);
631         ++nEvicted;
632     }
633     return nEvicted;
634 }
635
636
637
638
639
640
641
642 bool IsStandardTx(const CTransaction& tx, string& reason)
643 {
644     if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
645         reason = "version";
646         return false;
647     }
648
649     // Extremely large transactions with lots of inputs can cost the network
650     // almost as much to process as they cost the sender in fees, because
651     // computing signature hashes is O(ninputs*txsize). Limiting transactions
652     // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
653     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
654     if (sz >= MAX_STANDARD_TX_SIZE) {
655         reason = "tx-size";
656         return false;
657     }
658
659     BOOST_FOREACH(const CTxIn& txin, tx.vin)
660     {
661         // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
662         // keys. (remember the 520 byte limit on redeemScript size) That works
663         // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
664         // bytes of scriptSig, which we round off to 1650 bytes for some minor
665         // future-proofing. That's also enough to spend a 20-of-20
666         // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
667         // considered standard)
668         if (txin.scriptSig.size() > 1650) {
669             reason = "scriptsig-size";
670             return false;
671         }
672         if (!txin.scriptSig.IsPushOnly()) {
673             reason = "scriptsig-not-pushonly";
674             return false;
675         }
676     }
677
678     unsigned int nDataOut = 0;
679     txnouttype whichType;
680     BOOST_FOREACH(const CTxOut& txout, tx.vout) {
681         if (!::IsStandard(txout.scriptPubKey, whichType)) {
682             reason = "scriptpubkey";
683             return false;
684         }
685
686         if (whichType == TX_NULL_DATA)
687             nDataOut++;
688         else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
689             reason = "bare-multisig";
690             return false;
691         } else if (txout.IsDust(::minRelayTxFee)) {
692             reason = "dust";
693             return false;
694         }
695     }
696
697     // only one OP_RETURN txout is permitted
698     if (nDataOut > 1) {
699         reason = "multi-op-return";
700         return false;
701     }
702
703     return true;
704 }
705
706 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
707 {
708     AssertLockHeld(cs_main);
709     // Time based nLockTime implemented in 0.1.6
710     if (tx.nLockTime == 0)
711         return true;
712     if (nBlockHeight == 0)
713         nBlockHeight = chainActive.Height();
714     if (nBlockTime == 0)
715         nBlockTime = GetAdjustedTime();
716     if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
717         return true;
718     BOOST_FOREACH(const CTxIn& txin, tx.vin)
719         if (!txin.IsFinal())
720             return false;
721     return true;
722 }
723
724 /**
725  * Check transaction inputs to mitigate two
726  * potential denial-of-service attacks:
727  * 
728  * 1. scriptSigs with extra data stuffed into them,
729  *    not consumed by scriptPubKey (or P2SH script)
730  * 2. P2SH scripts with a crazy number of expensive
731  *    CHECKSIG/CHECKMULTISIG operations
732  */
733 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
734 {
735     if (tx.IsCoinBase())
736         return true; // Coinbases don't use vin normally
737
738     for (unsigned int i = 0; i < tx.vin.size(); i++)
739     {
740         const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
741
742         vector<vector<unsigned char> > vSolutions;
743         txnouttype whichType;
744         // get the scriptPubKey corresponding to this input:
745         const CScript& prevScript = prev.scriptPubKey;
746         if (!Solver(prevScript, whichType, vSolutions))
747             return false;
748         int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
749         if (nArgsExpected < 0)
750             return false;
751
752         // Transactions with extra stuff in their scriptSigs are
753         // non-standard. Note that this EvalScript() call will
754         // be quick, because if there are any operations
755         // beside "push data" in the scriptSig
756         // IsStandardTx() will have already returned false
757         // and this method isn't called.
758         vector<vector<unsigned char> > stack;
759         if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
760             return false;
761
762         if (whichType == TX_SCRIPTHASH)
763         {
764             if (stack.empty())
765                 return false;
766             CScript subscript(stack.back().begin(), stack.back().end());
767             vector<vector<unsigned char> > vSolutions2;
768             txnouttype whichType2;
769             if (Solver(subscript, whichType2, vSolutions2))
770             {
771                 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
772                 if (tmpExpected < 0)
773                     return false;
774                 nArgsExpected += tmpExpected;
775             }
776             else
777             {
778                 // Any other Script with less than 15 sigops OK:
779                 unsigned int sigops = subscript.GetSigOpCount(true);
780                 // ... extra data left on the stack after execution is OK, too:
781                 return (sigops <= MAX_P2SH_SIGOPS);
782             }
783         }
784
785         if (stack.size() != (unsigned int)nArgsExpected)
786             return false;
787     }
788
789     return true;
790 }
791
792 unsigned int GetLegacySigOpCount(const CTransaction& tx)
793 {
794     unsigned int nSigOps = 0;
795     BOOST_FOREACH(const CTxIn& txin, tx.vin)
796     {
797         nSigOps += txin.scriptSig.GetSigOpCount(false);
798     }
799     BOOST_FOREACH(const CTxOut& txout, tx.vout)
800     {
801         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
802     }
803     return nSigOps;
804 }
805
806 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
807 {
808     if (tx.IsCoinBase())
809         return 0;
810
811     unsigned int nSigOps = 0;
812     for (unsigned int i = 0; i < tx.vin.size(); i++)
813     {
814         const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
815         if (prevout.scriptPubKey.IsPayToScriptHash())
816             nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
817     }
818     return nSigOps;
819 }
820
821
822
823
824
825
826
827
828 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
829 {
830     // Basic checks that don't depend on any context
831     if (tx.vin.empty())
832         return state.DoS(10, error("CheckTransaction(): vin empty"),
833                          REJECT_INVALID, "bad-txns-vin-empty");
834     if (tx.vout.empty())
835         return state.DoS(10, error("CheckTransaction(): vout empty"),
836                          REJECT_INVALID, "bad-txns-vout-empty");
837     // Size limits
838     if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
839         return state.DoS(100, error("CheckTransaction(): size limits failed"),
840                          REJECT_INVALID, "bad-txns-oversize");
841
842     // Check for negative or overflow output values
843     CAmount nValueOut = 0;
844     BOOST_FOREACH(const CTxOut& txout, tx.vout)
845     {
846         if (txout.nValue < 0)
847             return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
848                              REJECT_INVALID, "bad-txns-vout-negative");
849         if (txout.nValue > MAX_MONEY)
850             return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
851                              REJECT_INVALID, "bad-txns-vout-toolarge");
852         nValueOut += txout.nValue;
853         if (!MoneyRange(nValueOut))
854             return state.DoS(100, error("CheckTransaction(): txout total out of range"),
855                              REJECT_INVALID, "bad-txns-txouttotal-toolarge");
856     }
857
858     // Check for duplicate inputs
859     set<COutPoint> vInOutPoints;
860     BOOST_FOREACH(const CTxIn& txin, tx.vin)
861     {
862         if (vInOutPoints.count(txin.prevout))
863             return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
864                              REJECT_INVALID, "bad-txns-inputs-duplicate");
865         vInOutPoints.insert(txin.prevout);
866     }
867
868     if (tx.IsCoinBase())
869     {
870         if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
871             return state.DoS(100, error("CheckTransaction(): coinbase script size"),
872                              REJECT_INVALID, "bad-cb-length");
873     }
874     else
875     {
876         BOOST_FOREACH(const CTxIn& txin, tx.vin)
877             if (txin.prevout.IsNull())
878                 return state.DoS(10, error("CheckTransaction(): prevout is null"),
879                                  REJECT_INVALID, "bad-txns-prevout-null");
880     }
881
882     return true;
883 }
884
885 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
886 {
887     {
888         LOCK(mempool.cs);
889         uint256 hash = tx.GetHash();
890         double dPriorityDelta = 0;
891         CAmount nFeeDelta = 0;
892         mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
893         if (dPriorityDelta > 0 || nFeeDelta > 0)
894             return 0;
895     }
896
897     CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
898
899     if (fAllowFree)
900     {
901         // There is a free transaction area in blocks created by most miners,
902         // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
903         //   to be considered to fall into this category. We don't want to encourage sending
904         //   multiple transactions instead of one big transaction to avoid fees.
905         if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
906             nMinFee = 0;
907     }
908
909     if (!MoneyRange(nMinFee))
910         nMinFee = MAX_MONEY;
911     return nMinFee;
912 }
913
914
915 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
916                         bool* pfMissingInputs, bool fRejectAbsurdFee)
917 {
918     AssertLockHeld(cs_main);
919     if (pfMissingInputs)
920         *pfMissingInputs = false;
921
922     if (!CheckTransaction(tx, state))
923         return error("AcceptToMemoryPool: CheckTransaction failed");
924
925     // Coinbase is only valid in a block, not as a loose transaction
926     if (tx.IsCoinBase())
927         return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
928                          REJECT_INVALID, "coinbase");
929
930     // Rather not work on nonstandard transactions (unless -testnet/-regtest)
931     string reason;
932     if (Params().RequireStandard() && !IsStandardTx(tx, reason))
933         return state.DoS(0,
934                          error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
935                          REJECT_NONSTANDARD, reason);
936
937     // Only accept nLockTime-using transactions that can be mined in the next
938     // block; we don't want our mempool filled up with transactions that can't
939     // be mined yet.
940     //
941     // However, IsFinalTx() is confusing... Without arguments, it uses
942     // chainActive.Height() to evaluate nLockTime; when a block is accepted,
943     // chainActive.Height() is set to the value of nHeight in the block.
944     // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the
945     // height of the block *being* evaluated is what is used. Thus if we want
946     // to know if a transaction can be part of the *next* block, we need to
947     // call IsFinalTx() with one more than chainActive.Height().
948     //
949     // Timestamps on the other hand don't get any special treatment, because we
950     // can't know what timestamp the next block will have, and there aren't
951     // timestamp applications where it matters.
952     if (!IsFinalTx(tx, chainActive.Height() + 1))
953         return state.DoS(0,
954                          error("AcceptToMemoryPool: non-final"),
955                          REJECT_NONSTANDARD, "non-final");
956
957     // is it already in the memory pool?
958     uint256 hash = tx.GetHash();
959     if (pool.exists(hash))
960         return false;
961
962     // Check for conflicts with in-memory transactions
963     {
964     LOCK(pool.cs); // protect pool.mapNextTx
965     for (unsigned int i = 0; i < tx.vin.size(); i++)
966     {
967         COutPoint outpoint = tx.vin[i].prevout;
968         if (pool.mapNextTx.count(outpoint))
969         {
970             // Disable replacement feature for now
971             return false;
972         }
973     }
974     }
975
976     {
977         CCoinsView dummy;
978         CCoinsViewCache view(&dummy);
979
980         CAmount nValueIn = 0;
981         {
982         LOCK(pool.cs);
983         CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
984         view.SetBackend(viewMemPool);
985
986         // do we already have it?
987         if (view.HaveCoins(hash))
988             return false;
989
990         // do all inputs exist?
991         // Note that this does not check for the presence of actual outputs (see the next check for that),
992         // only helps filling in pfMissingInputs (to determine missing vs spent).
993         BOOST_FOREACH(const CTxIn txin, tx.vin) {
994             if (!view.HaveCoins(txin.prevout.hash)) {
995                 if (pfMissingInputs)
996                     *pfMissingInputs = true;
997                 return false;
998             }
999         }
1000
1001         // are the actual inputs available?
1002         if (!view.HaveInputs(tx))
1003             return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1004                                  REJECT_DUPLICATE, "bad-txns-inputs-spent");
1005
1006         // Bring the best block into scope
1007         view.GetBestBlock();
1008
1009         nValueIn = view.GetValueIn(tx);
1010
1011         // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1012         view.SetBackend(dummy);
1013         }
1014
1015         // Check for non-standard pay-to-script-hash in inputs
1016         if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1017             return error("AcceptToMemoryPool: nonstandard transaction input");
1018
1019         // Check that the transaction doesn't have an excessive number of
1020         // sigops, making it impossible to mine. Since the coinbase transaction
1021         // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1022         // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1023         // merely non-standard transaction.
1024         unsigned int nSigOps = GetLegacySigOpCount(tx);
1025         nSigOps += GetP2SHSigOpCount(tx, view);
1026         if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1027             return state.DoS(0,
1028                              error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1029                                    hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1030                              REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1031
1032         CAmount nValueOut = tx.GetValueOut();
1033         CAmount nFees = nValueIn-nValueOut;
1034         double dPriority = view.GetPriority(tx, chainActive.Height());
1035
1036         CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
1037         unsigned int nSize = entry.GetTxSize();
1038
1039         // Don't accept it if it can't get into a block
1040         CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1041         if (fLimitFree && nFees < txMinFee)
1042             return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1043                                       hash.ToString(), nFees, txMinFee),
1044                              REJECT_INSUFFICIENTFEE, "insufficient fee");
1045
1046         // Require that free transactions have sufficient priority to be mined in the next block.
1047         if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1048             return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1049         }
1050
1051         // Continuously rate-limit free (really, very-low-fee) transactions
1052         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1053         // be annoying or make others' transactions take longer to confirm.
1054         if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1055         {
1056             static CCriticalSection csFreeLimiter;
1057             static double dFreeCount;
1058             static int64_t nLastTime;
1059             int64_t nNow = GetTime();
1060
1061             LOCK(csFreeLimiter);
1062
1063             // Use an exponentially decaying ~10-minute window:
1064             dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1065             nLastTime = nNow;
1066             // -limitfreerelay unit is thousand-bytes-per-minute
1067             // At default rate it would take over a month to fill 1GB
1068             if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1069                 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1070                                  REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1071             LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1072             dFreeCount += nSize;
1073         }
1074
1075         if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1076             return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1077                          hash.ToString(),
1078                          nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1079
1080         // Check against previous transactions
1081         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1082         if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1083         {
1084             return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1085         }
1086
1087         // Check again against just the consensus-critical mandatory script
1088         // verification flags, in case of bugs in the standard flags that cause
1089         // transactions to pass as valid when they're actually invalid. For
1090         // instance the STRICTENC flag was incorrectly allowing certain
1091         // CHECKSIG NOT scripts to pass, even though they were invalid.
1092         //
1093         // There is a similar check in CreateNewBlock() to prevent creating
1094         // invalid blocks, however allowing such transactions into the mempool
1095         // can be exploited as a DoS attack.
1096         if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1097         {
1098             return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1099         }
1100
1101         // Store transaction in memory
1102         pool.addUnchecked(hash, entry);
1103     }
1104
1105     SyncWithWallets(tx, NULL);
1106
1107     return true;
1108 }
1109
1110 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1111 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1112 {
1113     CBlockIndex *pindexSlow = NULL;
1114     {
1115         LOCK(cs_main);
1116         {
1117             if (mempool.lookup(hash, txOut))
1118             {
1119                 return true;
1120             }
1121         }
1122
1123         if (fTxIndex) {
1124             CDiskTxPos postx;
1125             if (pblocktree->ReadTxIndex(hash, postx)) {
1126                 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1127                 if (file.IsNull())
1128                     return error("%s: OpenBlockFile failed", __func__);
1129                 CBlockHeader header;
1130                 try {
1131                     file >> header;
1132                     fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1133                     file >> txOut;
1134                 } catch (const std::exception& e) {
1135                     return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1136                 }
1137                 hashBlock = header.GetHash();
1138                 if (txOut.GetHash() != hash)
1139                     return error("%s: txid mismatch", __func__);
1140                 return true;
1141             }
1142         }
1143
1144         if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1145             int nHeight = -1;
1146             {
1147                 CCoinsViewCache &view = *pcoinsTip;
1148                 const CCoins* coins = view.AccessCoins(hash);
1149                 if (coins)
1150                     nHeight = coins->nHeight;
1151             }
1152             if (nHeight > 0)
1153                 pindexSlow = chainActive[nHeight];
1154         }
1155     }
1156
1157     if (pindexSlow) {
1158         CBlock block;
1159         if (ReadBlockFromDisk(block, pindexSlow)) {
1160             BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1161                 if (tx.GetHash() == hash) {
1162                     txOut = tx;
1163                     hashBlock = pindexSlow->GetBlockHash();
1164                     return true;
1165                 }
1166             }
1167         }
1168     }
1169
1170     return false;
1171 }
1172
1173
1174
1175
1176
1177
1178 //////////////////////////////////////////////////////////////////////////////
1179 //
1180 // CBlock and CBlockIndex
1181 //
1182
1183 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1184 {
1185     // Open history file to append
1186     CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1187     if (fileout.IsNull())
1188         return error("WriteBlockToDisk: OpenBlockFile failed");
1189
1190     // Write index header
1191     unsigned int nSize = fileout.GetSerializeSize(block);
1192     fileout << FLATDATA(Params().MessageStart()) << nSize;
1193
1194     // Write block
1195     long fileOutPos = ftell(fileout.Get());
1196     if (fileOutPos < 0)
1197         return error("WriteBlockToDisk: ftell failed");
1198     pos.nPos = (unsigned int)fileOutPos;
1199     fileout << block;
1200
1201     return true;
1202 }
1203
1204 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1205 {
1206     block.SetNull();
1207
1208     // Open history file to read
1209     CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1210     if (filein.IsNull())
1211         return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1212
1213     // Read block
1214     try {
1215         filein >> block;
1216     }
1217     catch (const std::exception& e) {
1218         return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1219     }
1220
1221     // Check the header
1222     if (!CheckProofOfWork(block.GetHash(), block.nBits))
1223         return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1224
1225     return true;
1226 }
1227
1228 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1229 {
1230     if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1231         return false;
1232     if (block.GetHash() != pindex->GetBlockHash())
1233         return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1234                 pindex->ToString(), pindex->GetBlockPos().ToString());
1235     return true;
1236 }
1237
1238 CAmount GetBlockValue(int nHeight, const CAmount& nFees)
1239 {
1240     CAmount nSubsidy = 50 * COIN;
1241     int halvings = nHeight / Params().SubsidyHalvingInterval();
1242
1243     // Force block reward to zero when right shift is undefined.
1244     if (halvings >= 64)
1245         return nFees;
1246
1247     // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1248     nSubsidy >>= halvings;
1249
1250     return nSubsidy + nFees;
1251 }
1252
1253 bool IsInitialBlockDownload()
1254 {
1255     LOCK(cs_main);
1256     if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1257         return true;
1258     static bool lockIBDState = false;
1259     if (lockIBDState)
1260         return false;
1261     bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1262             pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1263     if (!state)
1264         lockIBDState = true;
1265     return state;
1266 }
1267
1268 bool fLargeWorkForkFound = false;
1269 bool fLargeWorkInvalidChainFound = false;
1270 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1271
1272 void CheckForkWarningConditions()
1273 {
1274     AssertLockHeld(cs_main);
1275     // Before we get past initial download, we cannot reliably alert about forks
1276     // (we assume we don't get stuck on a fork before the last checkpoint)
1277     if (IsInitialBlockDownload())
1278         return;
1279
1280     // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1281     // of our head, drop it
1282     if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1283         pindexBestForkTip = NULL;
1284
1285     if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1286     {
1287         if (!fLargeWorkForkFound && pindexBestForkBase)
1288         {
1289             std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1290                 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1291             CAlert::Notify(warning, true);
1292         }
1293         if (pindexBestForkTip && pindexBestForkBase)
1294         {
1295             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",
1296                    pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1297                    pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1298             fLargeWorkForkFound = true;
1299         }
1300         else
1301         {
1302             LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1303             fLargeWorkInvalidChainFound = true;
1304         }
1305     }
1306     else
1307     {
1308         fLargeWorkForkFound = false;
1309         fLargeWorkInvalidChainFound = false;
1310     }
1311 }
1312
1313 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1314 {
1315     AssertLockHeld(cs_main);
1316     // If we are on a fork that is sufficiently large, set a warning flag
1317     CBlockIndex* pfork = pindexNewForkTip;
1318     CBlockIndex* plonger = chainActive.Tip();
1319     while (pfork && pfork != plonger)
1320     {
1321         while (plonger && plonger->nHeight > pfork->nHeight)
1322             plonger = plonger->pprev;
1323         if (pfork == plonger)
1324             break;
1325         pfork = pfork->pprev;
1326     }
1327
1328     // We define a condition which we should warn the user about as a fork of at least 7 blocks
1329     // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1330     // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1331     // hash rate operating on the fork.
1332     // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1333     // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1334     // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1335     if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1336             pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1337             chainActive.Height() - pindexNewForkTip->nHeight < 72)
1338     {
1339         pindexBestForkTip = pindexNewForkTip;
1340         pindexBestForkBase = pfork;
1341     }
1342
1343     CheckForkWarningConditions();
1344 }
1345
1346 // Requires cs_main.
1347 void Misbehaving(NodeId pnode, int howmuch)
1348 {
1349     if (howmuch == 0)
1350         return;
1351
1352     CNodeState *state = State(pnode);
1353     if (state == NULL)
1354         return;
1355
1356     state->nMisbehavior += howmuch;
1357     int banscore = GetArg("-banscore", 100);
1358     if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1359     {
1360         LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1361         state->fShouldBan = true;
1362     } else
1363         LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1364 }
1365
1366 void static InvalidChainFound(CBlockIndex* pindexNew)
1367 {
1368     if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1369         pindexBestInvalid = pindexNew;
1370
1371     LogPrintf("InvalidChainFound: invalid block=%s  height=%d  log2_work=%.8g  date=%s\n",
1372       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1373       log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1374       pindexNew->GetBlockTime()));
1375     LogPrintf("InvalidChainFound:  current best=%s  height=%d  log2_work=%.8g  date=%s\n",
1376       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1377       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1378     CheckForkWarningConditions();
1379 }
1380
1381 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1382     int nDoS = 0;
1383     if (state.IsInvalid(nDoS)) {
1384         std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1385         if (it != mapBlockSource.end() && State(it->second)) {
1386             CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1387             State(it->second)->rejects.push_back(reject);
1388             if (nDoS > 0)
1389                 Misbehaving(it->second, nDoS);
1390         }
1391     }
1392     if (!state.CorruptionPossible()) {
1393         pindex->nStatus |= BLOCK_FAILED_VALID;
1394         setDirtyBlockIndex.insert(pindex);
1395         setBlockIndexCandidates.erase(pindex);
1396         InvalidChainFound(pindex);
1397     }
1398 }
1399
1400 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1401 {
1402     // mark inputs spent
1403     if (!tx.IsCoinBase()) {
1404         txundo.vprevout.reserve(tx.vin.size());
1405         BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1406             CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1407             unsigned nPos = txin.prevout.n;
1408
1409             if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1410                 assert(false);
1411             // mark an outpoint spent, and construct undo information
1412             txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1413             coins->Spend(nPos);
1414             if (coins->vout.size() == 0) {
1415                 CTxInUndo& undo = txundo.vprevout.back();
1416                 undo.nHeight = coins->nHeight;
1417                 undo.fCoinBase = coins->fCoinBase;
1418                 undo.nVersion = coins->nVersion;
1419             }
1420         }
1421     }
1422
1423     // add outputs
1424     inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1425 }
1426
1427 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1428 {
1429     CTxUndo txundo;
1430     UpdateCoins(tx, state, inputs, txundo, nHeight);
1431 }
1432
1433 bool CScriptCheck::operator()() {
1434     const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1435     if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1436         return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1437     }
1438     return true;
1439 }
1440
1441 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1442 {
1443     if (!tx.IsCoinBase())
1444     {
1445         if (pvChecks)
1446             pvChecks->reserve(tx.vin.size());
1447
1448         // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1449         // for an attacker to attempt to split the network.
1450         if (!inputs.HaveInputs(tx))
1451             return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1452
1453         // While checking, GetBestBlock() refers to the parent block.
1454         // This is also true for mempool checks.
1455         CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1456         int nSpendHeight = pindexPrev->nHeight + 1;
1457         CAmount nValueIn = 0;
1458         CAmount nFees = 0;
1459         for (unsigned int i = 0; i < tx.vin.size(); i++)
1460         {
1461             const COutPoint &prevout = tx.vin[i].prevout;
1462             const CCoins *coins = inputs.AccessCoins(prevout.hash);
1463             assert(coins);
1464
1465             // If prev is coinbase, check that it's matured
1466             if (coins->IsCoinBase()) {
1467                 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1468                     return state.Invalid(
1469                         error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1470                         REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1471             }
1472
1473             // Check for negative or overflow input values
1474             nValueIn += coins->vout[prevout.n].nValue;
1475             if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1476                 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1477                                  REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1478
1479         }
1480
1481         if (nValueIn < tx.GetValueOut())
1482             return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1483                                         tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1484                              REJECT_INVALID, "bad-txns-in-belowout");
1485
1486         // Tally transaction fees
1487         CAmount nTxFee = nValueIn - tx.GetValueOut();
1488         if (nTxFee < 0)
1489             return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1490                              REJECT_INVALID, "bad-txns-fee-negative");
1491         nFees += nTxFee;
1492         if (!MoneyRange(nFees))
1493             return state.DoS(100, error("CheckInputs(): nFees out of range"),
1494                              REJECT_INVALID, "bad-txns-fee-outofrange");
1495
1496         // The first loop above does all the inexpensive checks.
1497         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1498         // Helps prevent CPU exhaustion attacks.
1499
1500         // Skip ECDSA signature verification when connecting blocks
1501         // before the last block chain checkpoint. This is safe because block merkle hashes are
1502         // still computed and checked, and any change will be caught at the next checkpoint.
1503         if (fScriptChecks) {
1504             for (unsigned int i = 0; i < tx.vin.size(); i++) {
1505                 const COutPoint &prevout = tx.vin[i].prevout;
1506                 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1507                 assert(coins);
1508
1509                 // Verify signature
1510                 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1511                 if (pvChecks) {
1512                     pvChecks->push_back(CScriptCheck());
1513                     check.swap(pvChecks->back());
1514                 } else if (!check()) {
1515                     if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1516                         // Check whether the failure was caused by a
1517                         // non-mandatory script verification check, such as
1518                         // non-standard DER encodings or non-null dummy
1519                         // arguments; if so, don't trigger DoS protection to
1520                         // avoid splitting the network between upgraded and
1521                         // non-upgraded nodes.
1522                         CScriptCheck check(*coins, tx, i,
1523                                 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1524                         if (check())
1525                             return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1526                     }
1527                     // Failures of other flags indicate a transaction that is
1528                     // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1529                     // such nodes as they are not following the protocol. That
1530                     // said during an upgrade careful thought should be taken
1531                     // as to the correct behavior - we may want to continue
1532                     // peering with non-upgraded nodes even after a soft-fork
1533                     // super-majority vote has passed.
1534                     return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1535                 }
1536             }
1537         }
1538     }
1539
1540     return true;
1541 }
1542
1543 namespace {
1544
1545 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock)
1546 {
1547     // Open history file to append
1548     CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1549     if (fileout.IsNull())
1550         return error("%s: OpenUndoFile failed", __func__);
1551
1552     // Write index header
1553     unsigned int nSize = fileout.GetSerializeSize(blockundo);
1554     fileout << FLATDATA(Params().MessageStart()) << nSize;
1555
1556     // Write undo data
1557     long fileOutPos = ftell(fileout.Get());
1558     if (fileOutPos < 0)
1559         return error("%s: ftell failed", __func__);
1560     pos.nPos = (unsigned int)fileOutPos;
1561     fileout << blockundo;
1562
1563     // calculate & write checksum
1564     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1565     hasher << hashBlock;
1566     hasher << blockundo;
1567     fileout << hasher.GetHash();
1568
1569     return true;
1570 }
1571
1572 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1573 {
1574     // Open history file to read
1575     CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1576     if (filein.IsNull())
1577         return error("%s: OpenBlockFile failed", __func__);
1578
1579     // Read block
1580     uint256 hashChecksum;
1581     try {
1582         filein >> blockundo;
1583         filein >> hashChecksum;
1584     }
1585     catch (const std::exception& e) {
1586         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1587     }
1588
1589     // Verify checksum
1590     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1591     hasher << hashBlock;
1592     hasher << blockundo;
1593     if (hashChecksum != hasher.GetHash())
1594         return error("%s: Checksum mismatch", __func__);
1595
1596     return true;
1597 }
1598
1599 } // anon namespace
1600
1601 /**
1602  * Apply the undo operation of a CTxInUndo to the given chain state.
1603  * @param undo The undo object.
1604  * @param view The coins view to which to apply the changes.
1605  * @param out The out point that corresponds to the tx input.
1606  * @return True on success.
1607  */
1608 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1609 {
1610     bool fClean = true;
1611
1612     CCoinsModifier coins = view.ModifyCoins(out.hash);
1613     if (undo.nHeight != 0) {
1614         // undo data contains height: this is the last output of the prevout tx being spent
1615         if (!coins->IsPruned())
1616             fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1617         coins->Clear();
1618         coins->fCoinBase = undo.fCoinBase;
1619         coins->nHeight = undo.nHeight;
1620         coins->nVersion = undo.nVersion;
1621     } else {
1622         if (coins->IsPruned())
1623             fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1624     }
1625     if (coins->IsAvailable(out.n))
1626         fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1627     if (coins->vout.size() < out.n+1)
1628         coins->vout.resize(out.n+1);
1629     coins->vout[out.n] = undo.txout;
1630
1631     return fClean;
1632 }
1633
1634 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1635 {
1636     assert(pindex->GetBlockHash() == view.GetBestBlock());
1637
1638     if (pfClean)
1639         *pfClean = false;
1640
1641     bool fClean = true;
1642
1643     CBlockUndo blockUndo;
1644     CDiskBlockPos pos = pindex->GetUndoPos();
1645     if (pos.IsNull())
1646         return error("DisconnectBlock(): no undo data available");
1647     if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1648         return error("DisconnectBlock(): failure reading undo data");
1649
1650     if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1651         return error("DisconnectBlock(): block and undo data inconsistent");
1652
1653     // undo transactions in reverse order
1654     for (int i = block.vtx.size() - 1; i >= 0; i--) {
1655         const CTransaction &tx = block.vtx[i];
1656         uint256 hash = tx.GetHash();
1657
1658         // Check that all outputs are available and match the outputs in the block itself
1659         // exactly.
1660         {
1661         CCoinsModifier outs = view.ModifyCoins(hash);
1662         outs->ClearUnspendable();
1663
1664         CCoins outsBlock(tx, pindex->nHeight);
1665         // The CCoins serialization does not serialize negative numbers.
1666         // No network rules currently depend on the version here, so an inconsistency is harmless
1667         // but it must be corrected before txout nversion ever influences a network rule.
1668         if (outsBlock.nVersion < 0)
1669             outs->nVersion = outsBlock.nVersion;
1670         if (*outs != outsBlock)
1671             fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1672
1673         // remove outputs
1674         outs->Clear();
1675         }
1676
1677         // restore inputs
1678         if (i > 0) { // not coinbases
1679             const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1680             if (txundo.vprevout.size() != tx.vin.size())
1681                 return error("DisconnectBlock(): transaction and undo data inconsistent");
1682             for (unsigned int j = tx.vin.size(); j-- > 0;) {
1683                 const COutPoint &out = tx.vin[j].prevout;
1684                 const CTxInUndo &undo = txundo.vprevout[j];
1685                 if (!ApplyTxInUndo(undo, view, out))
1686                     fClean = false;
1687             }
1688         }
1689     }
1690
1691     // move best block pointer to prevout block
1692     view.SetBestBlock(pindex->pprev->GetBlockHash());
1693
1694     if (pfClean) {
1695         *pfClean = fClean;
1696         return true;
1697     }
1698
1699     return fClean;
1700 }
1701
1702 void static FlushBlockFile(bool fFinalize = false)
1703 {
1704     LOCK(cs_LastBlockFile);
1705
1706     CDiskBlockPos posOld(nLastBlockFile, 0);
1707
1708     FILE *fileOld = OpenBlockFile(posOld);
1709     if (fileOld) {
1710         if (fFinalize)
1711             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1712         FileCommit(fileOld);
1713         fclose(fileOld);
1714     }
1715
1716     fileOld = OpenUndoFile(posOld);
1717     if (fileOld) {
1718         if (fFinalize)
1719             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1720         FileCommit(fileOld);
1721         fclose(fileOld);
1722     }
1723 }
1724
1725 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1726
1727 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1728
1729 void ThreadScriptCheck() {
1730     RenameThread("bitcoin-scriptch");
1731     scriptcheckqueue.Thread();
1732 }
1733
1734 static int64_t nTimeVerify = 0;
1735 static int64_t nTimeConnect = 0;
1736 static int64_t nTimeIndex = 0;
1737 static int64_t nTimeCallbacks = 0;
1738 static int64_t nTimeTotal = 0;
1739
1740 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1741 {
1742     AssertLockHeld(cs_main);
1743     // Check it again in case a previous version let a bad block in
1744     if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1745         return false;
1746
1747     // verify that the view's current state corresponds to the previous block
1748     uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1749     assert(hashPrevBlock == view.GetBestBlock());
1750
1751     // Special case for the genesis block, skipping connection of its transactions
1752     // (its coinbase is unspendable)
1753     if (block.GetHash() == Params().HashGenesisBlock()) {
1754         if (!fJustCheck)
1755             view.SetBestBlock(pindex->GetBlockHash());
1756         return true;
1757     }
1758
1759     bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1760
1761     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1762     // unless those are already completely spent.
1763     // If such overwrites are allowed, coinbases and transactions depending upon those
1764     // can be duplicated to remove the ability to spend the first instance -- even after
1765     // being sent to another address.
1766     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1767     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1768     // already refuses previously-known transaction ids entirely.
1769     // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1770     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1771     // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1772     // initial block download.
1773     bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1774                           !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1775                            (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1776     if (fEnforceBIP30) {
1777         BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1778             const CCoins* coins = view.AccessCoins(tx.GetHash());
1779             if (coins && !coins->IsPruned())
1780                 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1781                                  REJECT_INVALID, "bad-txns-BIP30");
1782         }
1783     }
1784
1785     // BIP16 didn't become active until Apr 1 2012
1786     int64_t nBIP16SwitchTime = 1333238400;
1787     bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1788
1789     unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1790
1791     // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1792     if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
1793         flags |= SCRIPT_VERIFY_DERSIG;
1794     }
1795
1796     CBlockUndo blockundo;
1797
1798     CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1799
1800     int64_t nTimeStart = GetTimeMicros();
1801     CAmount nFees = 0;
1802     int nInputs = 0;
1803     unsigned int nSigOps = 0;
1804     CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1805     std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1806     vPos.reserve(block.vtx.size());
1807     blockundo.vtxundo.reserve(block.vtx.size() - 1);
1808     for (unsigned int i = 0; i < block.vtx.size(); i++)
1809     {
1810         const CTransaction &tx = block.vtx[i];
1811
1812         nInputs += tx.vin.size();
1813         nSigOps += GetLegacySigOpCount(tx);
1814         if (nSigOps > MAX_BLOCK_SIGOPS)
1815             return state.DoS(100, error("ConnectBlock(): too many sigops"),
1816                              REJECT_INVALID, "bad-blk-sigops");
1817
1818         if (!tx.IsCoinBase())
1819         {
1820             if (!view.HaveInputs(tx))
1821                 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1822                                  REJECT_INVALID, "bad-txns-inputs-missingorspent");
1823
1824             if (fStrictPayToScriptHash)
1825             {
1826                 // Add in sigops done by pay-to-script-hash inputs;
1827                 // this is to prevent a "rogue miner" from creating
1828                 // an incredibly-expensive-to-validate block.
1829                 nSigOps += GetP2SHSigOpCount(tx, view);
1830                 if (nSigOps > MAX_BLOCK_SIGOPS)
1831                     return state.DoS(100, error("ConnectBlock(): too many sigops"),
1832                                      REJECT_INVALID, "bad-blk-sigops");
1833             }
1834
1835             nFees += view.GetValueIn(tx)-tx.GetValueOut();
1836
1837             std::vector<CScriptCheck> vChecks;
1838             if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1839                 return false;
1840             control.Add(vChecks);
1841         }
1842
1843         CTxUndo undoDummy;
1844         if (i > 0) {
1845             blockundo.vtxundo.push_back(CTxUndo());
1846         }
1847         UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1848
1849         vPos.push_back(std::make_pair(tx.GetHash(), pos));
1850         pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1851     }
1852     int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1853     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);
1854
1855     if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1856         return state.DoS(100,
1857                          error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1858                                block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
1859                                REJECT_INVALID, "bad-cb-amount");
1860
1861     if (!control.Wait())
1862         return state.DoS(100, false);
1863     int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1864     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);
1865
1866     if (fJustCheck)
1867         return true;
1868
1869     // Write undo information to disk
1870     if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1871     {
1872         if (pindex->GetUndoPos().IsNull()) {
1873             CDiskBlockPos pos;
1874             if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1875                 return error("ConnectBlock(): FindUndoPos failed");
1876             if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash()))
1877                 return state.Abort("Failed to write undo data");
1878
1879             // update nUndoPos in block index
1880             pindex->nUndoPos = pos.nPos;
1881             pindex->nStatus |= BLOCK_HAVE_UNDO;
1882         }
1883
1884         pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1885         setDirtyBlockIndex.insert(pindex);
1886     }
1887
1888     if (fTxIndex)
1889         if (!pblocktree->WriteTxIndex(vPos))
1890             return state.Abort("Failed to write transaction index");
1891
1892     // add this block to the view's block chain
1893     view.SetBestBlock(pindex->GetBlockHash());
1894
1895     int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1896     LogPrint("bench", "    - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1897
1898     // Watch for changes to the previous coinbase transaction.
1899     static uint256 hashPrevBestCoinBase;
1900     g_signals.UpdatedTransaction(hashPrevBestCoinBase);
1901     hashPrevBestCoinBase = block.vtx[0].GetHash();
1902
1903     int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1904     LogPrint("bench", "    - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1905
1906     return true;
1907 }
1908
1909 enum FlushStateMode {
1910     FLUSH_STATE_IF_NEEDED,
1911     FLUSH_STATE_PERIODIC,
1912     FLUSH_STATE_ALWAYS
1913 };
1914
1915 /**
1916  * Update the on-disk chain state.
1917  * The caches and indexes are flushed if either they're too large, forceWrite is set, or
1918  * fast is not set and it's been a while since the last write.
1919  */
1920 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1921     LOCK(cs_main);
1922     static int64_t nLastWrite = 0;
1923     try {
1924     if ((mode == FLUSH_STATE_ALWAYS) ||
1925         ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
1926         (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
1927         // Typical CCoins structures on disk are around 100 bytes in size.
1928         // Pushing a new one to the database can cause it to be written
1929         // twice (once in the log, and once in the tables). This is already
1930         // an overestimation, as most will delete an existing entry or
1931         // overwrite one. Still, use a conservative safety factor of 2.
1932         if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1933             return state.Error("out of disk space");
1934         // First make sure all block and undo data is flushed to disk.
1935         FlushBlockFile();
1936         // Then update all block file information (which may refer to block and undo files).
1937         {
1938             std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1939             vFiles.reserve(setDirtyFileInfo.size());
1940             for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1941                 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
1942                 setDirtyFileInfo.erase(it++);
1943             }
1944             std::vector<const CBlockIndex*> vBlocks;
1945             vBlocks.reserve(setDirtyBlockIndex.size());
1946             for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1947                 vBlocks.push_back(*it);
1948                 setDirtyBlockIndex.erase(it++);
1949             }
1950             if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1951                 return state.Abort("Files to write to block index database");
1952             }
1953         }
1954         // Finally flush the chainstate (which may refer to block index entries).
1955         if (!pcoinsTip->Flush())
1956             return state.Abort("Failed to write to coin database");
1957         // Update best block in wallet (so we can detect restored wallets).
1958         if (mode != FLUSH_STATE_IF_NEEDED) {
1959             g_signals.SetBestChain(chainActive.GetLocator());
1960         }
1961         nLastWrite = GetTimeMicros();
1962     }
1963     } catch (const std::runtime_error& e) {
1964         return state.Abort(std::string("System error while flushing: ") + e.what());
1965     }
1966     return true;
1967 }
1968
1969 void FlushStateToDisk() {
1970     CValidationState state;
1971     FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1972 }
1973
1974 /** Update chainActive and related internal data structures. */
1975 void static UpdateTip(CBlockIndex *pindexNew) {
1976     chainActive.SetTip(pindexNew);
1977
1978     // New best block
1979     nTimeBestReceived = GetTime();
1980     mempool.AddTransactionsUpdated(1);
1981
1982     LogPrintf("UpdateTip: new best=%s  height=%d  log2_work=%.8g  tx=%lu  date=%s progress=%f  cache=%u\n",
1983       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1984       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1985       Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
1986
1987     cvBlockChange.notify_all();
1988
1989     // Check the version of the last 100 blocks to see if we need to upgrade:
1990     static bool fWarned = false;
1991     if (!IsInitialBlockDownload() && !fWarned)
1992     {
1993         int nUpgraded = 0;
1994         const CBlockIndex* pindex = chainActive.Tip();
1995         for (int i = 0; i < 100 && pindex != NULL; i++)
1996         {
1997             if (pindex->nVersion > CBlock::CURRENT_VERSION)
1998                 ++nUpgraded;
1999             pindex = pindex->pprev;
2000         }
2001         if (nUpgraded > 0)
2002             LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
2003         if (nUpgraded > 100/2)
2004         {
2005             // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2006             strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2007             CAlert::Notify(strMiscWarning, true);
2008             fWarned = true;
2009         }
2010     }
2011 }
2012
2013 /** Disconnect chainActive's tip. */
2014 bool static DisconnectTip(CValidationState &state) {
2015     CBlockIndex *pindexDelete = chainActive.Tip();
2016     assert(pindexDelete);
2017     mempool.check(pcoinsTip);
2018     // Read block from disk.
2019     CBlock block;
2020     if (!ReadBlockFromDisk(block, pindexDelete))
2021         return state.Abort("Failed to read block");
2022     // Apply the block atomically to the chain state.
2023     int64_t nStart = GetTimeMicros();
2024     {
2025         CCoinsViewCache view(pcoinsTip);
2026         if (!DisconnectBlock(block, state, pindexDelete, view))
2027             return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2028         assert(view.Flush());
2029     }
2030     LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2031     // Write the chain state to disk, if necessary.
2032     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2033         return false;
2034     // Resurrect mempool transactions from the disconnected block.
2035     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2036         // ignore validation errors in resurrected transactions
2037         list<CTransaction> removed;
2038         CValidationState stateDummy;
2039         if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2040             mempool.remove(tx, removed, true);
2041     }
2042     mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2043     mempool.check(pcoinsTip);
2044     // Update chainActive and related variables.
2045     UpdateTip(pindexDelete->pprev);
2046     // Let wallets know transactions went from 1-confirmed to
2047     // 0-confirmed or conflicted:
2048     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2049         SyncWithWallets(tx, NULL);
2050     }
2051     return true;
2052 }
2053
2054 static int64_t nTimeReadFromDisk = 0;
2055 static int64_t nTimeConnectTotal = 0;
2056 static int64_t nTimeFlush = 0;
2057 static int64_t nTimeChainState = 0;
2058 static int64_t nTimePostConnect = 0;
2059
2060 /** 
2061  * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2062  * corresponding to pindexNew, to bypass loading it again from disk.
2063  */
2064 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2065     assert(pindexNew->pprev == chainActive.Tip());
2066     mempool.check(pcoinsTip);
2067     // Read block from disk.
2068     int64_t nTime1 = GetTimeMicros();
2069     CBlock block;
2070     if (!pblock) {
2071         if (!ReadBlockFromDisk(block, pindexNew))
2072             return state.Abort("Failed to read block");
2073         pblock = &block;
2074     }
2075     // Apply the block atomically to the chain state.
2076     int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2077     int64_t nTime3;
2078     LogPrint("bench", "  - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2079     {
2080         CCoinsViewCache view(pcoinsTip);
2081         CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2082         bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2083         g_signals.BlockChecked(*pblock, state);
2084         if (!rv) {
2085             if (state.IsInvalid())
2086                 InvalidBlockFound(pindexNew, state);
2087             return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2088         }
2089         mapBlockSource.erase(inv.hash);
2090         nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2091         LogPrint("bench", "  - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2092         assert(view.Flush());
2093     }
2094     int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2095     LogPrint("bench", "  - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2096     // Write the chain state to disk, if necessary.
2097     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2098         return false;
2099     int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2100     LogPrint("bench", "  - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2101     // Remove conflicting transactions from the mempool.
2102     list<CTransaction> txConflicted;
2103     mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
2104     mempool.check(pcoinsTip);
2105     // Update chainActive & related variables.
2106     UpdateTip(pindexNew);
2107     // Tell wallet about transactions that went from mempool
2108     // to conflicted:
2109     BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2110         SyncWithWallets(tx, NULL);
2111     }
2112     // ... and about transactions that got confirmed:
2113     BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2114         SyncWithWallets(tx, pblock);
2115     }
2116
2117     int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2118     LogPrint("bench", "  - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2119     LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2120     return true;
2121 }
2122
2123 /**
2124  * Return the tip of the chain with the most work in it, that isn't
2125  * known to be invalid (it's however far from certain to be valid).
2126  */
2127 static CBlockIndex* FindMostWorkChain() {
2128     do {
2129         CBlockIndex *pindexNew = NULL;
2130
2131         // Find the best candidate header.
2132         {
2133             std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2134             if (it == setBlockIndexCandidates.rend())
2135                 return NULL;
2136             pindexNew = *it;
2137         }
2138
2139         // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2140         // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2141         CBlockIndex *pindexTest = pindexNew;
2142         bool fInvalidAncestor = false;
2143         while (pindexTest && !chainActive.Contains(pindexTest)) {
2144             assert(pindexTest->nStatus & BLOCK_HAVE_DATA);
2145             assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2146             if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
2147                 // Candidate has an invalid ancestor, remove entire chain from the set.
2148                 if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
2149                     pindexBestInvalid = pindexNew;
2150                 CBlockIndex *pindexFailed = pindexNew;
2151                 while (pindexTest != pindexFailed) {
2152                     pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2153                     setBlockIndexCandidates.erase(pindexFailed);
2154                     pindexFailed = pindexFailed->pprev;
2155                 }
2156                 setBlockIndexCandidates.erase(pindexTest);
2157                 fInvalidAncestor = true;
2158                 break;
2159             }
2160             pindexTest = pindexTest->pprev;
2161         }
2162         if (!fInvalidAncestor)
2163             return pindexNew;
2164     } while(true);
2165 }
2166
2167 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2168 static void PruneBlockIndexCandidates() {
2169     // Note that we can't delete the current block itself, as we may need to return to it later in case a
2170     // reorganization to a better block fails.
2171     std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2172     while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2173         setBlockIndexCandidates.erase(it++);
2174     }
2175     // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2176     assert(!setBlockIndexCandidates.empty());
2177 }
2178
2179 /**
2180  * Try to make some progress towards making pindexMostWork the active block.
2181  * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2182  */
2183 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2184     AssertLockHeld(cs_main);
2185     bool fInvalidFound = false;
2186     const CBlockIndex *pindexOldTip = chainActive.Tip();
2187     const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2188
2189     // Disconnect active blocks which are no longer in the best chain.
2190     while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2191         if (!DisconnectTip(state))
2192             return false;
2193     }
2194
2195     // Build list of new blocks to connect.
2196     std::vector<CBlockIndex*> vpindexToConnect;
2197     bool fContinue = true;
2198     int nHeight = pindexFork ? pindexFork->nHeight : -1;
2199     while (fContinue && nHeight != pindexMostWork->nHeight) {
2200     // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2201     // a few blocks along the way.
2202     int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2203     vpindexToConnect.clear();
2204     vpindexToConnect.reserve(nTargetHeight - nHeight);
2205     CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2206     while (pindexIter && pindexIter->nHeight != nHeight) {
2207         vpindexToConnect.push_back(pindexIter);
2208         pindexIter = pindexIter->pprev;
2209     }
2210     nHeight = nTargetHeight;
2211
2212     // Connect new blocks.
2213     BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2214         if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2215             if (state.IsInvalid()) {
2216                 // The block violates a consensus rule.
2217                 if (!state.CorruptionPossible())
2218                     InvalidChainFound(vpindexToConnect.back());
2219                 state = CValidationState();
2220                 fInvalidFound = true;
2221                 fContinue = false;
2222                 break;
2223             } else {
2224                 // A system error occurred (disk space, database error, ...).
2225                 return false;
2226             }
2227         } else {
2228             PruneBlockIndexCandidates();
2229             if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2230                 // We're in a better position than we were. Return temporarily to release the lock.
2231                 fContinue = false;
2232                 break;
2233             }
2234         }
2235     }
2236     }
2237
2238     // Callbacks/notifications for a new best chain.
2239     if (fInvalidFound)
2240         CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2241     else
2242         CheckForkWarningConditions();
2243
2244     return true;
2245 }
2246
2247 /**
2248  * Make the best chain active, in multiple steps. The result is either failure
2249  * or an activated best chain. pblock is either NULL or a pointer to a block
2250  * that is already loaded (to avoid loading it again from disk).
2251  */
2252 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2253     CBlockIndex *pindexNewTip = NULL;
2254     CBlockIndex *pindexMostWork = NULL;
2255     do {
2256         boost::this_thread::interruption_point();
2257
2258         bool fInitialDownload;
2259         {
2260             LOCK(cs_main);
2261             pindexMostWork = FindMostWorkChain();
2262
2263             // Whether we have anything to do at all.
2264             if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2265                 return true;
2266
2267             if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2268                 return false;
2269
2270             pindexNewTip = chainActive.Tip();
2271             fInitialDownload = IsInitialBlockDownload();
2272         }
2273         // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2274
2275         // Notifications/callbacks that can run without cs_main
2276         if (!fInitialDownload) {
2277             uint256 hashNewTip = pindexNewTip->GetBlockHash();
2278             // Relay inventory, but don't relay old inventory during initial block download.
2279             int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2280             {
2281                 LOCK(cs_vNodes);
2282                 BOOST_FOREACH(CNode* pnode, vNodes)
2283                     if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2284                         pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2285             }
2286             // Notify external listeners about the new tip.
2287             uiInterface.NotifyBlockTip(hashNewTip);
2288         }
2289     } while(pindexMostWork != chainActive.Tip());
2290
2291     // Write changes periodically to disk, after relay.
2292     if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2293         return false;
2294     }
2295
2296     return true;
2297 }
2298
2299 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2300     AssertLockHeld(cs_main);
2301
2302     // Mark the block itself as invalid.
2303     pindex->nStatus |= BLOCK_FAILED_VALID;
2304     setDirtyBlockIndex.insert(pindex);
2305     setBlockIndexCandidates.erase(pindex);
2306
2307     while (chainActive.Contains(pindex)) {
2308         CBlockIndex *pindexWalk = chainActive.Tip();
2309         pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2310         setDirtyBlockIndex.insert(pindexWalk);
2311         setBlockIndexCandidates.erase(pindexWalk);
2312         // ActivateBestChain considers blocks already in chainActive
2313         // unconditionally valid already, so force disconnect away from it.
2314         if (!DisconnectTip(state)) {
2315             return false;
2316         }
2317     }
2318
2319     // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2320     // add them again.
2321     BlockMap::iterator it = mapBlockIndex.begin();
2322     while (it != mapBlockIndex.end()) {
2323         if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2324             setBlockIndexCandidates.insert(it->second);
2325         }
2326         it++;
2327     }
2328
2329     InvalidChainFound(pindex);
2330     return true;
2331 }
2332
2333 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2334     AssertLockHeld(cs_main);
2335
2336     int nHeight = pindex->nHeight;
2337
2338     // Remove the invalidity flag from this block and all its descendants.
2339     BlockMap::iterator it = mapBlockIndex.begin();
2340     while (it != mapBlockIndex.end()) {
2341         if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2342             it->second->nStatus &= ~BLOCK_FAILED_MASK;
2343             setDirtyBlockIndex.insert(it->second);
2344             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2345                 setBlockIndexCandidates.insert(it->second);
2346             }
2347             if (it->second == pindexBestInvalid) {
2348                 // Reset invalid block marker if it was pointing to one of those.
2349                 pindexBestInvalid = NULL;
2350             }
2351         }
2352         it++;
2353     }
2354
2355     // Remove the invalidity flag from all ancestors too.
2356     while (pindex != NULL) {
2357         if (pindex->nStatus & BLOCK_FAILED_MASK) {
2358             pindex->nStatus &= ~BLOCK_FAILED_MASK;
2359             setDirtyBlockIndex.insert(pindex);
2360         }
2361         pindex = pindex->pprev;
2362     }
2363     return true;
2364 }
2365
2366 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2367 {
2368     // Check for duplicate
2369     uint256 hash = block.GetHash();
2370     BlockMap::iterator it = mapBlockIndex.find(hash);
2371     if (it != mapBlockIndex.end())
2372         return it->second;
2373
2374     // Construct new block index object
2375     CBlockIndex* pindexNew = new CBlockIndex(block);
2376     assert(pindexNew);
2377     // We assign the sequence id to blocks only when the full data is available,
2378     // to avoid miners withholding blocks but broadcasting headers, to get a
2379     // competitive advantage.
2380     pindexNew->nSequenceId = 0;
2381     BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2382     pindexNew->phashBlock = &((*mi).first);
2383     BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2384     if (miPrev != mapBlockIndex.end())
2385     {
2386         pindexNew->pprev = (*miPrev).second;
2387         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2388         pindexNew->BuildSkip();
2389     }
2390     pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2391     pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2392     if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2393         pindexBestHeader = pindexNew;
2394
2395     setDirtyBlockIndex.insert(pindexNew);
2396
2397     return pindexNew;
2398 }
2399
2400 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2401 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2402 {
2403     pindexNew->nTx = block.vtx.size();
2404     pindexNew->nChainTx = 0;
2405     pindexNew->nFile = pos.nFile;
2406     pindexNew->nDataPos = pos.nPos;
2407     pindexNew->nUndoPos = 0;
2408     pindexNew->nStatus |= BLOCK_HAVE_DATA;
2409     pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2410     {
2411          LOCK(cs_nBlockSequenceId);
2412          pindexNew->nSequenceId = nBlockSequenceId++;
2413     }
2414     setDirtyBlockIndex.insert(pindexNew);
2415
2416     if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2417         // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2418         deque<CBlockIndex*> queue;
2419         queue.push_back(pindexNew);
2420
2421         // Recursively process any descendant blocks that now may be eligible to be connected.
2422         while (!queue.empty()) {
2423             CBlockIndex *pindex = queue.front();
2424             queue.pop_front();
2425             pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2426             setBlockIndexCandidates.insert(pindex);
2427             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2428             while (range.first != range.second) {
2429                 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2430                 queue.push_back(it->second);
2431                 range.first++;
2432                 mapBlocksUnlinked.erase(it);
2433             }
2434         }
2435     } else {
2436         if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2437             mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2438         }
2439     }
2440
2441     return true;
2442 }
2443
2444 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2445 {
2446     LOCK(cs_LastBlockFile);
2447
2448     unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2449     if (vinfoBlockFile.size() <= nFile) {
2450         vinfoBlockFile.resize(nFile + 1);
2451     }
2452
2453     if (!fKnown) {
2454         while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2455             LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2456             FlushBlockFile(true);
2457             nFile++;
2458             if (vinfoBlockFile.size() <= nFile) {
2459                 vinfoBlockFile.resize(nFile + 1);
2460             }
2461         }
2462         pos.nFile = nFile;
2463         pos.nPos = vinfoBlockFile[nFile].nSize;
2464     }
2465
2466     nLastBlockFile = nFile;
2467     vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2468     if (fKnown)
2469         vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2470     else
2471         vinfoBlockFile[nFile].nSize += nAddSize;
2472
2473     if (!fKnown) {
2474         unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2475         unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2476         if (nNewChunks > nOldChunks) {
2477             if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2478                 FILE *file = OpenBlockFile(pos);
2479                 if (file) {
2480                     LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2481                     AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2482                     fclose(file);
2483                 }
2484             }
2485             else
2486                 return state.Error("out of disk space");
2487         }
2488     }
2489
2490     setDirtyFileInfo.insert(nFile);
2491     return true;
2492 }
2493
2494 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2495 {
2496     pos.nFile = nFile;
2497
2498     LOCK(cs_LastBlockFile);
2499
2500     unsigned int nNewSize;
2501     pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2502     nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2503     setDirtyFileInfo.insert(nFile);
2504
2505     unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2506     unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2507     if (nNewChunks > nOldChunks) {
2508         if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2509             FILE *file = OpenUndoFile(pos);
2510             if (file) {
2511                 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2512                 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2513                 fclose(file);
2514             }
2515         }
2516         else
2517             return state.Error("out of disk space");
2518     }
2519
2520     return true;
2521 }
2522
2523 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2524 {
2525     // Check proof of work matches claimed amount
2526     if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2527         return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2528                          REJECT_INVALID, "high-hash");
2529
2530     // Check timestamp
2531     if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2532         return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2533                              REJECT_INVALID, "time-too-new");
2534
2535     return true;
2536 }
2537
2538 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2539 {
2540     // These are checks that are independent of context.
2541
2542     // Check that the header is valid (particularly PoW).  This is mostly
2543     // redundant with the call in AcceptBlockHeader.
2544     if (!CheckBlockHeader(block, state, fCheckPOW))
2545         return false;
2546
2547     // Check the merkle root.
2548     if (fCheckMerkleRoot) {
2549         bool mutated;
2550         uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2551         if (block.hashMerkleRoot != hashMerkleRoot2)
2552             return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2553                              REJECT_INVALID, "bad-txnmrklroot", true);
2554
2555         // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2556         // of transactions in a block without affecting the merkle root of a block,
2557         // while still invalidating it.
2558         if (mutated)
2559             return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2560                              REJECT_INVALID, "bad-txns-duplicate", true);
2561     }
2562
2563     // All potential-corruption validation must be done before we do any
2564     // transaction validation, as otherwise we may mark the header as invalid
2565     // because we receive the wrong transactions for it.
2566
2567     // Size limits
2568     if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2569         return state.DoS(100, error("CheckBlock(): size limits failed"),
2570                          REJECT_INVALID, "bad-blk-length");
2571
2572     // First transaction must be coinbase, the rest must not be
2573     if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2574         return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2575                          REJECT_INVALID, "bad-cb-missing");
2576     for (unsigned int i = 1; i < block.vtx.size(); i++)
2577         if (block.vtx[i].IsCoinBase())
2578             return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2579                              REJECT_INVALID, "bad-cb-multiple");
2580
2581     // Check transactions
2582     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2583         if (!CheckTransaction(tx, state))
2584             return error("CheckBlock(): CheckTransaction failed");
2585
2586     unsigned int nSigOps = 0;
2587     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2588     {
2589         nSigOps += GetLegacySigOpCount(tx);
2590     }
2591     if (nSigOps > MAX_BLOCK_SIGOPS)
2592         return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2593                          REJECT_INVALID, "bad-blk-sigops", true);
2594
2595     return true;
2596 }
2597
2598 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2599 {
2600     uint256 hash = block.GetHash();
2601     if (hash == Params().HashGenesisBlock())
2602         return true;
2603
2604     assert(pindexPrev);
2605
2606     int nHeight = pindexPrev->nHeight+1;
2607
2608     // Check proof of work
2609     if ((block.nBits != GetNextWorkRequired(pindexPrev, &block)))
2610         return state.DoS(100, error("%s: incorrect proof of work", __func__),
2611                          REJECT_INVALID, "bad-diffbits");
2612
2613     // Check timestamp against prev
2614     if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2615         return state.Invalid(error("%s: block's timestamp is too early", __func__),
2616                              REJECT_INVALID, "time-too-old");
2617
2618     // Check that the block chain matches the known block chain up to a checkpoint
2619     if (!Checkpoints::CheckBlock(nHeight, hash))
2620         return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
2621                          REJECT_CHECKPOINT, "checkpoint mismatch");
2622
2623     // Don't accept any forks from the main chain prior to last checkpoint
2624     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
2625     if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2626         return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2627
2628     // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2629     if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
2630     {
2631         return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2632                              REJECT_OBSOLETE, "bad-version");
2633     }
2634
2635     // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2636     if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority()))
2637     {
2638         return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2639                              REJECT_OBSOLETE, "bad-version");
2640     }
2641
2642     return true;
2643 }
2644
2645 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2646 {
2647     const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2648
2649     // Check that all transactions are finalized
2650     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2651         if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2652             return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2653         }
2654
2655     // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2656     // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2657     if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority()))
2658     {
2659         CScript expect = CScript() << nHeight;
2660         if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2661             !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2662             return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2663         }
2664     }
2665
2666     return true;
2667 }
2668
2669 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2670 {
2671     AssertLockHeld(cs_main);
2672     // Check for duplicate
2673     uint256 hash = block.GetHash();
2674     BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2675     CBlockIndex *pindex = NULL;
2676     if (miSelf != mapBlockIndex.end()) {
2677         // Block header is already known.
2678         pindex = miSelf->second;
2679         if (ppindex)
2680             *ppindex = pindex;
2681         if (pindex->nStatus & BLOCK_FAILED_MASK)
2682             return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2683         return true;
2684     }
2685
2686     if (!CheckBlockHeader(block, state))
2687         return false;
2688
2689     // Get prev block index
2690     CBlockIndex* pindexPrev = NULL;
2691     if (hash != Params().HashGenesisBlock()) {
2692         BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2693         if (mi == mapBlockIndex.end())
2694             return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2695         pindexPrev = (*mi).second;
2696         if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2697             return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2698     }
2699
2700     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2701         return false;
2702
2703     if (pindex == NULL)
2704         pindex = AddToBlockIndex(block);
2705
2706     if (ppindex)
2707         *ppindex = pindex;
2708
2709     return true;
2710 }
2711
2712 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2713 {
2714     AssertLockHeld(cs_main);
2715
2716     CBlockIndex *&pindex = *ppindex;
2717
2718     if (!AcceptBlockHeader(block, state, &pindex))
2719         return false;
2720
2721     if (pindex->nStatus & BLOCK_HAVE_DATA) {
2722         // TODO: deal better with duplicate blocks.
2723         // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2724         return true;
2725     }
2726
2727     if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2728         if (state.IsInvalid() && !state.CorruptionPossible()) {
2729             pindex->nStatus |= BLOCK_FAILED_VALID;
2730             setDirtyBlockIndex.insert(pindex);
2731         }
2732         return false;
2733     }
2734
2735     int nHeight = pindex->nHeight;
2736
2737     // Write block to history file
2738     try {
2739         unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2740         CDiskBlockPos blockPos;
2741         if (dbp != NULL)
2742             blockPos = *dbp;
2743         if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2744             return error("AcceptBlock(): FindBlockPos failed");
2745         if (dbp == NULL)
2746             if (!WriteBlockToDisk(block, blockPos))
2747                 return state.Abort("Failed to write block");
2748         if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2749             return error("AcceptBlock(): ReceivedBlockTransactions failed");
2750     } catch (const std::runtime_error& e) {
2751         return state.Abort(std::string("System error: ") + e.what());
2752     }
2753
2754     return true;
2755 }
2756
2757 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
2758 {
2759     unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
2760     unsigned int nFound = 0;
2761     for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2762     {
2763         if (pstart->nVersion >= minVersion)
2764             ++nFound;
2765         pstart = pstart->pprev;
2766     }
2767     return (nFound >= nRequired);
2768 }
2769
2770
2771 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2772 {
2773     // Preliminary checks
2774     bool checked = CheckBlock(*pblock, state);
2775
2776     {
2777         LOCK(cs_main);
2778         MarkBlockAsReceived(pblock->GetHash());
2779         if (!checked) {
2780             return error("%s: CheckBlock FAILED", __func__);
2781         }
2782
2783         // Store to disk
2784         CBlockIndex *pindex = NULL;
2785         bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2786         if (pindex && pfrom) {
2787             mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2788         }
2789         if (!ret)
2790             return error("%s: AcceptBlock FAILED", __func__);
2791     }
2792
2793     if (!ActivateBestChain(state, pblock))
2794         return error("%s: ActivateBestChain failed", __func__);
2795
2796     return true;
2797 }
2798
2799 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2800 {
2801     AssertLockHeld(cs_main);
2802     assert(pindexPrev == chainActive.Tip());
2803
2804     CCoinsViewCache viewNew(pcoinsTip);
2805     CBlockIndex indexDummy(block);
2806     indexDummy.pprev = pindexPrev;
2807     indexDummy.nHeight = pindexPrev->nHeight + 1;
2808
2809     // NOTE: CheckBlockHeader is called by CheckBlock
2810     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2811         return false;
2812     if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2813         return false;
2814     if (!ContextualCheckBlock(block, state, pindexPrev))
2815         return false;
2816     if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2817         return false;
2818     assert(state.IsValid());
2819
2820     return true;
2821 }
2822
2823
2824
2825
2826
2827
2828
2829
2830 bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
2831     strMiscWarning = strMessage;
2832     LogPrintf("*** %s\n", strMessage);
2833     uiInterface.ThreadSafeMessageBox(
2834         userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
2835         "", CClientUIInterface::MSG_ERROR);
2836     StartShutdown();
2837     return false;
2838 }
2839
2840 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2841 {
2842     uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2843
2844     // Check for nMinDiskSpace bytes (currently 50MB)
2845     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2846         return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
2847
2848     return true;
2849 }
2850
2851 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2852 {
2853     if (pos.IsNull())
2854         return NULL;
2855     boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
2856     boost::filesystem::create_directories(path.parent_path());
2857     FILE* file = fopen(path.string().c_str(), "rb+");
2858     if (!file && !fReadOnly)
2859         file = fopen(path.string().c_str(), "wb+");
2860     if (!file) {
2861         LogPrintf("Unable to open file %s\n", path.string());
2862         return NULL;
2863     }
2864     if (pos.nPos) {
2865         if (fseek(file, pos.nPos, SEEK_SET)) {
2866             LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
2867             fclose(file);
2868             return NULL;
2869         }
2870     }
2871     return file;
2872 }
2873
2874 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2875     return OpenDiskFile(pos, "blk", fReadOnly);
2876 }
2877
2878 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2879     return OpenDiskFile(pos, "rev", fReadOnly);
2880 }
2881
2882 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
2883 {
2884     return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2885 }
2886
2887 CBlockIndex * InsertBlockIndex(uint256 hash)
2888 {
2889     if (hash.IsNull())
2890         return NULL;
2891
2892     // Return existing
2893     BlockMap::iterator mi = mapBlockIndex.find(hash);
2894     if (mi != mapBlockIndex.end())
2895         return (*mi).second;
2896
2897     // Create new
2898     CBlockIndex* pindexNew = new CBlockIndex();
2899     if (!pindexNew)
2900         throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
2901     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2902     pindexNew->phashBlock = &((*mi).first);
2903
2904     return pindexNew;
2905 }
2906
2907 bool static LoadBlockIndexDB()
2908 {
2909     if (!pblocktree->LoadBlockIndexGuts())
2910         return false;
2911
2912     boost::this_thread::interruption_point();
2913
2914     // Calculate nChainWork
2915     vector<pair<int, CBlockIndex*> > vSortedByHeight;
2916     vSortedByHeight.reserve(mapBlockIndex.size());
2917     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2918     {
2919         CBlockIndex* pindex = item.second;
2920         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2921     }
2922     sort(vSortedByHeight.begin(), vSortedByHeight.end());
2923     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2924     {
2925         CBlockIndex* pindex = item.second;
2926         pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
2927         if (pindex->nStatus & BLOCK_HAVE_DATA) {
2928             if (pindex->pprev) {
2929                 if (pindex->pprev->nChainTx) {
2930                     pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
2931                 } else {
2932                     pindex->nChainTx = 0;
2933                     mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
2934                 }
2935             } else {
2936                 pindex->nChainTx = pindex->nTx;
2937             }
2938         }
2939         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
2940             setBlockIndexCandidates.insert(pindex);
2941         if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
2942             pindexBestInvalid = pindex;
2943         if (pindex->pprev)
2944             pindex->BuildSkip();
2945         if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
2946             pindexBestHeader = pindex;
2947     }
2948
2949     // Load block file info
2950     pblocktree->ReadLastBlockFile(nLastBlockFile);
2951     vinfoBlockFile.resize(nLastBlockFile + 1);
2952     LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
2953     for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
2954         pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
2955     }
2956     LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
2957     for (int nFile = nLastBlockFile + 1; true; nFile++) {
2958         CBlockFileInfo info;
2959         if (pblocktree->ReadBlockFileInfo(nFile, info)) {
2960             vinfoBlockFile.push_back(info);
2961         } else {
2962             break;
2963         }
2964     }
2965
2966     // Check presence of blk files
2967     LogPrintf("Checking all blk files are present...\n");
2968     set<int> setBlkDataFiles;
2969     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2970     {
2971         CBlockIndex* pindex = item.second;
2972         if (pindex->nStatus & BLOCK_HAVE_DATA) {
2973             setBlkDataFiles.insert(pindex->nFile);
2974         }
2975     }
2976     for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
2977     {
2978         CDiskBlockPos pos(*it, 0);
2979         if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
2980             return false;
2981         }
2982     }
2983
2984     // Check whether we need to continue reindexing
2985     bool fReindexing = false;
2986     pblocktree->ReadReindexing(fReindexing);
2987     fReindex |= fReindexing;
2988
2989     // Check whether we have a transaction index
2990     pblocktree->ReadFlag("txindex", fTxIndex);
2991     LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2992
2993     // Load pointer to end of best chain
2994     BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
2995     if (it == mapBlockIndex.end())
2996         return true;
2997     chainActive.SetTip(it->second);
2998
2999     PruneBlockIndexCandidates();
3000
3001     LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
3002         chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3003         DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3004         Checkpoints::GuessVerificationProgress(chainActive.Tip()));
3005
3006     return true;
3007 }
3008
3009 CVerifyDB::CVerifyDB()
3010 {
3011     uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3012 }
3013
3014 CVerifyDB::~CVerifyDB()
3015 {
3016     uiInterface.ShowProgress("", 100);
3017 }
3018
3019 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3020 {
3021     LOCK(cs_main);
3022     if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3023         return true;
3024
3025     // Verify blocks in the best chain
3026     if (nCheckDepth <= 0)
3027         nCheckDepth = 1000000000; // suffices until the year 19000
3028     if (nCheckDepth > chainActive.Height())
3029         nCheckDepth = chainActive.Height();
3030     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3031     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3032     CCoinsViewCache coins(coinsview);
3033     CBlockIndex* pindexState = chainActive.Tip();
3034     CBlockIndex* pindexFailure = NULL;
3035     int nGoodTransactions = 0;
3036     CValidationState state;
3037     for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3038     {
3039         boost::this_thread::interruption_point();
3040         uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3041         if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3042             break;
3043         CBlock block;
3044         // check level 0: read from disk
3045         if (!ReadBlockFromDisk(block, pindex))
3046             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3047         // check level 1: verify block validity
3048         if (nCheckLevel >= 1 && !CheckBlock(block, state))
3049             return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3050         // check level 2: verify undo validity
3051         if (nCheckLevel >= 2 && pindex) {
3052             CBlockUndo undo;
3053             CDiskBlockPos pos = pindex->GetUndoPos();
3054             if (!pos.IsNull()) {
3055                 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3056                     return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3057             }
3058         }
3059         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3060         if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
3061             bool fClean = true;
3062             if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3063                 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3064             pindexState = pindex->pprev;
3065             if (!fClean) {
3066                 nGoodTransactions = 0;
3067                 pindexFailure = pindex;
3068             } else
3069                 nGoodTransactions += block.vtx.size();
3070         }
3071         if (ShutdownRequested())
3072             return true;
3073     }
3074     if (pindexFailure)
3075         return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3076
3077     // check level 4: try reconnecting blocks
3078     if (nCheckLevel >= 4) {
3079         CBlockIndex *pindex = pindexState;
3080         while (pindex != chainActive.Tip()) {
3081             boost::this_thread::interruption_point();
3082             uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3083             pindex = chainActive.Next(pindex);
3084             CBlock block;
3085             if (!ReadBlockFromDisk(block, pindex))
3086                 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3087             if (!ConnectBlock(block, state, pindex, coins))
3088                 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3089         }
3090     }
3091
3092     LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3093
3094     return true;
3095 }
3096
3097 void UnloadBlockIndex()
3098 {
3099     LOCK(cs_main);
3100     setBlockIndexCandidates.clear();
3101     chainActive.SetTip(NULL);
3102     pindexBestInvalid = NULL;
3103     pindexBestHeader = NULL;
3104     mempool.clear();
3105     mapOrphanTransactions.clear();
3106     mapOrphanTransactionsByPrev.clear();
3107     nSyncStarted = 0;
3108     mapBlocksUnlinked.clear();
3109     vinfoBlockFile.clear();
3110     nLastBlockFile = 0;
3111     nBlockSequenceId = 1;
3112     mapBlockSource.clear();
3113     mapBlocksInFlight.clear();
3114     nQueuedValidatedHeaders = 0;
3115     nPreferredDownload = 0;
3116     setDirtyBlockIndex.clear();
3117     setDirtyFileInfo.clear();
3118     mapNodeState.clear();
3119
3120     BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3121         delete entry.second;
3122     }
3123     mapBlockIndex.clear();
3124 }
3125
3126 bool LoadBlockIndex()
3127 {
3128     // Load block index from databases
3129     if (!fReindex && !LoadBlockIndexDB())
3130         return false;
3131     return true;
3132 }
3133
3134
3135 bool InitBlockIndex() {
3136     LOCK(cs_main);
3137     // Check whether we're already initialized
3138     if (chainActive.Genesis() != NULL)
3139         return true;
3140
3141     // Use the provided setting for -txindex in the new database
3142     fTxIndex = GetBoolArg("-txindex", false);
3143     pblocktree->WriteFlag("txindex", fTxIndex);
3144     LogPrintf("Initializing databases...\n");
3145
3146     // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3147     if (!fReindex) {
3148         try {
3149             CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3150             // Start new block file
3151             unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3152             CDiskBlockPos blockPos;
3153             CValidationState state;
3154             if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3155                 return error("LoadBlockIndex(): FindBlockPos failed");
3156             if (!WriteBlockToDisk(block, blockPos))
3157                 return error("LoadBlockIndex(): writing genesis block to disk failed");
3158             CBlockIndex *pindex = AddToBlockIndex(block);
3159             if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3160                 return error("LoadBlockIndex(): genesis block not accepted");
3161             if (!ActivateBestChain(state, &block))
3162                 return error("LoadBlockIndex(): genesis block cannot be activated");
3163             // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3164             return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3165         } catch (const std::runtime_error& e) {
3166             return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3167         }
3168     }
3169
3170     return true;
3171 }
3172
3173
3174
3175 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3176 {
3177     // Map of disk positions for blocks with unknown parent (only used for reindex)
3178     static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3179     int64_t nStart = GetTimeMillis();
3180
3181     int nLoaded = 0;
3182     try {
3183         // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3184         CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3185         uint64_t nRewind = blkdat.GetPos();
3186         while (!blkdat.eof()) {
3187             boost::this_thread::interruption_point();
3188
3189             blkdat.SetPos(nRewind);
3190             nRewind++; // start one byte further next time, in case of failure
3191             blkdat.SetLimit(); // remove former limit
3192             unsigned int nSize = 0;
3193             try {
3194                 // locate a header
3195                 unsigned char buf[MESSAGE_START_SIZE];
3196                 blkdat.FindByte(Params().MessageStart()[0]);
3197                 nRewind = blkdat.GetPos()+1;
3198                 blkdat >> FLATDATA(buf);
3199                 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3200                     continue;
3201                 // read size
3202                 blkdat >> nSize;
3203                 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3204                     continue;
3205             } catch (const std::exception&) {
3206                 // no valid block header found; don't complain
3207                 break;
3208             }
3209             try {
3210                 // read block
3211                 uint64_t nBlockPos = blkdat.GetPos();
3212                 if (dbp)
3213                     dbp->nPos = nBlockPos;
3214                 blkdat.SetLimit(nBlockPos + nSize);
3215                 blkdat.SetPos(nBlockPos);
3216                 CBlock block;
3217                 blkdat >> block;
3218                 nRewind = blkdat.GetPos();
3219
3220                 // detect out of order blocks, and store them for later
3221                 uint256 hash = block.GetHash();
3222                 if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3223                     LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3224                             block.hashPrevBlock.ToString());
3225                     if (dbp)
3226                         mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3227                     continue;
3228                 }
3229
3230                 // process in case the block isn't known yet
3231                 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3232                     CValidationState state;
3233                     if (ProcessNewBlock(state, NULL, &block, dbp))
3234                         nLoaded++;
3235                     if (state.IsError())
3236                         break;
3237                 } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3238                     LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3239                 }
3240
3241                 // Recursively process earlier encountered successors of this block
3242                 deque<uint256> queue;
3243                 queue.push_back(hash);
3244                 while (!queue.empty()) {
3245                     uint256 head = queue.front();
3246                     queue.pop_front();
3247                     std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3248                     while (range.first != range.second) {
3249                         std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3250                         if (ReadBlockFromDisk(block, it->second))
3251                         {
3252                             LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3253                                     head.ToString());
3254                             CValidationState dummy;
3255                             if (ProcessNewBlock(dummy, NULL, &block, &it->second))
3256                             {
3257                                 nLoaded++;
3258                                 queue.push_back(block.GetHash());
3259                             }
3260                         }
3261                         range.first++;
3262                         mapBlocksUnknownParent.erase(it);
3263                     }
3264                 }
3265             } catch (const std::exception& e) {
3266                 LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
3267             }
3268         }
3269     } catch (const std::runtime_error& e) {
3270         AbortNode(std::string("System error: ") + e.what());
3271     }
3272     if (nLoaded > 0)
3273         LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3274     return nLoaded > 0;
3275 }
3276
3277 //////////////////////////////////////////////////////////////////////////////
3278 //
3279 // CAlert
3280 //
3281
3282 string GetWarnings(string strFor)
3283 {
3284     int nPriority = 0;
3285     string strStatusBar;
3286     string strRPC;
3287
3288     if (!CLIENT_VERSION_IS_RELEASE)
3289         strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3290
3291     if (GetBoolArg("-testsafemode", false))
3292         strStatusBar = strRPC = "testsafemode enabled";
3293
3294     // Misc warnings like out of disk space and clock is wrong
3295     if (strMiscWarning != "")
3296     {
3297         nPriority = 1000;
3298         strStatusBar = strMiscWarning;
3299     }
3300
3301     if (fLargeWorkForkFound)
3302     {
3303         nPriority = 2000;
3304         strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3305     }
3306     else if (fLargeWorkInvalidChainFound)
3307     {
3308         nPriority = 2000;
3309         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.");
3310     }
3311
3312     // Alerts
3313     {
3314         LOCK(cs_mapAlerts);
3315         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3316         {
3317             const CAlert& alert = item.second;
3318             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3319             {
3320                 nPriority = alert.nPriority;
3321                 strStatusBar = alert.strStatusBar;
3322             }
3323         }
3324     }
3325
3326     if (strFor == "statusbar")
3327         return strStatusBar;
3328     else if (strFor == "rpc")
3329         return strRPC;
3330     assert(!"GetWarnings(): invalid parameter");
3331     return "error";
3332 }
3333
3334
3335
3336
3337
3338
3339
3340
3341 //////////////////////////////////////////////////////////////////////////////
3342 //
3343 // Messages
3344 //
3345
3346
3347 bool static AlreadyHave(const CInv& inv)
3348 {
3349     switch (inv.type)
3350     {
3351     case MSG_TX:
3352         {
3353             bool txInMap = false;
3354             txInMap = mempool.exists(inv.hash);
3355             return txInMap || mapOrphanTransactions.count(inv.hash) ||
3356                 pcoinsTip->HaveCoins(inv.hash);
3357         }
3358     case MSG_BLOCK:
3359         return mapBlockIndex.count(inv.hash);
3360     }
3361     // Don't know what it is, just say we already got one
3362     return true;
3363 }
3364
3365
3366 void static ProcessGetData(CNode* pfrom)
3367 {
3368     std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3369
3370     vector<CInv> vNotFound;
3371
3372     LOCK(cs_main);
3373
3374     while (it != pfrom->vRecvGetData.end()) {
3375         // Don't bother if send buffer is too full to respond anyway
3376         if (pfrom->nSendSize >= SendBufferSize())
3377             break;
3378
3379         const CInv &inv = *it;
3380         {
3381             boost::this_thread::interruption_point();
3382             it++;
3383
3384             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3385             {
3386                 bool send = false;
3387                 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3388                 if (mi != mapBlockIndex.end())
3389                 {
3390                     if (chainActive.Contains(mi->second)) {
3391                         send = true;
3392                     } else {
3393                         // To prevent fingerprinting attacks, only send blocks outside of the active
3394                         // chain if they are valid, and no more than a month older than the best header
3395                         // chain we know about.
3396                         send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3397                             (mi->second->GetBlockTime() > pindexBestHeader->GetBlockTime() - 30 * 24 * 60 * 60);
3398                         if (!send) {
3399                             LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
3400                         }
3401                     }
3402                 }
3403                 if (send)
3404                 {
3405                     // Send block from disk
3406                     CBlock block;
3407                     if (!ReadBlockFromDisk(block, (*mi).second))
3408                         assert(!"cannot load block from disk");
3409                     if (inv.type == MSG_BLOCK)
3410                         pfrom->PushMessage("block", block);
3411                     else // MSG_FILTERED_BLOCK)
3412                     {
3413                         LOCK(pfrom->cs_filter);
3414                         if (pfrom->pfilter)
3415                         {
3416                             CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3417                             pfrom->PushMessage("merkleblock", merkleBlock);
3418                             // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3419                             // This avoids hurting performance by pointlessly requiring a round-trip
3420                             // Note that there is currently no way for a node to request any single transactions we didnt send here -
3421                             // they must either disconnect and retry or request the full block.
3422                             // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3423                             // however we MUST always provide at least what the remote peer needs
3424                             typedef std::pair<unsigned int, uint256> PairType;
3425                             BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3426                                 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3427                                     pfrom->PushMessage("tx", block.vtx[pair.first]);
3428                         }
3429                         // else
3430                             // no response
3431                     }
3432
3433                     // Trigger them to send a getblocks request for the next batch of inventory
3434                     if (inv.hash == pfrom->hashContinue)
3435                     {
3436                         // Bypass PushInventory, this must send even if redundant,
3437                         // and we want it right after the last block so they don't
3438                         // wait for other stuff first.
3439                         vector<CInv> vInv;
3440                         vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3441                         pfrom->PushMessage("inv", vInv);
3442                         pfrom->hashContinue.SetNull();
3443                     }
3444                 }
3445             }
3446             else if (inv.IsKnownType())
3447             {
3448                 // Send stream from relay memory
3449                 bool pushed = false;
3450                 {
3451                     LOCK(cs_mapRelay);
3452                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3453                     if (mi != mapRelay.end()) {
3454                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3455                         pushed = true;
3456                     }
3457                 }
3458                 if (!pushed && inv.type == MSG_TX) {
3459                     CTransaction tx;
3460                     if (mempool.lookup(inv.hash, tx)) {
3461                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3462                         ss.reserve(1000);
3463                         ss << tx;
3464                         pfrom->PushMessage("tx", ss);
3465                         pushed = true;
3466                     }
3467                 }
3468                 if (!pushed) {
3469                     vNotFound.push_back(inv);
3470                 }
3471             }
3472
3473             // Track requests for our stuff.
3474             g_signals.Inventory(inv.hash);
3475
3476             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3477                 break;
3478         }
3479     }
3480
3481     pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3482
3483     if (!vNotFound.empty()) {
3484         // Let the peer know that we didn't find what it asked for, so it doesn't
3485         // have to wait around forever. Currently only SPV clients actually care
3486         // about this message: it's needed when they are recursively walking the
3487         // dependencies of relevant unconfirmed transactions. SPV clients want to
3488         // do that because they want to know about (and store and rebroadcast and
3489         // risk analyze) the dependencies of transactions relevant to them, without
3490         // having to download the entire memory pool.
3491         pfrom->PushMessage("notfound", vNotFound);
3492     }
3493 }
3494
3495 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3496 {
3497     RandAddSeedPerfmon();
3498     LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3499     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3500     {
3501         LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3502         return true;
3503     }
3504
3505
3506
3507
3508     if (strCommand == "version")
3509     {
3510         // Each connection can only send one version message
3511         if (pfrom->nVersion != 0)
3512         {
3513             pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3514             Misbehaving(pfrom->GetId(), 1);
3515             return false;
3516         }
3517
3518         int64_t nTime;
3519         CAddress addrMe;
3520         CAddress addrFrom;
3521         uint64_t nNonce = 1;
3522         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3523         if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3524         {
3525             // disconnect from peers older than this proto version
3526             LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3527             pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3528                                strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3529             pfrom->fDisconnect = true;
3530             return false;
3531         }
3532
3533         if (pfrom->nVersion == 10300)
3534             pfrom->nVersion = 300;
3535         if (!vRecv.empty())
3536             vRecv >> addrFrom >> nNonce;
3537         if (!vRecv.empty()) {
3538             vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3539             pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3540         }
3541         if (!vRecv.empty())
3542             vRecv >> pfrom->nStartingHeight;
3543         if (!vRecv.empty())
3544             vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3545         else
3546             pfrom->fRelayTxes = true;
3547
3548         // Disconnect if we connected to ourself
3549         if (nNonce == nLocalHostNonce && nNonce > 1)
3550         {
3551             LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3552             pfrom->fDisconnect = true;
3553             return true;
3554         }
3555
3556         pfrom->addrLocal = addrMe;
3557         if (pfrom->fInbound && addrMe.IsRoutable())
3558         {
3559             SeenLocal(addrMe);
3560         }
3561
3562         // Be shy and don't send version until we hear
3563         if (pfrom->fInbound)
3564             pfrom->PushVersion();
3565
3566         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3567
3568         // Potentially mark this peer as a preferred download peer.
3569         UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3570
3571         // Change version
3572         pfrom->PushMessage("verack");
3573         pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3574
3575         if (!pfrom->fInbound)
3576         {
3577             // Advertise our address
3578             if (fListen && !IsInitialBlockDownload())
3579             {
3580                 CAddress addr = GetLocalAddress(&pfrom->addr);
3581                 if (addr.IsRoutable())
3582                 {
3583                     pfrom->PushAddress(addr);
3584                 } else if (IsPeerAddrLocalGood(pfrom)) {
3585                     addr.SetIP(pfrom->addrLocal);
3586                     pfrom->PushAddress(addr);
3587                 }
3588             }
3589
3590             // Get recent addresses
3591             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3592             {
3593                 pfrom->PushMessage("getaddr");
3594                 pfrom->fGetAddr = true;
3595             }
3596             addrman.Good(pfrom->addr);
3597         } else {
3598             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3599             {
3600                 addrman.Add(addrFrom, addrFrom);
3601                 addrman.Good(addrFrom);
3602             }
3603         }
3604
3605         // Relay alerts
3606         {
3607             LOCK(cs_mapAlerts);
3608             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3609                 item.second.RelayTo(pfrom);
3610         }
3611
3612         pfrom->fSuccessfullyConnected = true;
3613
3614         string remoteAddr;
3615         if (fLogIPs)
3616             remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
3617
3618         LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
3619                   pfrom->cleanSubVer, pfrom->nVersion,
3620                   pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
3621                   remoteAddr);
3622
3623         int64_t nTimeOffset = nTime - GetTime();
3624         pfrom->nTimeOffset = nTimeOffset;
3625         AddTimeData(pfrom->addr, nTimeOffset);
3626     }
3627
3628
3629     else if (pfrom->nVersion == 0)
3630     {
3631         // Must have a version message before anything else
3632         Misbehaving(pfrom->GetId(), 1);
3633         return false;
3634     }
3635
3636
3637     else if (strCommand == "verack")
3638     {
3639         pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3640
3641         // Mark this node as currently connected, so we update its timestamp later.
3642         if (pfrom->fNetworkNode) {
3643             LOCK(cs_main);
3644             State(pfrom->GetId())->fCurrentlyConnected = true;
3645         }
3646     }
3647
3648
3649     else if (strCommand == "addr")
3650     {
3651         vector<CAddress> vAddr;
3652         vRecv >> vAddr;
3653
3654         // Don't want addr from older versions unless seeding
3655         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3656             return true;
3657         if (vAddr.size() > 1000)
3658         {
3659             Misbehaving(pfrom->GetId(), 20);
3660             return error("message addr size() = %u", vAddr.size());
3661         }
3662
3663         // Store the new addresses
3664         vector<CAddress> vAddrOk;
3665         int64_t nNow = GetAdjustedTime();
3666         int64_t nSince = nNow - 10 * 60;
3667         BOOST_FOREACH(CAddress& addr, vAddr)
3668         {
3669             boost::this_thread::interruption_point();
3670
3671             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3672                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3673             pfrom->AddAddressKnown(addr);
3674             bool fReachable = IsReachable(addr);
3675             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3676             {
3677                 // Relay to a limited number of other nodes
3678                 {
3679                     LOCK(cs_vNodes);
3680                     // Use deterministic randomness to send to the same nodes for 24 hours
3681                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3682                     static uint256 hashSalt;
3683                     if (hashSalt.IsNull())
3684                         hashSalt = GetRandHash();
3685                     uint64_t hashAddr = addr.GetHash();
3686                     uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
3687                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3688                     multimap<uint256, CNode*> mapMix;
3689                     BOOST_FOREACH(CNode* pnode, vNodes)
3690                     {
3691                         if (pnode->nVersion < CADDR_TIME_VERSION)
3692                             continue;
3693                         unsigned int nPointer;
3694                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3695                         uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
3696                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3697                         mapMix.insert(make_pair(hashKey, pnode));
3698                     }
3699                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3700                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3701                         ((*mi).second)->PushAddress(addr);
3702                 }
3703             }
3704             // Do not store addresses outside our network
3705             if (fReachable)
3706                 vAddrOk.push_back(addr);
3707         }
3708         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3709         if (vAddr.size() < 1000)
3710             pfrom->fGetAddr = false;
3711         if (pfrom->fOneShot)
3712             pfrom->fDisconnect = true;
3713     }
3714
3715
3716     else if (strCommand == "inv")
3717     {
3718         vector<CInv> vInv;
3719         vRecv >> vInv;
3720         if (vInv.size() > MAX_INV_SZ)
3721         {
3722             Misbehaving(pfrom->GetId(), 20);
3723             return error("message inv size() = %u", vInv.size());
3724         }
3725
3726         LOCK(cs_main);
3727
3728         std::vector<CInv> vToFetch;
3729
3730         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3731         {
3732             const CInv &inv = vInv[nInv];
3733
3734             boost::this_thread::interruption_point();
3735             pfrom->AddInventoryKnown(inv);
3736
3737             bool fAlreadyHave = AlreadyHave(inv);
3738             LogPrint("net", "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
3739
3740             if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
3741                 pfrom->AskFor(inv);
3742
3743             if (inv.type == MSG_BLOCK) {
3744                 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
3745                 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
3746                     // First request the headers preceeding the announced block. In the normal fully-synced
3747                     // case where a new block is announced that succeeds the current tip (no reorganization),
3748                     // there are no such headers.
3749                     // Secondly, and only when we are close to being synced, we request the announced block directly,
3750                     // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
3751                     // time the block arrives, the header chain leading up to it is already validated. Not
3752                     // doing this will result in the received block being rejected as an orphan in case it is
3753                     // not a direct successor.
3754                     pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
3755                     CNodeState *nodestate = State(pfrom->GetId());
3756                     if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - Params().TargetSpacing() * 20 &&
3757                         nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3758                         vToFetch.push_back(inv);
3759                         // Mark block as in flight already, even though the actual "getdata" message only goes out
3760                         // later (within the same cs_main lock, though).
3761                         MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
3762                     }
3763                     LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
3764                 }
3765             }
3766
3767             // Track requests for our stuff
3768             g_signals.Inventory(inv.hash);
3769
3770             if (pfrom->nSendSize > (SendBufferSize() * 2)) {
3771                 Misbehaving(pfrom->GetId(), 50);
3772                 return error("send buffer size() = %u", pfrom->nSendSize);
3773             }
3774         }
3775
3776         if (!vToFetch.empty())
3777             pfrom->PushMessage("getdata", vToFetch);
3778     }
3779
3780
3781     else if (strCommand == "getdata")
3782     {
3783         vector<CInv> vInv;
3784         vRecv >> vInv;
3785         if (vInv.size() > MAX_INV_SZ)
3786         {
3787             Misbehaving(pfrom->GetId(), 20);
3788             return error("message getdata size() = %u", vInv.size());
3789         }
3790
3791         if (fDebug || (vInv.size() != 1))
3792             LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
3793
3794         if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
3795             LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
3796
3797         pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3798         ProcessGetData(pfrom);
3799     }
3800
3801
3802     else if (strCommand == "getblocks")
3803     {
3804         CBlockLocator locator;
3805         uint256 hashStop;
3806         vRecv >> locator >> hashStop;
3807
3808         LOCK(cs_main);
3809
3810         // Find the last block the caller has in the main chain
3811         CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
3812
3813         // Send the rest of the chain
3814         if (pindex)
3815             pindex = chainActive.Next(pindex);
3816         int nLimit = 500;
3817         LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
3818         for (; pindex; pindex = chainActive.Next(pindex))
3819         {
3820             if (pindex->GetBlockHash() == hashStop)
3821             {
3822                 LogPrint("net", "  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3823                 break;
3824             }
3825             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3826             if (--nLimit <= 0)
3827             {
3828                 // When this block is requested, we'll send an inv that'll make them
3829                 // getblocks the next batch of inventory.
3830                 LogPrint("net", "  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3831                 pfrom->hashContinue = pindex->GetBlockHash();
3832                 break;
3833             }
3834         }
3835     }
3836
3837
3838     else if (strCommand == "getheaders")
3839     {
3840         CBlockLocator locator;
3841         uint256 hashStop;
3842         vRecv >> locator >> hashStop;
3843
3844         LOCK(cs_main);
3845
3846         CBlockIndex* pindex = NULL;
3847         if (locator.IsNull())
3848         {
3849             // If locator is null, return the hashStop block
3850             BlockMap::iterator mi = mapBlockIndex.find(hashStop);
3851             if (mi == mapBlockIndex.end())
3852                 return true;
3853             pindex = (*mi).second;
3854         }
3855         else
3856         {
3857             // Find the last block the caller has in the main chain
3858             pindex = FindForkInGlobalIndex(chainActive, locator);
3859             if (pindex)
3860                 pindex = chainActive.Next(pindex);
3861         }
3862
3863         // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3864         vector<CBlock> vHeaders;
3865         int nLimit = MAX_HEADERS_RESULTS;
3866         LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
3867         for (; pindex; pindex = chainActive.Next(pindex))
3868         {
3869             vHeaders.push_back(pindex->GetBlockHeader());
3870             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3871                 break;
3872         }
3873         pfrom->PushMessage("headers", vHeaders);
3874     }
3875
3876
3877     else if (strCommand == "tx")
3878     {
3879         vector<uint256> vWorkQueue;
3880         vector<uint256> vEraseQueue;
3881         CTransaction tx;
3882         vRecv >> tx;
3883
3884         CInv inv(MSG_TX, tx.GetHash());
3885         pfrom->AddInventoryKnown(inv);
3886
3887         LOCK(cs_main);
3888
3889         bool fMissingInputs = false;
3890         CValidationState state;
3891
3892         mapAlreadyAskedFor.erase(inv);
3893
3894         if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
3895         {
3896             mempool.check(pcoinsTip);
3897             RelayTransaction(tx);
3898             vWorkQueue.push_back(inv.hash);
3899             vEraseQueue.push_back(inv.hash);
3900
3901             LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
3902                 pfrom->id, pfrom->cleanSubVer,
3903                 tx.GetHash().ToString(),
3904                 mempool.mapTx.size());
3905
3906             // Recursively process any orphan transactions that depended on this one
3907             set<NodeId> setMisbehaving;
3908             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3909             {
3910                 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3911                 if (itByPrev == mapOrphanTransactionsByPrev.end())
3912                     continue;
3913                 for (set<uint256>::iterator mi = itByPrev->second.begin();
3914                      mi != itByPrev->second.end();
3915                      ++mi)
3916                 {
3917                     const uint256& orphanHash = *mi;
3918                     const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3919                     NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3920                     bool fMissingInputs2 = false;
3921                     // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3922                     // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3923                     // anyone relaying LegitTxX banned)
3924                     CValidationState stateDummy;
3925
3926                     vEraseQueue.push_back(orphanHash);
3927
3928                     if (setMisbehaving.count(fromPeer))
3929                         continue;
3930                     if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
3931                     {
3932                         LogPrint("mempool", "   accepted orphan tx %s\n", orphanHash.ToString());
3933                         RelayTransaction(orphanTx);
3934                         vWorkQueue.push_back(orphanHash);
3935                     }
3936                     else if (!fMissingInputs2)
3937                     {
3938                         int nDos = 0;
3939                         if (stateDummy.IsInvalid(nDos) && nDos > 0)
3940                         {
3941                             // Punish peer that gave us an invalid orphan tx
3942                             Misbehaving(fromPeer, nDos);
3943                             setMisbehaving.insert(fromPeer);
3944                             LogPrint("mempool", "   invalid orphan tx %s\n", orphanHash.ToString());
3945                         }
3946                         // too-little-fee orphan
3947                         LogPrint("mempool", "   removed orphan tx %s\n", orphanHash.ToString());
3948                     }
3949                     mempool.check(pcoinsTip);
3950                 }
3951             }
3952
3953             BOOST_FOREACH(uint256 hash, vEraseQueue)
3954                 EraseOrphanTx(hash);
3955         }
3956         else if (fMissingInputs)
3957         {
3958             AddOrphanTx(tx, pfrom->GetId());
3959
3960             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3961             unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3962             unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
3963             if (nEvicted > 0)
3964                 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3965         } else if (pfrom->fWhitelisted) {
3966             // Always relay transactions received from whitelisted peers, even
3967             // if they are already in the mempool (allowing the node to function
3968             // as a gateway for nodes hidden behind it).
3969             RelayTransaction(tx);
3970         }
3971         int nDoS = 0;
3972         if (state.IsInvalid(nDoS))
3973         {
3974             LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3975                 pfrom->id, pfrom->cleanSubVer,
3976                 state.GetRejectReason());
3977             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3978                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
3979             if (nDoS > 0)
3980                 Misbehaving(pfrom->GetId(), nDoS);
3981         }
3982     }
3983
3984
3985     else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
3986     {
3987         std::vector<CBlockHeader> headers;
3988
3989         // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3990         unsigned int nCount = ReadCompactSize(vRecv);
3991         if (nCount > MAX_HEADERS_RESULTS) {
3992             Misbehaving(pfrom->GetId(), 20);
3993             return error("headers message size = %u", nCount);
3994         }
3995         headers.resize(nCount);
3996         for (unsigned int n = 0; n < nCount; n++) {
3997             vRecv >> headers[n];
3998             ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
3999         }
4000
4001         LOCK(cs_main);
4002
4003         if (nCount == 0) {
4004             // Nothing interesting. Stop asking this peers for more headers.
4005             return true;
4006         }
4007
4008         CBlockIndex *pindexLast = NULL;
4009         BOOST_FOREACH(const CBlockHeader& header, headers) {
4010             CValidationState state;
4011             if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4012                 Misbehaving(pfrom->GetId(), 20);
4013                 return error("non-continuous headers sequence");
4014             }
4015             if (!AcceptBlockHeader(header, state, &pindexLast)) {
4016                 int nDoS;
4017                 if (state.IsInvalid(nDoS)) {
4018                     if (nDoS > 0)
4019                         Misbehaving(pfrom->GetId(), nDoS);
4020                     return error("invalid header received");
4021                 }
4022             }
4023         }
4024
4025         if (pindexLast)
4026             UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4027
4028         if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4029             // Headers message had its maximum size; the peer may have more headers.
4030             // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4031             // from there instead.
4032             LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4033             pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4034         }
4035     }
4036
4037     else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4038     {
4039         CBlock block;
4040         vRecv >> block;
4041
4042         CInv inv(MSG_BLOCK, block.GetHash());
4043         LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4044
4045         pfrom->AddInventoryKnown(inv);
4046
4047         CValidationState state;
4048         ProcessNewBlock(state, pfrom, &block);
4049         int nDoS;
4050         if (state.IsInvalid(nDoS)) {
4051             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4052                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4053             if (nDoS > 0) {
4054                 LOCK(cs_main);
4055                 Misbehaving(pfrom->GetId(), nDoS);
4056             }
4057         }
4058
4059     }
4060
4061
4062     // This asymmetric behavior for inbound and outbound connections was introduced
4063     // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4064     // to users' AddrMan and later request them by sending getaddr messages. 
4065     // Making users (which are behind NAT and can only make outgoing connections) ignore 
4066     // getaddr message mitigates the attack.
4067     else if ((strCommand == "getaddr") && (pfrom->fInbound))
4068     {
4069         pfrom->vAddrToSend.clear();
4070         vector<CAddress> vAddr = addrman.GetAddr();
4071         BOOST_FOREACH(const CAddress &addr, vAddr)
4072             pfrom->PushAddress(addr);
4073     }
4074
4075
4076     else if (strCommand == "mempool")
4077     {
4078         LOCK2(cs_main, pfrom->cs_filter);
4079
4080         std::vector<uint256> vtxid;
4081         mempool.queryHashes(vtxid);
4082         vector<CInv> vInv;
4083         BOOST_FOREACH(uint256& hash, vtxid) {
4084             CInv inv(MSG_TX, hash);
4085             CTransaction tx;
4086             bool fInMemPool = mempool.lookup(hash, tx);
4087             if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4088             if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4089                (!pfrom->pfilter))
4090                 vInv.push_back(inv);
4091             if (vInv.size() == MAX_INV_SZ) {
4092                 pfrom->PushMessage("inv", vInv);
4093                 vInv.clear();
4094             }
4095         }
4096         if (vInv.size() > 0)
4097             pfrom->PushMessage("inv", vInv);
4098     }
4099
4100
4101     else if (strCommand == "ping")
4102     {
4103         if (pfrom->nVersion > BIP0031_VERSION)
4104         {
4105             uint64_t nonce = 0;
4106             vRecv >> nonce;
4107             // Echo the message back with the nonce. This allows for two useful features:
4108             //
4109             // 1) A remote node can quickly check if the connection is operational
4110             // 2) Remote nodes can measure the latency of the network thread. If this node
4111             //    is overloaded it won't respond to pings quickly and the remote node can
4112             //    avoid sending us more work, like chain download requests.
4113             //
4114             // The nonce stops the remote getting confused between different pings: without
4115             // it, if the remote node sends a ping once per second and this node takes 5
4116             // seconds to respond to each, the 5th ping the remote sends would appear to
4117             // return very quickly.
4118             pfrom->PushMessage("pong", nonce);
4119         }
4120     }
4121
4122
4123     else if (strCommand == "pong")
4124     {
4125         int64_t pingUsecEnd = nTimeReceived;
4126         uint64_t nonce = 0;
4127         size_t nAvail = vRecv.in_avail();
4128         bool bPingFinished = false;
4129         std::string sProblem;
4130
4131         if (nAvail >= sizeof(nonce)) {
4132             vRecv >> nonce;
4133
4134             // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4135             if (pfrom->nPingNonceSent != 0) {
4136                 if (nonce == pfrom->nPingNonceSent) {
4137                     // Matching pong received, this ping is no longer outstanding
4138                     bPingFinished = true;
4139                     int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4140                     if (pingUsecTime > 0) {
4141                         // Successful ping time measurement, replace previous
4142                         pfrom->nPingUsecTime = pingUsecTime;
4143                     } else {
4144                         // This should never happen
4145                         sProblem = "Timing mishap";
4146                     }
4147                 } else {
4148                     // Nonce mismatches are normal when pings are overlapping
4149                     sProblem = "Nonce mismatch";
4150                     if (nonce == 0) {
4151                         // This is most likely a bug in another implementation somewhere, cancel this ping
4152                         bPingFinished = true;
4153                         sProblem = "Nonce zero";
4154                     }
4155                 }
4156             } else {
4157                 sProblem = "Unsolicited pong without ping";
4158             }
4159         } else {
4160             // This is most likely a bug in another implementation somewhere, cancel this ping
4161             bPingFinished = true;
4162             sProblem = "Short payload";
4163         }
4164
4165         if (!(sProblem.empty())) {
4166             LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4167                 pfrom->id,
4168                 pfrom->cleanSubVer,
4169                 sProblem,
4170                 pfrom->nPingNonceSent,
4171                 nonce,
4172                 nAvail);
4173         }
4174         if (bPingFinished) {
4175             pfrom->nPingNonceSent = 0;
4176         }
4177     }
4178
4179
4180     else if (strCommand == "alert")
4181     {
4182         CAlert alert;
4183         vRecv >> alert;
4184
4185         uint256 alertHash = alert.GetHash();
4186         if (pfrom->setKnown.count(alertHash) == 0)
4187         {
4188             if (alert.ProcessAlert())
4189             {
4190                 // Relay
4191                 pfrom->setKnown.insert(alertHash);
4192                 {
4193                     LOCK(cs_vNodes);
4194                     BOOST_FOREACH(CNode* pnode, vNodes)
4195                         alert.RelayTo(pnode);
4196                 }
4197             }
4198             else {
4199                 // Small DoS penalty so peers that send us lots of
4200                 // duplicate/expired/invalid-signature/whatever alerts
4201                 // eventually get banned.
4202                 // This isn't a Misbehaving(100) (immediate ban) because the
4203                 // peer might be an older or different implementation with
4204                 // a different signature key, etc.
4205                 Misbehaving(pfrom->GetId(), 10);
4206             }
4207         }
4208     }
4209
4210
4211     else if (strCommand == "filterload")
4212     {
4213         CBloomFilter filter;
4214         vRecv >> filter;
4215
4216         if (!filter.IsWithinSizeConstraints())
4217             // There is no excuse for sending a too-large filter
4218             Misbehaving(pfrom->GetId(), 100);
4219         else
4220         {
4221             LOCK(pfrom->cs_filter);
4222             delete pfrom->pfilter;
4223             pfrom->pfilter = new CBloomFilter(filter);
4224             pfrom->pfilter->UpdateEmptyFull();
4225         }
4226         pfrom->fRelayTxes = true;
4227     }
4228
4229
4230     else if (strCommand == "filteradd")
4231     {
4232         vector<unsigned char> vData;
4233         vRecv >> vData;
4234
4235         // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4236         // and thus, the maximum size any matched object can have) in a filteradd message
4237         if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4238         {
4239             Misbehaving(pfrom->GetId(), 100);
4240         } else {
4241             LOCK(pfrom->cs_filter);
4242             if (pfrom->pfilter)
4243                 pfrom->pfilter->insert(vData);
4244             else
4245                 Misbehaving(pfrom->GetId(), 100);
4246         }
4247     }
4248
4249
4250     else if (strCommand == "filterclear")
4251     {
4252         LOCK(pfrom->cs_filter);
4253         delete pfrom->pfilter;
4254         pfrom->pfilter = new CBloomFilter();
4255         pfrom->fRelayTxes = true;
4256     }
4257
4258
4259     else if (strCommand == "reject")
4260     {
4261         if (fDebug) {
4262             try {
4263                 string strMsg; unsigned char ccode; string strReason;
4264                 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4265
4266                 ostringstream ss;
4267                 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4268
4269                 if (strMsg == "block" || strMsg == "tx")
4270                 {
4271                     uint256 hash;
4272                     vRecv >> hash;
4273                     ss << ": hash " << hash.ToString();
4274                 }
4275                 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4276             } catch (const std::ios_base::failure&) {
4277                 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4278                 LogPrint("net", "Unparseable reject message received\n");
4279             }
4280         }
4281     }
4282
4283     else
4284     {
4285         // Ignore unknown commands for extensibility
4286         LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4287     }
4288
4289
4290
4291     return true;
4292 }
4293
4294 // requires LOCK(cs_vRecvMsg)
4295 bool ProcessMessages(CNode* pfrom)
4296 {
4297     //if (fDebug)
4298     //    LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
4299
4300     //
4301     // Message format
4302     //  (4) message start
4303     //  (12) command
4304     //  (4) size
4305     //  (4) checksum
4306     //  (x) data
4307     //
4308     bool fOk = true;
4309
4310     if (!pfrom->vRecvGetData.empty())
4311         ProcessGetData(pfrom);
4312
4313     // this maintains the order of responses
4314     if (!pfrom->vRecvGetData.empty()) return fOk;
4315
4316     std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4317     while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4318         // Don't bother if send buffer is too full to respond anyway
4319         if (pfrom->nSendSize >= SendBufferSize())
4320             break;
4321
4322         // get next message
4323         CNetMessage& msg = *it;
4324
4325         //if (fDebug)
4326         //    LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
4327         //            msg.hdr.nMessageSize, msg.vRecv.size(),
4328         //            msg.complete() ? "Y" : "N");
4329
4330         // end, if an incomplete message is found
4331         if (!msg.complete())
4332             break;
4333
4334         // at this point, any failure means we can delete the current message
4335         it++;
4336
4337         // Scan for message start
4338         if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4339             LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4340             fOk = false;
4341             break;
4342         }
4343
4344         // Read header
4345         CMessageHeader& hdr = msg.hdr;
4346         if (!hdr.IsValid(Params().MessageStart()))
4347         {
4348             LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4349             continue;
4350         }
4351         string strCommand = hdr.GetCommand();
4352
4353         // Message size
4354         unsigned int nMessageSize = hdr.nMessageSize;
4355
4356         // Checksum
4357         CDataStream& vRecv = msg.vRecv;
4358         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4359         unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4360         if (nChecksum != hdr.nChecksum)
4361         {
4362             LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4363                SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4364             continue;
4365         }
4366
4367         // Process message
4368         bool fRet = false;
4369         try
4370         {
4371             fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4372             boost::this_thread::interruption_point();
4373         }
4374         catch (const std::ios_base::failure& e)
4375         {
4376             pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4377             if (strstr(e.what(), "end of data"))
4378             {
4379                 // Allow exceptions from under-length message on vRecv
4380                 LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
4381             }
4382             else if (strstr(e.what(), "size too large"))
4383             {
4384                 // Allow exceptions from over-long size
4385                 LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
4386             }
4387             else
4388             {
4389                 PrintExceptionContinue(&e, "ProcessMessages()");
4390             }
4391         }
4392         catch (const boost::thread_interrupted&) {
4393             throw;
4394         }
4395         catch (const std::exception& e) {
4396             PrintExceptionContinue(&e, "ProcessMessages()");
4397         } catch (...) {
4398             PrintExceptionContinue(NULL, "ProcessMessages()");
4399         }
4400
4401         if (!fRet)
4402             LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
4403
4404         break;
4405     }
4406
4407     // In case the connection got shut down, its receive buffer was wiped
4408     if (!pfrom->fDisconnect)
4409         pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4410
4411     return fOk;
4412 }
4413
4414
4415 bool SendMessages(CNode* pto, bool fSendTrickle)
4416 {
4417     {
4418         // Don't send anything until we get their version message
4419         if (pto->nVersion == 0)
4420             return true;
4421
4422         //
4423         // Message: ping
4424         //
4425         bool pingSend = false;
4426         if (pto->fPingQueued) {
4427             // RPC ping request by user
4428             pingSend = true;
4429         }
4430         if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4431             // Ping automatically sent as a latency probe & keepalive.
4432             pingSend = true;
4433         }
4434         if (pingSend) {
4435             uint64_t nonce = 0;
4436             while (nonce == 0) {
4437                 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4438             }
4439             pto->fPingQueued = false;
4440             pto->nPingUsecStart = GetTimeMicros();
4441             if (pto->nVersion > BIP0031_VERSION) {
4442                 pto->nPingNonceSent = nonce;
4443                 pto->PushMessage("ping", nonce);
4444             } else {
4445                 // Peer is too old to support ping command with nonce, pong will never arrive.
4446                 pto->nPingNonceSent = 0;
4447                 pto->PushMessage("ping");
4448             }
4449         }
4450
4451         TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4452         if (!lockMain)
4453             return true;
4454
4455         // Address refresh broadcast
4456         static int64_t nLastRebroadcast;
4457         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4458         {
4459             LOCK(cs_vNodes);
4460             BOOST_FOREACH(CNode* pnode, vNodes)
4461             {
4462                 // Periodically clear setAddrKnown to allow refresh broadcasts
4463                 if (nLastRebroadcast)
4464                     pnode->setAddrKnown.clear();
4465
4466                 // Rebroadcast our address
4467                 AdvertizeLocal(pnode);
4468             }
4469             if (!vNodes.empty())
4470                 nLastRebroadcast = GetTime();
4471         }
4472
4473         //
4474         // Message: addr
4475         //
4476         if (fSendTrickle)
4477         {
4478             vector<CAddress> vAddr;
4479             vAddr.reserve(pto->vAddrToSend.size());
4480             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4481             {
4482                 // returns true if wasn't already contained in the set
4483                 if (pto->setAddrKnown.insert(addr).second)
4484                 {
4485                     vAddr.push_back(addr);
4486                     // receiver rejects addr messages larger than 1000
4487                     if (vAddr.size() >= 1000)
4488                     {
4489                         pto->PushMessage("addr", vAddr);
4490                         vAddr.clear();
4491                     }
4492                 }
4493             }
4494             pto->vAddrToSend.clear();
4495             if (!vAddr.empty())
4496                 pto->PushMessage("addr", vAddr);
4497         }
4498
4499         CNodeState &state = *State(pto->GetId());
4500         if (state.fShouldBan) {
4501             if (pto->fWhitelisted)
4502                 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4503             else {
4504                 pto->fDisconnect = true;
4505                 if (pto->addr.IsLocal())
4506                     LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4507                 else
4508                 {
4509                     CNode::Ban(pto->addr);
4510                 }
4511             }
4512             state.fShouldBan = false;
4513         }
4514
4515         BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4516             pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4517         state.rejects.clear();
4518
4519         // Start block sync
4520         if (pindexBestHeader == NULL)
4521             pindexBestHeader = chainActive.Tip();
4522         bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
4523         if (!state.fSyncStarted && !pto->fClient && fFetch && !fImporting && !fReindex) {
4524             // Only actively request headers from a single peer, unless we're close to today.
4525             if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4526                 state.fSyncStarted = true;
4527                 nSyncStarted++;
4528                 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4529                 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4530                 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
4531             }
4532         }
4533
4534         // Resend wallet transactions that haven't gotten in a block yet
4535         // Except during reindex, importing and IBD, when old wallet
4536         // transactions become unconfirmed and spams other nodes.
4537         if (!fReindex && !fImporting && !IsInitialBlockDownload())
4538         {
4539             g_signals.Broadcast();
4540         }
4541
4542         //
4543         // Message: inventory
4544         //
4545         vector<CInv> vInv;
4546         vector<CInv> vInvWait;
4547         {
4548             LOCK(pto->cs_inventory);
4549             vInv.reserve(pto->vInventoryToSend.size());
4550             vInvWait.reserve(pto->vInventoryToSend.size());
4551             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4552             {
4553                 if (pto->setInventoryKnown.count(inv))
4554                     continue;
4555
4556                 // trickle out tx inv to protect privacy
4557                 if (inv.type == MSG_TX && !fSendTrickle)
4558                 {
4559                     // 1/4 of tx invs blast to all immediately
4560                     static uint256 hashSalt;
4561                     if (hashSalt.IsNull())
4562                         hashSalt = GetRandHash();
4563                     uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
4564                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4565                     bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
4566
4567                     if (fTrickleWait)
4568                     {
4569                         vInvWait.push_back(inv);
4570                         continue;
4571                     }
4572                 }
4573
4574                 // returns true if wasn't already contained in the set
4575                 if (pto->setInventoryKnown.insert(inv).second)
4576                 {
4577                     vInv.push_back(inv);
4578                     if (vInv.size() >= 1000)
4579                     {
4580                         pto->PushMessage("inv", vInv);
4581                         vInv.clear();
4582                     }
4583                 }
4584             }
4585             pto->vInventoryToSend = vInvWait;
4586         }
4587         if (!vInv.empty())
4588             pto->PushMessage("inv", vInv);
4589
4590         // Detect whether we're stalling
4591         int64_t nNow = GetTimeMicros();
4592         if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4593             // Stalling only triggers when the block download window cannot move. During normal steady state,
4594             // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4595             // should only happen during initial block download.
4596             LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
4597             pto->fDisconnect = true;
4598         }
4599         // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
4600         // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
4601         // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
4602         // being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
4603         // to unreasonably increase our timeout.
4604         if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
4605             LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
4606             pto->fDisconnect = true;
4607         }
4608
4609         //
4610         // Message: getdata (blocks)
4611         //
4612         vector<CInv> vGetData;
4613         if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4614             vector<CBlockIndex*> vToDownload;
4615             NodeId staller = -1;
4616             FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4617             BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
4618                 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4619                 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
4620                 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4621                     pindex->nHeight, pto->id);
4622             }
4623             if (state.nBlocksInFlight == 0 && staller != -1) {
4624                 if (State(staller)->nStallingSince == 0) {
4625                     State(staller)->nStallingSince = nNow;
4626                     LogPrint("net", "Stall started peer=%d\n", staller);
4627                 }
4628             }
4629         }
4630
4631         //
4632         // Message: getdata (non-blocks)
4633         //
4634         while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4635         {
4636             const CInv& inv = (*pto->mapAskFor.begin()).second;
4637             if (!AlreadyHave(inv))
4638             {
4639                 if (fDebug)
4640                     LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
4641                 vGetData.push_back(inv);
4642                 if (vGetData.size() >= 1000)
4643                 {
4644                     pto->PushMessage("getdata", vGetData);
4645                     vGetData.clear();
4646                 }
4647             }
4648             pto->mapAskFor.erase(pto->mapAskFor.begin());
4649         }
4650         if (!vGetData.empty())
4651             pto->PushMessage("getdata", vGetData);
4652
4653     }
4654     return true;
4655 }
4656
4657  std::string CBlockFileInfo::ToString() const {
4658      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));
4659  }
4660
4661
4662
4663 class CMainCleanup
4664 {
4665 public:
4666     CMainCleanup() {}
4667     ~CMainCleanup() {
4668         // block headers
4669         BlockMap::iterator it1 = mapBlockIndex.begin();
4670         for (; it1 != mapBlockIndex.end(); it1++)
4671             delete (*it1).second;
4672         mapBlockIndex.clear();
4673
4674         // orphan transactions
4675         mapOrphanTransactions.clear();
4676         mapOrphanTransactionsByPrev.clear();
4677     }
4678 } instance_of_cmaincleanup;
This page took 0.29372 seconds and 4 git commands to generate.