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