Remove invalid dependent orphans from memory
[novacoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "checkpoints.h"
6 #include "db.h"
7 #include "net.h"
8 #include "init.h"
9 #include "ui_interface.h"
10 #include <boost/algorithm/string/replace.hpp>
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13
14 using namespace std;
15 using namespace boost;
16
17 //
18 // Global state
19 //
20
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
23
24 CCriticalSection cs_main;
25
26 CTxMemPool mempool;
27 unsigned int nTransactionsUpdated = 0;
28
29 map<uint256, CBlockIndex*> mapBlockIndex;
30 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
31 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
32 CBlockIndex* pindexGenesisBlock = NULL;
33 int nBestHeight = -1;
34 CBigNum bnBestChainWork = 0;
35 CBigNum bnBestInvalidWork = 0;
36 uint256 hashBestChain = 0;
37 CBlockIndex* pindexBest = NULL;
38 int64 nTimeBestReceived = 0;
39
40 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
41
42 map<uint256, CBlock*> mapOrphanBlocks;
43 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
44
45 map<uint256, CDataStream*> mapOrphanTransactions;
46 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
47
48 // Constant stuff for coinbase transactions we create:
49 CScript COINBASE_FLAGS;
50
51 const string strMessageMagic = "Bitcoin Signed Message:\n";
52
53 double dHashesPerSec;
54 int64 nHPSTimerStart;
55
56 // Settings
57 int64 nTransactionFee = 0;
58
59
60
61 //////////////////////////////////////////////////////////////////////////////
62 //
63 // dispatching functions
64 //
65
66 // These functions dispatch to one or all registered wallets
67
68
69 void RegisterWallet(CWallet* pwalletIn)
70 {
71     {
72         LOCK(cs_setpwalletRegistered);
73         setpwalletRegistered.insert(pwalletIn);
74     }
75 }
76
77 void UnregisterWallet(CWallet* pwalletIn)
78 {
79     {
80         LOCK(cs_setpwalletRegistered);
81         setpwalletRegistered.erase(pwalletIn);
82     }
83 }
84
85 // check whether the passed transaction is from us
86 bool static IsFromMe(CTransaction& tx)
87 {
88     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
89         if (pwallet->IsFromMe(tx))
90             return true;
91     return false;
92 }
93
94 // get the wallet transaction with the given hash (if it exists)
95 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
96 {
97     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
98         if (pwallet->GetTransaction(hashTx,wtx))
99             return true;
100     return false;
101 }
102
103 // erases transaction with the given hash from all wallets
104 void static EraseFromWallets(uint256 hash)
105 {
106     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
107         pwallet->EraseFromWallet(hash);
108 }
109
110 // make sure all wallets know about the given transaction, in the given block
111 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
112 {
113     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
115 }
116
117 // notify wallets about a new best chain
118 void static SetBestChain(const CBlockLocator& loc)
119 {
120     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121         pwallet->SetBestChain(loc);
122 }
123
124 // notify wallets about an updated transaction
125 void static UpdatedTransaction(const uint256& hashTx)
126 {
127     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128         pwallet->UpdatedTransaction(hashTx);
129 }
130
131 // dump all wallets
132 void static PrintWallets(const CBlock& block)
133 {
134     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135         pwallet->PrintWallet(block);
136 }
137
138 // notify wallets about an incoming inventory (for request counts)
139 void static Inventory(const uint256& hash)
140 {
141     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142         pwallet->Inventory(hash);
143 }
144
145 // ask wallets to resend their transactions
146 void static ResendWalletTransactions()
147 {
148     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149         pwallet->ResendWalletTransactions();
150 }
151
152
153
154
155
156
157
158 //////////////////////////////////////////////////////////////////////////////
159 //
160 // mapOrphanTransactions
161 //
162
163 bool AddOrphanTx(const CDataStream& vMsg)
164 {
165     CTransaction tx;
166     CDataStream(vMsg) >> tx;
167     uint256 hash = tx.GetHash();
168     if (mapOrphanTransactions.count(hash))
169         return false;
170
171     CDataStream* pvMsg = new CDataStream(vMsg);
172
173     // Ignore big transactions, to avoid a
174     // send-big-orphans memory exhaustion attack. If a peer has a legitimate
175     // large transaction with a missing parent then we assume
176     // it will rebroadcast it later, after the parent transaction(s)
177     // have been mined or received.
178     // 10,000 orphans, each of which is at most 5,000 bytes big is
179     // at most 500 megabytes of orphans:
180     if (pvMsg->size() > 5000)
181     {
182         delete pvMsg;
183         printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
184         return false;
185     }
186
187     mapOrphanTransactions[hash] = pvMsg;
188     BOOST_FOREACH(const CTxIn& txin, tx.vin)
189         mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
190
191     printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
192         mapOrphanTransactions.size());
193     return true;
194 }
195
196 void static EraseOrphanTx(uint256 hash)
197 {
198     if (!mapOrphanTransactions.count(hash))
199         return;
200     const CDataStream* pvMsg = mapOrphanTransactions[hash];
201     CTransaction tx;
202     CDataStream(*pvMsg) >> tx;
203     BOOST_FOREACH(const CTxIn& txin, tx.vin)
204     {
205         mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
206         if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
207             mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
208     }
209     delete pvMsg;
210     mapOrphanTransactions.erase(hash);
211 }
212
213 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
214 {
215     unsigned int nEvicted = 0;
216     while (mapOrphanTransactions.size() > nMaxOrphans)
217     {
218         // Evict a random orphan:
219         std::vector<unsigned char> randbytes(32);
220         RAND_bytes(&randbytes[0], 32);
221         uint256 randomhash(randbytes);
222         map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
223         if (it == mapOrphanTransactions.end())
224             it = mapOrphanTransactions.begin();
225         EraseOrphanTx(it->first);
226         ++nEvicted;
227     }
228     return nEvicted;
229 }
230
231
232
233
234
235
236
237 //////////////////////////////////////////////////////////////////////////////
238 //
239 // CTransaction and CTxIndex
240 //
241
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
243 {
244     SetNull();
245     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
246         return false;
247     if (!ReadFromDisk(txindexRet.pos))
248         return false;
249     if (prevout.n >= vout.size())
250     {
251         SetNull();
252         return false;
253     }
254     return true;
255 }
256
257 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
258 {
259     CTxIndex txindex;
260     return ReadFromDisk(txdb, prevout, txindex);
261 }
262
263 bool CTransaction::ReadFromDisk(COutPoint prevout)
264 {
265     CTxDB txdb("r");
266     CTxIndex txindex;
267     return ReadFromDisk(txdb, prevout, txindex);
268 }
269
270 bool CTransaction::IsStandard() const
271 {
272     BOOST_FOREACH(const CTxIn& txin, vin)
273     {
274         // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
275         // pay-to-script-hash, which is 3 ~80-byte signatures, 3
276         // ~65-byte public keys, plus a few script ops.
277         if (txin.scriptSig.size() > 500)
278             return false;
279         if (!txin.scriptSig.IsPushOnly())
280             return false;
281     }
282     BOOST_FOREACH(const CTxOut& txout, vout)
283         if (!::IsStandard(txout.scriptPubKey))
284             return false;
285     return true;
286 }
287
288 //
289 // Check transaction inputs, and make sure any
290 // pay-to-script-hash transactions are evaluating IsStandard scripts
291 //
292 // Why bother? To avoid denial-of-service attacks; an attacker
293 // can submit a standard HASH... OP_EQUAL transaction,
294 // which will get accepted into blocks. The redemption
295 // script can be anything; an attacker could use a very
296 // expensive-to-check-upon-redemption script like:
297 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
298 //
299 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
300 {
301     if (IsCoinBase())
302         return true; // Coinbases don't use vin normally
303
304     for (unsigned int i = 0; i < vin.size(); i++)
305     {
306         const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
307
308         vector<vector<unsigned char> > vSolutions;
309         txnouttype whichType;
310         // get the scriptPubKey corresponding to this input:
311         const CScript& prevScript = prev.scriptPubKey;
312         if (!Solver(prevScript, whichType, vSolutions))
313             return false;
314         int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
315         if (nArgsExpected < 0)
316             return false;
317
318         // Transactions with extra stuff in their scriptSigs are
319         // non-standard. Note that this EvalScript() call will
320         // be quick, because if there are any operations
321         // beside "push data" in the scriptSig the
322         // IsStandard() call returns false
323         vector<vector<unsigned char> > stack;
324         if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
325             return false;
326
327         if (whichType == TX_SCRIPTHASH)
328         {
329             if (stack.empty())
330                 return false;
331             CScript subscript(stack.back().begin(), stack.back().end());
332             vector<vector<unsigned char> > vSolutions2;
333             txnouttype whichType2;
334             if (!Solver(subscript, whichType2, vSolutions2))
335                 return false;
336             if (whichType2 == TX_SCRIPTHASH)
337                 return false;
338
339             int tmpExpected;
340             tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
341             if (tmpExpected < 0)
342                 return false;
343             nArgsExpected += tmpExpected;
344         }
345
346         if (stack.size() != (unsigned int)nArgsExpected)
347             return false;
348     }
349
350     return true;
351 }
352
353 unsigned int
354 CTransaction::GetLegacySigOpCount() const
355 {
356     unsigned int nSigOps = 0;
357     BOOST_FOREACH(const CTxIn& txin, vin)
358     {
359         nSigOps += txin.scriptSig.GetSigOpCount(false);
360     }
361     BOOST_FOREACH(const CTxOut& txout, vout)
362     {
363         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
364     }
365     return nSigOps;
366 }
367
368
369 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
370 {
371     if (fClient)
372     {
373         if (hashBlock == 0)
374             return 0;
375     }
376     else
377     {
378         CBlock blockTmp;
379         if (pblock == NULL)
380         {
381             // Load the block this tx is in
382             CTxIndex txindex;
383             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
384                 return 0;
385             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
386                 return 0;
387             pblock = &blockTmp;
388         }
389
390         // Update the tx's hashBlock
391         hashBlock = pblock->GetHash();
392
393         // Locate the transaction
394         for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
395             if (pblock->vtx[nIndex] == *(CTransaction*)this)
396                 break;
397         if (nIndex == (int)pblock->vtx.size())
398         {
399             vMerkleBranch.clear();
400             nIndex = -1;
401             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
402             return 0;
403         }
404
405         // Fill in merkle branch
406         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
407     }
408
409     // Is the tx in a block that's in the main chain
410     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
411     if (mi == mapBlockIndex.end())
412         return 0;
413     CBlockIndex* pindex = (*mi).second;
414     if (!pindex || !pindex->IsInMainChain())
415         return 0;
416
417     return pindexBest->nHeight - pindex->nHeight + 1;
418 }
419
420
421
422
423
424
425
426 bool CTransaction::CheckTransaction() const
427 {
428     // Basic checks that don't depend on any context
429     if (vin.empty())
430         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
431     if (vout.empty())
432         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
433     // Size limits
434     if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
435         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
436
437     // Check for negative or overflow output values
438     int64 nValueOut = 0;
439     BOOST_FOREACH(const CTxOut& txout, vout)
440     {
441         if (txout.nValue < 0)
442             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
443         if (txout.nValue > MAX_MONEY)
444             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
445         nValueOut += txout.nValue;
446         if (!MoneyRange(nValueOut))
447             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
448     }
449
450     // Check for duplicate inputs
451     set<COutPoint> vInOutPoints;
452     BOOST_FOREACH(const CTxIn& txin, vin)
453     {
454         if (vInOutPoints.count(txin.prevout))
455             return false;
456         vInOutPoints.insert(txin.prevout);
457     }
458
459     if (IsCoinBase())
460     {
461         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
462             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
463     }
464     else
465     {
466         BOOST_FOREACH(const CTxIn& txin, vin)
467             if (txin.prevout.IsNull())
468                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
469     }
470
471     return true;
472 }
473
474 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
475                         bool* pfMissingInputs)
476 {
477     if (pfMissingInputs)
478         *pfMissingInputs = false;
479
480     if (!tx.CheckTransaction())
481         return error("CTxMemPool::accept() : CheckTransaction failed");
482
483     // Coinbase is only valid in a block, not as a loose transaction
484     if (tx.IsCoinBase())
485         return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
486
487     // To help v0.1.5 clients who would see it as a negative number
488     if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
489         return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
490
491     // Rather not work on nonstandard transactions (unless -testnet)
492     if (!fTestNet && !tx.IsStandard())
493         return error("CTxMemPool::accept() : nonstandard transaction type");
494
495     // Do we already have it?
496     uint256 hash = tx.GetHash();
497     {
498         LOCK(cs);
499         if (mapTx.count(hash))
500             return false;
501     }
502     if (fCheckInputs)
503         if (txdb.ContainsTx(hash))
504             return false;
505
506     // Check for conflicts with in-memory transactions
507     CTransaction* ptxOld = NULL;
508     for (unsigned int i = 0; i < tx.vin.size(); i++)
509     {
510         COutPoint outpoint = tx.vin[i].prevout;
511         if (mapNextTx.count(outpoint))
512         {
513             // Disable replacement feature for now
514             return false;
515
516             // Allow replacing with a newer version of the same transaction
517             if (i != 0)
518                 return false;
519             ptxOld = mapNextTx[outpoint].ptx;
520             if (ptxOld->IsFinal())
521                 return false;
522             if (!tx.IsNewerThan(*ptxOld))
523                 return false;
524             for (unsigned int i = 0; i < tx.vin.size(); i++)
525             {
526                 COutPoint outpoint = tx.vin[i].prevout;
527                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
528                     return false;
529             }
530             break;
531         }
532     }
533
534     if (fCheckInputs)
535     {
536         MapPrevTx mapInputs;
537         map<uint256, CTxIndex> mapUnused;
538         bool fInvalid = false;
539         if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
540         {
541             if (fInvalid)
542                 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
543             if (pfMissingInputs)
544                 *pfMissingInputs = true;
545             return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
546         }
547
548         // Check for non-standard pay-to-script-hash in inputs
549         if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
550             return error("CTxMemPool::accept() : nonstandard transaction input");
551
552         // Note: if you modify this code to accept non-standard transactions, then
553         // you should add code here to check that the transaction does a
554         // reasonable number of ECDSA signature verifications.
555
556         int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
557         unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
558
559         // Don't accept it if it can't get into a block
560         if (nFees < tx.GetMinFee(1000, true, GMF_RELAY))
561             return error("CTxMemPool::accept() : not enough fees");
562
563         // Continuously rate-limit free transactions
564         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
565         // be annoying or make other's transactions take longer to confirm.
566         if (nFees < MIN_RELAY_TX_FEE)
567         {
568             static CCriticalSection cs;
569             static double dFreeCount;
570             static int64 nLastTime;
571             int64 nNow = GetTime();
572
573             {
574                 LOCK(cs);
575                 // Use an exponentially decaying ~10-minute window:
576                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
577                 nLastTime = nNow;
578                 // -limitfreerelay unit is thousand-bytes-per-minute
579                 // At default rate it would take over a month to fill 1GB
580                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
581                     return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
582                 if (fDebug)
583                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
584                 dFreeCount += nSize;
585             }
586         }
587
588         // Check against previous transactions
589         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
590         if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
591         {
592             return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
593         }
594     }
595
596     // Store transaction in memory
597     {
598         LOCK(cs);
599         if (ptxOld)
600         {
601             printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
602             remove(*ptxOld);
603         }
604         addUnchecked(tx);
605     }
606
607     ///// are we sure this is ok when loading transactions or restoring block txes
608     // If updated, erase old tx from wallet
609     if (ptxOld)
610         EraseFromWallets(ptxOld->GetHash());
611
612     printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
613     return true;
614 }
615
616 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
617 {
618     return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
619 }
620
621 bool CTxMemPool::addUnchecked(CTransaction &tx)
622 {
623     printf("addUnchecked(): size %lu\n",  mapTx.size());
624     // Add to memory pool without checking anything.  Don't call this directly,
625     // call CTxMemPool::accept to properly check the transaction first.
626     {
627         LOCK(cs);
628         uint256 hash = tx.GetHash();
629         mapTx[hash] = tx;
630         for (unsigned int i = 0; i < tx.vin.size(); i++)
631             mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
632         nTransactionsUpdated++;
633     }
634     return true;
635 }
636
637
638 bool CTxMemPool::remove(CTransaction &tx)
639 {
640     // Remove transaction from memory pool
641     {
642         LOCK(cs);
643         uint256 hash = tx.GetHash();
644         if (mapTx.count(hash))
645         {
646             BOOST_FOREACH(const CTxIn& txin, tx.vin)
647                 mapNextTx.erase(txin.prevout);
648             mapTx.erase(hash);
649             nTransactionsUpdated++;
650         }
651     }
652     return true;
653 }
654
655
656
657
658
659
660 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
661 {
662     if (hashBlock == 0 || nIndex == -1)
663         return 0;
664
665     // Find the block it claims to be in
666     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
667     if (mi == mapBlockIndex.end())
668         return 0;
669     CBlockIndex* pindex = (*mi).second;
670     if (!pindex || !pindex->IsInMainChain())
671         return 0;
672
673     // Make sure the merkle branch connects to this block
674     if (!fMerkleVerified)
675     {
676         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
677             return 0;
678         fMerkleVerified = true;
679     }
680
681     pindexRet = pindex;
682     return pindexBest->nHeight - pindex->nHeight + 1;
683 }
684
685
686 int CMerkleTx::GetBlocksToMaturity() const
687 {
688     if (!IsCoinBase())
689         return 0;
690     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
691 }
692
693
694 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
695 {
696     if (fClient)
697     {
698         if (!IsInMainChain() && !ClientConnectInputs())
699             return false;
700         return CTransaction::AcceptToMemoryPool(txdb, false);
701     }
702     else
703     {
704         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
705     }
706 }
707
708 bool CMerkleTx::AcceptToMemoryPool()
709 {
710     CTxDB txdb("r");
711     return AcceptToMemoryPool(txdb);
712 }
713
714
715
716 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
717 {
718
719     {
720         LOCK(mempool.cs);
721         // Add previous supporting transactions first
722         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
723         {
724             if (!tx.IsCoinBase())
725             {
726                 uint256 hash = tx.GetHash();
727                 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
728                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
729             }
730         }
731         return AcceptToMemoryPool(txdb, fCheckInputs);
732     }
733     return false;
734 }
735
736 bool CWalletTx::AcceptWalletTransaction()
737 {
738     CTxDB txdb("r");
739     return AcceptWalletTransaction(txdb);
740 }
741
742 int CTxIndex::GetDepthInMainChain() const
743 {
744     // Read block header
745     CBlock block;
746     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
747         return 0;
748     // Find the block in the index
749     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
750     if (mi == mapBlockIndex.end())
751         return 0;
752     CBlockIndex* pindex = (*mi).second;
753     if (!pindex || !pindex->IsInMainChain())
754         return 0;
755     return 1 + nBestHeight - pindex->nHeight;
756 }
757
758
759
760
761
762
763
764
765
766
767 //////////////////////////////////////////////////////////////////////////////
768 //
769 // CBlock and CBlockIndex
770 //
771
772 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
773 {
774     if (!fReadTransactions)
775     {
776         *this = pindex->GetBlockHeader();
777         return true;
778     }
779     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
780         return false;
781     if (GetHash() != pindex->GetBlockHash())
782         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
783     return true;
784 }
785
786 uint256 static GetOrphanRoot(const CBlock* pblock)
787 {
788     // Work back to the first block in the orphan chain
789     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
790         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
791     return pblock->GetHash();
792 }
793
794 int64 static GetBlockValue(int nHeight, int64 nFees)
795 {
796     int64 nSubsidy = 50 * COIN;
797
798     // Subsidy is cut in half every 4 years
799     nSubsidy >>= (nHeight / 210000);
800
801     return nSubsidy + nFees;
802 }
803
804 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
805 static const int64 nTargetSpacing = 10 * 60;
806 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
807
808 //
809 // minimum amount of work that could possibly be required nTime after
810 // minimum work required was nBase
811 //
812 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
813 {
814     // Testnet has min-difficulty blocks
815     // after nTargetSpacing*2 time between blocks:
816     if (fTestNet && nTime > nTargetSpacing*2)
817         return bnProofOfWorkLimit.GetCompact();
818
819     CBigNum bnResult;
820     bnResult.SetCompact(nBase);
821     while (nTime > 0 && bnResult < bnProofOfWorkLimit)
822     {
823         // Maximum 400% adjustment...
824         bnResult *= 4;
825         // ... in best-case exactly 4-times-normal target time
826         nTime -= nTargetTimespan*4;
827     }
828     if (bnResult > bnProofOfWorkLimit)
829         bnResult = bnProofOfWorkLimit;
830     return bnResult.GetCompact();
831 }
832
833 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
834 {
835     unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
836
837     // Genesis block
838     if (pindexLast == NULL)
839         return nProofOfWorkLimit;
840
841     // Only change once per interval
842     if ((pindexLast->nHeight+1) % nInterval != 0)
843     {
844         // Special rules for testnet after 15 Feb 2012:
845         if (fTestNet && pblock->nTime > 1329264000)
846         {
847             // If the new block's timestamp is more than 2* 10 minutes
848             // then allow mining of a min-difficulty block.
849             if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
850                 return nProofOfWorkLimit;
851             else
852             {
853                 // Return the last non-special-min-difficulty-rules-block
854                 const CBlockIndex* pindex = pindexLast;
855                 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
856                     pindex = pindex->pprev;
857                 return pindex->nBits;
858             }
859         }
860
861         return pindexLast->nBits;
862     }
863
864     // Go back by what we want to be 14 days worth of blocks
865     const CBlockIndex* pindexFirst = pindexLast;
866     for (int i = 0; pindexFirst && i < nInterval-1; i++)
867         pindexFirst = pindexFirst->pprev;
868     assert(pindexFirst);
869
870     // Limit adjustment step
871     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
872     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
873     if (nActualTimespan < nTargetTimespan/4)
874         nActualTimespan = nTargetTimespan/4;
875     if (nActualTimespan > nTargetTimespan*4)
876         nActualTimespan = nTargetTimespan*4;
877
878     // Retarget
879     CBigNum bnNew;
880     bnNew.SetCompact(pindexLast->nBits);
881     bnNew *= nActualTimespan;
882     bnNew /= nTargetTimespan;
883
884     if (bnNew > bnProofOfWorkLimit)
885         bnNew = bnProofOfWorkLimit;
886
887     /// debug print
888     printf("GetNextWorkRequired RETARGET\n");
889     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
890     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
891     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
892
893     return bnNew.GetCompact();
894 }
895
896 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
897 {
898     CBigNum bnTarget;
899     bnTarget.SetCompact(nBits);
900
901     // Check range
902     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
903         return error("CheckProofOfWork() : nBits below minimum work");
904
905     // Check proof of work matches claimed amount
906     if (hash > bnTarget.getuint256())
907         return error("CheckProofOfWork() : hash doesn't match nBits");
908
909     return true;
910 }
911
912 // Return maximum amount of blocks that other nodes claim to have
913 int GetNumBlocksOfPeers()
914 {
915     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
916 }
917
918 bool IsInitialBlockDownload()
919 {
920     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
921         return true;
922     static int64 nLastUpdate;
923     static CBlockIndex* pindexLastBest;
924     if (pindexBest != pindexLastBest)
925     {
926         pindexLastBest = pindexBest;
927         nLastUpdate = GetTime();
928     }
929     return (GetTime() - nLastUpdate < 10 &&
930             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
931 }
932
933 void static InvalidChainFound(CBlockIndex* pindexNew)
934 {
935     if (pindexNew->bnChainWork > bnBestInvalidWork)
936     {
937         bnBestInvalidWork = pindexNew->bnChainWork;
938         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
939         MainFrameRepaint();
940     }
941     printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
942     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
943     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
944         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
945 }
946
947 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
948 {
949     nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
950
951     // Updating time can change work required on testnet:
952     if (fTestNet)
953         nBits = GetNextWorkRequired(pindexPrev, this);
954 }
955
956
957
958
959
960
961
962
963
964
965
966 bool CTransaction::DisconnectInputs(CTxDB& txdb)
967 {
968     // Relinquish previous transactions' spent pointers
969     if (!IsCoinBase())
970     {
971         BOOST_FOREACH(const CTxIn& txin, vin)
972         {
973             COutPoint prevout = txin.prevout;
974
975             // Get prev txindex from disk
976             CTxIndex txindex;
977             if (!txdb.ReadTxIndex(prevout.hash, txindex))
978                 return error("DisconnectInputs() : ReadTxIndex failed");
979
980             if (prevout.n >= txindex.vSpent.size())
981                 return error("DisconnectInputs() : prevout.n out of range");
982
983             // Mark outpoint as not spent
984             txindex.vSpent[prevout.n].SetNull();
985
986             // Write back
987             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
988                 return error("DisconnectInputs() : UpdateTxIndex failed");
989         }
990     }
991
992     // Remove transaction from index
993     // This can fail if a duplicate of this transaction was in a chain that got
994     // reorganized away. This is only possible if this transaction was completely
995     // spent, so erasing it would be a no-op anway.
996     txdb.EraseTxIndex(*this);
997
998     return true;
999 }
1000
1001
1002 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1003                                bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1004 {
1005     // FetchInputs can return false either because we just haven't seen some inputs
1006     // (in which case the transaction should be stored as an orphan)
1007     // or because the transaction is malformed (in which case the transaction should
1008     // be dropped).  If tx is definitely invalid, fInvalid will be set to true.
1009     fInvalid = false;
1010
1011     if (IsCoinBase())
1012         return true; // Coinbase transactions have no inputs to fetch.
1013
1014     for (unsigned int i = 0; i < vin.size(); i++)
1015     {
1016         COutPoint prevout = vin[i].prevout;
1017         if (inputsRet.count(prevout.hash))
1018             continue; // Got it already
1019
1020         // Read txindex
1021         CTxIndex& txindex = inputsRet[prevout.hash].first;
1022         bool fFound = true;
1023         if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1024         {
1025             // Get txindex from current proposed changes
1026             txindex = mapTestPool.find(prevout.hash)->second;
1027         }
1028         else
1029         {
1030             // Read txindex from txdb
1031             fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1032         }
1033         if (!fFound && (fBlock || fMiner))
1034             return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1035
1036         // Read txPrev
1037         CTransaction& txPrev = inputsRet[prevout.hash].second;
1038         if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1039         {
1040             // Get prev tx from single transactions in memory
1041             {
1042                 LOCK(mempool.cs);
1043                 if (!mempool.exists(prevout.hash))
1044                     return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1045                 txPrev = mempool.lookup(prevout.hash);
1046             }
1047             if (!fFound)
1048                 txindex.vSpent.resize(txPrev.vout.size());
1049         }
1050         else
1051         {
1052             // Get prev tx from disk
1053             if (!txPrev.ReadFromDisk(txindex.pos))
1054                 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1055         }
1056     }
1057
1058     // Make sure all prevout.n's are valid:
1059     for (unsigned int i = 0; i < vin.size(); i++)
1060     {
1061         const COutPoint prevout = vin[i].prevout;
1062         assert(inputsRet.count(prevout.hash) != 0);
1063         const CTxIndex& txindex = inputsRet[prevout.hash].first;
1064         const CTransaction& txPrev = inputsRet[prevout.hash].second;
1065         if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1066         {
1067             // Revisit this if/when transaction replacement is implemented and allows
1068             // adding inputs:
1069             fInvalid = true;
1070             return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1071         }
1072     }
1073
1074     return true;
1075 }
1076
1077 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1078 {
1079     MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1080     if (mi == inputs.end())
1081         throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1082
1083     const CTransaction& txPrev = (mi->second).second;
1084     if (input.prevout.n >= txPrev.vout.size())
1085         throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1086
1087     return txPrev.vout[input.prevout.n];
1088 }
1089
1090 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1091 {
1092     if (IsCoinBase())
1093         return 0;
1094
1095     int64 nResult = 0;
1096     for (unsigned int i = 0; i < vin.size(); i++)
1097     {
1098         nResult += GetOutputFor(vin[i], inputs).nValue;
1099     }
1100     return nResult;
1101
1102 }
1103
1104 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1105 {
1106     if (IsCoinBase())
1107         return 0;
1108
1109     unsigned int nSigOps = 0;
1110     for (unsigned int i = 0; i < vin.size(); i++)
1111     {
1112         const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1113         if (prevout.scriptPubKey.IsPayToScriptHash())
1114             nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1115     }
1116     return nSigOps;
1117 }
1118
1119 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1120                                  map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1121                                  const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1122 {
1123     // Take over previous transactions' spent pointers
1124     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1125     // fMiner is true when called from the internal bitcoin miner
1126     // ... both are false when called from CTransaction::AcceptToMemoryPool
1127     if (!IsCoinBase())
1128     {
1129         int64 nValueIn = 0;
1130         int64 nFees = 0;
1131         for (unsigned int i = 0; i < vin.size(); i++)
1132         {
1133             COutPoint prevout = vin[i].prevout;
1134             assert(inputs.count(prevout.hash) > 0);
1135             CTxIndex& txindex = inputs[prevout.hash].first;
1136             CTransaction& txPrev = inputs[prevout.hash].second;
1137
1138             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1139                 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1140
1141             // If prev is coinbase, check that it's matured
1142             if (txPrev.IsCoinBase())
1143                 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1144                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1145                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1146
1147             // Check for conflicts (double-spend)
1148             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1149             // for an attacker to attempt to split the network.
1150             if (!txindex.vSpent[prevout.n].IsNull())
1151                 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1152
1153             // Check for negative or overflow input values
1154             nValueIn += txPrev.vout[prevout.n].nValue;
1155             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1156                 return DoS(100, error("ConnectInputs() : txin values out of range"));
1157
1158             // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1159             // before the last blockchain checkpoint. This is safe because block merkle hashes are
1160             // still computed and checked, and any change will be caught at the next checkpoint.
1161             if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1162             {
1163                 // Verify signature
1164                 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1165                 {
1166                     // only during transition phase for P2SH: do not invoke anti-DoS code for
1167                     // potentially old clients relaying bad P2SH transactions
1168                     if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1169                         return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1170
1171                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1172                 }
1173             }
1174
1175             // Mark outpoints as spent
1176             txindex.vSpent[prevout.n] = posThisTx;
1177
1178             // Write back
1179             if (fBlock || fMiner)
1180             {
1181                 mapTestPool[prevout.hash] = txindex;
1182             }
1183         }
1184
1185         if (nValueIn < GetValueOut())
1186             return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1187
1188         // Tally transaction fees
1189         int64 nTxFee = nValueIn - GetValueOut();
1190         if (nTxFee < 0)
1191             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1192         nFees += nTxFee;
1193         if (!MoneyRange(nFees))
1194             return DoS(100, error("ConnectInputs() : nFees out of range"));
1195     }
1196
1197     return true;
1198 }
1199
1200
1201 bool CTransaction::ClientConnectInputs()
1202 {
1203     if (IsCoinBase())
1204         return false;
1205
1206     // Take over previous transactions' spent pointers
1207     {
1208         LOCK(mempool.cs);
1209         int64 nValueIn = 0;
1210         for (unsigned int i = 0; i < vin.size(); i++)
1211         {
1212             // Get prev tx from single transactions in memory
1213             COutPoint prevout = vin[i].prevout;
1214             if (!mempool.exists(prevout.hash))
1215                 return false;
1216             CTransaction& txPrev = mempool.lookup(prevout.hash);
1217
1218             if (prevout.n >= txPrev.vout.size())
1219                 return false;
1220
1221             // Verify signature
1222             if (!VerifySignature(txPrev, *this, i, true, 0))
1223                 return error("ConnectInputs() : VerifySignature failed");
1224
1225             ///// this is redundant with the mempool.mapNextTx stuff,
1226             ///// not sure which I want to get rid of
1227             ///// this has to go away now that posNext is gone
1228             // // Check for conflicts
1229             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1230             //     return error("ConnectInputs() : prev tx already used");
1231             //
1232             // // Flag outpoints as used
1233             // txPrev.vout[prevout.n].posNext = posThisTx;
1234
1235             nValueIn += txPrev.vout[prevout.n].nValue;
1236
1237             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1238                 return error("ClientConnectInputs() : txin values out of range");
1239         }
1240         if (GetValueOut() > nValueIn)
1241             return false;
1242     }
1243
1244     return true;
1245 }
1246
1247
1248
1249
1250 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1251 {
1252     // Disconnect in reverse order
1253     for (int i = vtx.size()-1; i >= 0; i--)
1254         if (!vtx[i].DisconnectInputs(txdb))
1255             return false;
1256
1257     // Update block index on disk without changing it in memory.
1258     // The memory index structure will be changed after the db commits.
1259     if (pindex->pprev)
1260     {
1261         CDiskBlockIndex blockindexPrev(pindex->pprev);
1262         blockindexPrev.hashNext = 0;
1263         if (!txdb.WriteBlockIndex(blockindexPrev))
1264             return error("DisconnectBlock() : WriteBlockIndex failed");
1265     }
1266
1267     return true;
1268 }
1269
1270 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1271 {
1272     // Check it again in case a previous version let a bad block in
1273     if (!CheckBlock())
1274         return false;
1275
1276     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1277     // unless those are already completely spent.
1278     // If such overwrites are allowed, coinbases and transactions depending upon those
1279     // can be duplicated to remove the ability to spend the first instance -- even after
1280     // being sent to another address.
1281     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1282     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1283     // already refuses previously-known transaction id's entirely.
1284     // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1285     // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1286     if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1287     {
1288         BOOST_FOREACH(CTransaction& tx, vtx)
1289         {
1290             CTxIndex txindexOld;
1291             if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1292             {
1293                 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1294                     if (pos.IsNull())
1295                         return false;
1296             }
1297         }
1298     }
1299
1300     // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1301     int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1302     bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1303
1304     //// issue here: it doesn't know the version
1305     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
1306
1307     map<uint256, CTxIndex> mapQueuedChanges;
1308     int64 nFees = 0;
1309     unsigned int nSigOps = 0;
1310     BOOST_FOREACH(CTransaction& tx, vtx)
1311     {
1312         nSigOps += tx.GetLegacySigOpCount();
1313         if (nSigOps > MAX_BLOCK_SIGOPS)
1314             return DoS(100, error("ConnectBlock() : too many sigops"));
1315
1316         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1317         nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1318
1319         MapPrevTx mapInputs;
1320         if (!tx.IsCoinBase())
1321         {
1322             bool fInvalid;
1323             if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1324                 return false;
1325
1326             if (fStrictPayToScriptHash)
1327             {
1328                 // Add in sigops done by pay-to-script-hash inputs;
1329                 // this is to prevent a "rogue miner" from creating
1330                 // an incredibly-expensive-to-validate block.
1331                 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1332                 if (nSigOps > MAX_BLOCK_SIGOPS)
1333                     return DoS(100, error("ConnectBlock() : too many sigops"));
1334             }
1335
1336             nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1337
1338             if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1339                 return false;
1340         }
1341
1342         mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1343     }
1344
1345     // Write queued txindex changes
1346     for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1347     {
1348         if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1349             return error("ConnectBlock() : UpdateTxIndex failed");
1350     }
1351
1352     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1353         return false;
1354
1355     // Update block index on disk without changing it in memory.
1356     // The memory index structure will be changed after the db commits.
1357     if (pindex->pprev)
1358     {
1359         CDiskBlockIndex blockindexPrev(pindex->pprev);
1360         blockindexPrev.hashNext = pindex->GetBlockHash();
1361         if (!txdb.WriteBlockIndex(blockindexPrev))
1362             return error("ConnectBlock() : WriteBlockIndex failed");
1363     }
1364
1365     // Watch for transactions paying to me
1366     BOOST_FOREACH(CTransaction& tx, vtx)
1367         SyncWithWallets(tx, this, true);
1368
1369     return true;
1370 }
1371
1372 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1373 {
1374     printf("REORGANIZE\n");
1375
1376     // Find the fork
1377     CBlockIndex* pfork = pindexBest;
1378     CBlockIndex* plonger = pindexNew;
1379     while (pfork != plonger)
1380     {
1381         while (plonger->nHeight > pfork->nHeight)
1382             if (!(plonger = plonger->pprev))
1383                 return error("Reorganize() : plonger->pprev is null");
1384         if (pfork == plonger)
1385             break;
1386         if (!(pfork = pfork->pprev))
1387             return error("Reorganize() : pfork->pprev is null");
1388     }
1389
1390     // List of what to disconnect
1391     vector<CBlockIndex*> vDisconnect;
1392     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1393         vDisconnect.push_back(pindex);
1394
1395     // List of what to connect
1396     vector<CBlockIndex*> vConnect;
1397     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1398         vConnect.push_back(pindex);
1399     reverse(vConnect.begin(), vConnect.end());
1400
1401     printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1402     printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1403
1404     // Disconnect shorter branch
1405     vector<CTransaction> vResurrect;
1406     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1407     {
1408         CBlock block;
1409         if (!block.ReadFromDisk(pindex))
1410             return error("Reorganize() : ReadFromDisk for disconnect failed");
1411         if (!block.DisconnectBlock(txdb, pindex))
1412             return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1413
1414         // Queue memory transactions to resurrect
1415         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1416             if (!tx.IsCoinBase())
1417                 vResurrect.push_back(tx);
1418     }
1419
1420     // Connect longer branch
1421     vector<CTransaction> vDelete;
1422     for (unsigned int i = 0; i < vConnect.size(); i++)
1423     {
1424         CBlockIndex* pindex = vConnect[i];
1425         CBlock block;
1426         if (!block.ReadFromDisk(pindex))
1427             return error("Reorganize() : ReadFromDisk for connect failed");
1428         if (!block.ConnectBlock(txdb, pindex))
1429         {
1430             // Invalid block
1431             txdb.TxnAbort();
1432             return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1433         }
1434
1435         // Queue memory transactions to delete
1436         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1437             vDelete.push_back(tx);
1438     }
1439     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1440         return error("Reorganize() : WriteHashBestChain failed");
1441
1442     // Make sure it's successfully written to disk before changing memory structure
1443     if (!txdb.TxnCommit())
1444         return error("Reorganize() : TxnCommit failed");
1445
1446     // Disconnect shorter branch
1447     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1448         if (pindex->pprev)
1449             pindex->pprev->pnext = NULL;
1450
1451     // Connect longer branch
1452     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1453         if (pindex->pprev)
1454             pindex->pprev->pnext = pindex;
1455
1456     // Resurrect memory transactions that were in the disconnected branch
1457     BOOST_FOREACH(CTransaction& tx, vResurrect)
1458         tx.AcceptToMemoryPool(txdb, false);
1459
1460     // Delete redundant memory transactions that are in the connected branch
1461     BOOST_FOREACH(CTransaction& tx, vDelete)
1462         mempool.remove(tx);
1463
1464     printf("REORGANIZE: done\n");
1465
1466     return true;
1467 }
1468
1469
1470 static void
1471 runCommand(std::string strCommand)
1472 {
1473     int nErr = ::system(strCommand.c_str());
1474     if (nErr)
1475         printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1476 }
1477
1478 // Called from inside SetBestChain: attaches a block to the new best chain being built
1479 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1480 {
1481     uint256 hash = GetHash();
1482
1483     // Adding to current best branch
1484     if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1485     {
1486         txdb.TxnAbort();
1487         InvalidChainFound(pindexNew);
1488         return false;
1489     }
1490     if (!txdb.TxnCommit())
1491         return error("SetBestChain() : TxnCommit failed");
1492
1493     // Add to current best branch
1494     pindexNew->pprev->pnext = pindexNew;
1495
1496     // Delete redundant memory transactions
1497     BOOST_FOREACH(CTransaction& tx, vtx)
1498         mempool.remove(tx);
1499
1500     return true;
1501 }
1502
1503 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1504 {
1505     uint256 hash = GetHash();
1506
1507     txdb.TxnBegin();
1508     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1509     {
1510         txdb.WriteHashBestChain(hash);
1511         if (!txdb.TxnCommit())
1512             return error("SetBestChain() : TxnCommit failed");
1513         pindexGenesisBlock = pindexNew;
1514     }
1515     else if (hashPrevBlock == hashBestChain)
1516     {
1517         if (!SetBestChainInner(txdb, pindexNew))
1518             return error("SetBestChain() : SetBestChainInner failed");
1519     }
1520     else
1521     {
1522         // the first block in the new chain that will cause it to become the new best chain
1523         CBlockIndex *pindexIntermediate = pindexNew;
1524
1525         // list of blocks that need to be connected afterwards
1526         std::vector<CBlockIndex*> vpindexSecondary;
1527
1528         // Reorganize is costly in terms of db load, as it works in a single db transaction.
1529         // Try to limit how much needs to be done inside
1530         while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
1531         {
1532             vpindexSecondary.push_back(pindexIntermediate);
1533             pindexIntermediate = pindexIntermediate->pprev;
1534         }
1535
1536         if (!vpindexSecondary.empty())
1537             printf("Postponing %i reconnects\n", vpindexSecondary.size());
1538
1539         // Switch to new best branch
1540         if (!Reorganize(txdb, pindexIntermediate))
1541         {
1542             txdb.TxnAbort();
1543             InvalidChainFound(pindexNew);
1544             return error("SetBestChain() : Reorganize failed");
1545         }
1546
1547         // Connect futher blocks
1548         BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1549         {
1550             CBlock block;
1551             if (!block.ReadFromDisk(pindex))
1552             {
1553                 printf("SetBestChain() : ReadFromDisk failed\n");
1554                 break;
1555             }
1556             txdb.TxnBegin();
1557             // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1558             if (!block.SetBestChainInner(txdb, pindex))
1559                 break;
1560         }
1561     }
1562
1563     // Update best block in wallet (so we can detect restored wallets)
1564     bool fIsInitialDownload = IsInitialBlockDownload();
1565     if (!fIsInitialDownload)
1566     {
1567         const CBlockLocator locator(pindexNew);
1568         ::SetBestChain(locator);
1569     }
1570
1571     // New best block
1572     hashBestChain = hash;
1573     pindexBest = pindexNew;
1574     nBestHeight = pindexBest->nHeight;
1575     bnBestChainWork = pindexNew->bnChainWork;
1576     nTimeBestReceived = GetTime();
1577     nTransactionsUpdated++;
1578     printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1579
1580     std::string strCmd = GetArg("-blocknotify", "");
1581
1582     if (!fIsInitialDownload && !strCmd.empty())
1583     {
1584         boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1585         boost::thread t(runCommand, strCmd); // thread runs free
1586     }
1587
1588     return true;
1589 }
1590
1591
1592 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1593 {
1594     // Check for duplicate
1595     uint256 hash = GetHash();
1596     if (mapBlockIndex.count(hash))
1597         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1598
1599     // Construct new block index object
1600     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1601     if (!pindexNew)
1602         return error("AddToBlockIndex() : new CBlockIndex failed");
1603     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1604     pindexNew->phashBlock = &((*mi).first);
1605     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1606     if (miPrev != mapBlockIndex.end())
1607     {
1608         pindexNew->pprev = (*miPrev).second;
1609         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1610     }
1611     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1612
1613     CTxDB txdb;
1614     txdb.TxnBegin();
1615     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1616     if (!txdb.TxnCommit())
1617         return false;
1618
1619     // New best
1620     if (pindexNew->bnChainWork > bnBestChainWork)
1621         if (!SetBestChain(txdb, pindexNew))
1622             return false;
1623
1624     txdb.Close();
1625
1626     if (pindexNew == pindexBest)
1627     {
1628         // Notify UI to display prev block's coinbase if it was ours
1629         static uint256 hashPrevBestCoinBase;
1630         UpdatedTransaction(hashPrevBestCoinBase);
1631         hashPrevBestCoinBase = vtx[0].GetHash();
1632     }
1633
1634     MainFrameRepaint();
1635     return true;
1636 }
1637
1638
1639
1640
1641 bool CBlock::CheckBlock() const
1642 {
1643     // These are checks that are independent of context
1644     // that can be verified before saving an orphan block.
1645
1646     // Size limits
1647     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1648         return DoS(100, error("CheckBlock() : size limits failed"));
1649
1650     // Check proof of work matches claimed amount
1651     if (!CheckProofOfWork(GetHash(), nBits))
1652         return DoS(50, error("CheckBlock() : proof of work failed"));
1653
1654     // Check timestamp
1655     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1656         return error("CheckBlock() : block timestamp too far in the future");
1657
1658     // First transaction must be coinbase, the rest must not be
1659     if (vtx.empty() || !vtx[0].IsCoinBase())
1660         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1661     for (unsigned int i = 1; i < vtx.size(); i++)
1662         if (vtx[i].IsCoinBase())
1663             return DoS(100, error("CheckBlock() : more than one coinbase"));
1664
1665     // Check transactions
1666     BOOST_FOREACH(const CTransaction& tx, vtx)
1667         if (!tx.CheckTransaction())
1668             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1669
1670     // Check for duplicate txids. This is caught by ConnectInputs(),
1671     // but catching it earlier avoids a potential DoS attack:
1672     set<uint256> uniqueTx;
1673     BOOST_FOREACH(const CTransaction& tx, vtx)
1674     {
1675         uniqueTx.insert(tx.GetHash());
1676     }
1677     if (uniqueTx.size() != vtx.size())
1678         return DoS(100, error("CheckBlock() : duplicate transaction"));
1679
1680     unsigned int nSigOps = 0;
1681     BOOST_FOREACH(const CTransaction& tx, vtx)
1682     {
1683         nSigOps += tx.GetLegacySigOpCount();
1684     }
1685     if (nSigOps > MAX_BLOCK_SIGOPS)
1686         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1687
1688     // Check merkleroot
1689     if (hashMerkleRoot != BuildMerkleTree())
1690         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1691
1692     return true;
1693 }
1694
1695 bool CBlock::AcceptBlock()
1696 {
1697     // Check for duplicate
1698     uint256 hash = GetHash();
1699     if (mapBlockIndex.count(hash))
1700         return error("AcceptBlock() : block already in mapBlockIndex");
1701
1702     // Get prev block index
1703     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1704     if (mi == mapBlockIndex.end())
1705         return DoS(10, error("AcceptBlock() : prev block not found"));
1706     CBlockIndex* pindexPrev = (*mi).second;
1707     int nHeight = pindexPrev->nHeight+1;
1708
1709     // Check proof of work
1710     if (nBits != GetNextWorkRequired(pindexPrev, this))
1711         return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1712
1713     // Check timestamp against prev
1714     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1715         return error("AcceptBlock() : block's timestamp is too early");
1716
1717     // Check that all transactions are finalized
1718     BOOST_FOREACH(const CTransaction& tx, vtx)
1719         if (!tx.IsFinal(nHeight, GetBlockTime()))
1720             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1721
1722     // Check that the block chain matches the known block chain up to a checkpoint
1723     if (!Checkpoints::CheckBlock(nHeight, hash))
1724         return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1725
1726     // Write block to history file
1727     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1728         return error("AcceptBlock() : out of disk space");
1729     unsigned int nFile = -1;
1730     unsigned int nBlockPos = 0;
1731     if (!WriteToDisk(nFile, nBlockPos))
1732         return error("AcceptBlock() : WriteToDisk failed");
1733     if (!AddToBlockIndex(nFile, nBlockPos))
1734         return error("AcceptBlock() : AddToBlockIndex failed");
1735
1736     // Relay inventory, but don't relay old inventory during initial block download
1737     int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1738     if (hashBestChain == hash)
1739     {
1740         LOCK(cs_vNodes);
1741         BOOST_FOREACH(CNode* pnode, vNodes)
1742             if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1743                 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1744     }
1745
1746     return true;
1747 }
1748
1749 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1750 {
1751     // Check for duplicate
1752     uint256 hash = pblock->GetHash();
1753     if (mapBlockIndex.count(hash))
1754         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1755     if (mapOrphanBlocks.count(hash))
1756         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1757
1758     // Preliminary checks
1759     if (!pblock->CheckBlock())
1760         return error("ProcessBlock() : CheckBlock FAILED");
1761
1762     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1763     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1764     {
1765         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1766         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1767         if (deltaTime < 0)
1768         {
1769             if (pfrom)
1770                 pfrom->Misbehaving(100);
1771             return error("ProcessBlock() : block with timestamp before last checkpoint");
1772         }
1773         CBigNum bnNewBlock;
1774         bnNewBlock.SetCompact(pblock->nBits);
1775         CBigNum bnRequired;
1776         bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1777         if (bnNewBlock > bnRequired)
1778         {
1779             if (pfrom)
1780                 pfrom->Misbehaving(100);
1781             return error("ProcessBlock() : block with too little proof-of-work");
1782         }
1783     }
1784
1785
1786     // If don't already have its previous block, shunt it off to holding area until we get it
1787     if (!mapBlockIndex.count(pblock->hashPrevBlock))
1788     {
1789         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1790         CBlock* pblock2 = new CBlock(*pblock);
1791         mapOrphanBlocks.insert(make_pair(hash, pblock2));
1792         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1793
1794         // Ask this guy to fill in what we're missing
1795         if (pfrom)
1796             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1797         return true;
1798     }
1799
1800     // Store to disk
1801     if (!pblock->AcceptBlock())
1802         return error("ProcessBlock() : AcceptBlock FAILED");
1803
1804     // Recursively process any orphan blocks that depended on this one
1805     vector<uint256> vWorkQueue;
1806     vWorkQueue.push_back(hash);
1807     for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1808     {
1809         uint256 hashPrev = vWorkQueue[i];
1810         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1811              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1812              ++mi)
1813         {
1814             CBlock* pblockOrphan = (*mi).second;
1815             if (pblockOrphan->AcceptBlock())
1816                 vWorkQueue.push_back(pblockOrphan->GetHash());
1817             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1818             delete pblockOrphan;
1819         }
1820         mapOrphanBlocksByPrev.erase(hashPrev);
1821     }
1822
1823     printf("ProcessBlock: ACCEPTED\n");
1824     return true;
1825 }
1826
1827
1828
1829
1830
1831
1832
1833
1834 bool CheckDiskSpace(uint64 nAdditionalBytes)
1835 {
1836     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1837
1838     // Check for 15MB because database could create another 10MB log file at any time
1839     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1840     {
1841         fShutdown = true;
1842         string strMessage = _("Warning: Disk space is low  ");
1843         strMiscWarning = strMessage;
1844         printf("*** %s\n", strMessage.c_str());
1845         ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
1846         QueueShutdown();
1847         return false;
1848     }
1849     return true;
1850 }
1851
1852 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1853 {
1854     if (nFile == -1)
1855         return NULL;
1856     FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
1857     if (!file)
1858         return NULL;
1859     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1860     {
1861         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1862         {
1863             fclose(file);
1864             return NULL;
1865         }
1866     }
1867     return file;
1868 }
1869
1870 static unsigned int nCurrentBlockFile = 1;
1871
1872 FILE* AppendBlockFile(unsigned int& nFileRet)
1873 {
1874     nFileRet = 0;
1875     loop
1876     {
1877         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1878         if (!file)
1879             return NULL;
1880         if (fseek(file, 0, SEEK_END) != 0)
1881             return NULL;
1882         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1883         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1884         {
1885             nFileRet = nCurrentBlockFile;
1886             return file;
1887         }
1888         fclose(file);
1889         nCurrentBlockFile++;
1890     }
1891 }
1892
1893 bool LoadBlockIndex(bool fAllowNew)
1894 {
1895     if (fTestNet)
1896     {
1897         hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1898         bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1899         pchMessageStart[0] = 0xfa;
1900         pchMessageStart[1] = 0xbf;
1901         pchMessageStart[2] = 0xb5;
1902         pchMessageStart[3] = 0xda;
1903     }
1904
1905     //
1906     // Load block index
1907     //
1908     CTxDB txdb("cr");
1909     if (!txdb.LoadBlockIndex())
1910         return false;
1911     txdb.Close();
1912
1913     //
1914     // Init with genesis block
1915     //
1916     if (mapBlockIndex.empty())
1917     {
1918         if (!fAllowNew)
1919             return false;
1920
1921         // Genesis Block:
1922         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1923         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1924         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1925         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1926         //   vMerkleTree: 4a5e1e
1927
1928         // Genesis block
1929         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1930         CTransaction txNew;
1931         txNew.vin.resize(1);
1932         txNew.vout.resize(1);
1933         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1934         txNew.vout[0].nValue = 50 * COIN;
1935         txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1936         CBlock block;
1937         block.vtx.push_back(txNew);
1938         block.hashPrevBlock = 0;
1939         block.hashMerkleRoot = block.BuildMerkleTree();
1940         block.nVersion = 1;
1941         block.nTime    = 1231006505;
1942         block.nBits    = 0x1d00ffff;
1943         block.nNonce   = 2083236893;
1944
1945         if (fTestNet)
1946         {
1947             block.nTime    = 1296688602;
1948             block.nBits    = 0x1d07fff8;
1949             block.nNonce   = 384568319;
1950         }
1951
1952         //// debug print
1953         printf("%s\n", block.GetHash().ToString().c_str());
1954         printf("%s\n", hashGenesisBlock.ToString().c_str());
1955         printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1956         assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1957         block.print();
1958         assert(block.GetHash() == hashGenesisBlock);
1959
1960         // Start new block file
1961         unsigned int nFile;
1962         unsigned int nBlockPos;
1963         if (!block.WriteToDisk(nFile, nBlockPos))
1964             return error("LoadBlockIndex() : writing genesis block to disk failed");
1965         if (!block.AddToBlockIndex(nFile, nBlockPos))
1966             return error("LoadBlockIndex() : genesis block not accepted");
1967     }
1968
1969     return true;
1970 }
1971
1972
1973
1974 void PrintBlockTree()
1975 {
1976     // precompute tree structure
1977     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1978     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1979     {
1980         CBlockIndex* pindex = (*mi).second;
1981         mapNext[pindex->pprev].push_back(pindex);
1982         // test
1983         //while (rand() % 3 == 0)
1984         //    mapNext[pindex->pprev].push_back(pindex);
1985     }
1986
1987     vector<pair<int, CBlockIndex*> > vStack;
1988     vStack.push_back(make_pair(0, pindexGenesisBlock));
1989
1990     int nPrevCol = 0;
1991     while (!vStack.empty())
1992     {
1993         int nCol = vStack.back().first;
1994         CBlockIndex* pindex = vStack.back().second;
1995         vStack.pop_back();
1996
1997         // print split or gap
1998         if (nCol > nPrevCol)
1999         {
2000             for (int i = 0; i < nCol-1; i++)
2001                 printf("| ");
2002             printf("|\\\n");
2003         }
2004         else if (nCol < nPrevCol)
2005         {
2006             for (int i = 0; i < nCol; i++)
2007                 printf("| ");
2008             printf("|\n");
2009        }
2010         nPrevCol = nCol;
2011
2012         // print columns
2013         for (int i = 0; i < nCol; i++)
2014             printf("| ");
2015
2016         // print item
2017         CBlock block;
2018         block.ReadFromDisk(pindex);
2019         printf("%d (%u,%u) %s  %s  tx %d",
2020             pindex->nHeight,
2021             pindex->nFile,
2022             pindex->nBlockPos,
2023             block.GetHash().ToString().substr(0,20).c_str(),
2024             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2025             block.vtx.size());
2026
2027         PrintWallets(block);
2028
2029         // put the main timechain first
2030         vector<CBlockIndex*>& vNext = mapNext[pindex];
2031         for (unsigned int i = 0; i < vNext.size(); i++)
2032         {
2033             if (vNext[i]->pnext)
2034             {
2035                 swap(vNext[0], vNext[i]);
2036                 break;
2037             }
2038         }
2039
2040         // iterate children
2041         for (unsigned int i = 0; i < vNext.size(); i++)
2042             vStack.push_back(make_pair(nCol+i, vNext[i]));
2043     }
2044 }
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055 //////////////////////////////////////////////////////////////////////////////
2056 //
2057 // CAlert
2058 //
2059
2060 map<uint256, CAlert> mapAlerts;
2061 CCriticalSection cs_mapAlerts;
2062
2063 string GetWarnings(string strFor)
2064 {
2065     int nPriority = 0;
2066     string strStatusBar;
2067     string strRPC;
2068     if (GetBoolArg("-testsafemode"))
2069         strRPC = "test";
2070
2071     // Misc warnings like out of disk space and clock is wrong
2072     if (strMiscWarning != "")
2073     {
2074         nPriority = 1000;
2075         strStatusBar = strMiscWarning;
2076     }
2077
2078     // Longer invalid proof-of-work chain
2079     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2080     {
2081         nPriority = 2000;
2082         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
2083     }
2084
2085     // Alerts
2086     {
2087         LOCK(cs_mapAlerts);
2088         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2089         {
2090             const CAlert& alert = item.second;
2091             if (alert.AppliesToMe() && alert.nPriority > nPriority)
2092             {
2093                 nPriority = alert.nPriority;
2094                 strStatusBar = alert.strStatusBar;
2095             }
2096         }
2097     }
2098
2099     if (strFor == "statusbar")
2100         return strStatusBar;
2101     else if (strFor == "rpc")
2102         return strRPC;
2103     assert(!"GetWarnings() : invalid parameter");
2104     return "error";
2105 }
2106
2107 bool CAlert::ProcessAlert()
2108 {
2109     if (!CheckSignature())
2110         return false;
2111     if (!IsInEffect())
2112         return false;
2113
2114     {
2115         LOCK(cs_mapAlerts);
2116         // Cancel previous alerts
2117         for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2118         {
2119             const CAlert& alert = (*mi).second;
2120             if (Cancels(alert))
2121             {
2122                 printf("cancelling alert %d\n", alert.nID);
2123                 mapAlerts.erase(mi++);
2124             }
2125             else if (!alert.IsInEffect())
2126             {
2127                 printf("expiring alert %d\n", alert.nID);
2128                 mapAlerts.erase(mi++);
2129             }
2130             else
2131                 mi++;
2132         }
2133
2134         // Check if this alert has been cancelled
2135         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2136         {
2137             const CAlert& alert = item.second;
2138             if (alert.Cancels(*this))
2139             {
2140                 printf("alert already cancelled by %d\n", alert.nID);
2141                 return false;
2142             }
2143         }
2144
2145         // Add to mapAlerts
2146         mapAlerts.insert(make_pair(GetHash(), *this));
2147     }
2148
2149     printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2150     MainFrameRepaint();
2151     return true;
2152 }
2153
2154
2155
2156
2157
2158
2159
2160
2161 //////////////////////////////////////////////////////////////////////////////
2162 //
2163 // Messages
2164 //
2165
2166
2167 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2168 {
2169     switch (inv.type)
2170     {
2171     case MSG_TX:
2172         {
2173         bool txInMap = false;
2174             {
2175             LOCK(mempool.cs);
2176             txInMap = (mempool.exists(inv.hash));
2177             }
2178         return txInMap ||
2179                mapOrphanTransactions.count(inv.hash) ||
2180                txdb.ContainsTx(inv.hash);
2181         }
2182
2183     case MSG_BLOCK:
2184         return mapBlockIndex.count(inv.hash) ||
2185                mapOrphanBlocks.count(inv.hash);
2186     }
2187     // Don't know what it is, just say we already got one
2188     return true;
2189 }
2190
2191
2192
2193
2194 // The message start string is designed to be unlikely to occur in normal data.
2195 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2196 // a large 4-byte int at any alignment.
2197 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2198
2199
2200 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2201 {
2202     static map<CService, vector<unsigned char> > mapReuseKey;
2203     RandAddSeedPerfmon();
2204     if (fDebug) {
2205         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2206         printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2207     }
2208     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2209     {
2210         printf("dropmessagestest DROPPING RECV MESSAGE\n");
2211         return true;
2212     }
2213
2214
2215
2216
2217
2218     if (strCommand == "version")
2219     {
2220         // Each connection can only send one version message
2221         if (pfrom->nVersion != 0)
2222         {
2223             pfrom->Misbehaving(1);
2224             return false;
2225         }
2226
2227         int64 nTime;
2228         CAddress addrMe;
2229         CAddress addrFrom;
2230         uint64 nNonce = 1;
2231         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2232         if (pfrom->nVersion < MIN_PROTO_VERSION)
2233         {
2234             // Since February 20, 2012, the protocol is initiated at version 209,
2235             // and earlier versions are no longer supported
2236             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2237             pfrom->fDisconnect = true;
2238             return false;
2239         }
2240
2241         if (pfrom->nVersion == 10300)
2242             pfrom->nVersion = 300;
2243         if (!vRecv.empty())
2244             vRecv >> addrFrom >> nNonce;
2245         if (!vRecv.empty())
2246             vRecv >> pfrom->strSubVer;
2247         if (!vRecv.empty())
2248             vRecv >> pfrom->nStartingHeight;
2249
2250         // Disconnect if we connected to ourself
2251         if (nNonce == nLocalHostNonce && nNonce > 1)
2252         {
2253             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2254             pfrom->fDisconnect = true;
2255             return true;
2256         }
2257
2258         // Be shy and don't send version until we hear
2259         if (pfrom->fInbound)
2260             pfrom->PushVersion();
2261
2262         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2263
2264         AddTimeData(pfrom->addr, nTime);
2265
2266         // Change version
2267         pfrom->PushMessage("verack");
2268         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2269
2270         if (!pfrom->fInbound)
2271         {
2272             // Advertise our address
2273             if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2274                 !IsInitialBlockDownload())
2275             {
2276                 CAddress addr(addrLocalHost);
2277                 addr.nTime = GetAdjustedTime();
2278                 pfrom->PushAddress(addr);
2279             }
2280
2281             // Get recent addresses
2282             if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2283             {
2284                 pfrom->PushMessage("getaddr");
2285                 pfrom->fGetAddr = true;
2286             }
2287             addrman.Good(pfrom->addr);
2288         } else {
2289             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2290             {
2291                 addrman.Add(addrFrom, addrFrom);
2292                 addrman.Good(addrFrom);
2293             }
2294         }
2295
2296         // Ask the first connected node for block updates
2297         static int nAskedForBlocks = 0;
2298         if (!pfrom->fClient &&
2299             (pfrom->nVersion < NOBLKS_VERSION_START ||
2300              pfrom->nVersion >= NOBLKS_VERSION_END) &&
2301              (nAskedForBlocks < 1 || vNodes.size() <= 1))
2302         {
2303             nAskedForBlocks++;
2304             pfrom->PushGetBlocks(pindexBest, uint256(0));
2305         }
2306
2307         // Relay alerts
2308         {
2309             LOCK(cs_mapAlerts);
2310             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2311                 item.second.RelayTo(pfrom);
2312         }
2313
2314         pfrom->fSuccessfullyConnected = true;
2315
2316         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2317
2318         cPeerBlockCounts.input(pfrom->nStartingHeight);
2319     }
2320
2321
2322     else if (pfrom->nVersion == 0)
2323     {
2324         // Must have a version message before anything else
2325         pfrom->Misbehaving(1);
2326         return false;
2327     }
2328
2329
2330     else if (strCommand == "verack")
2331     {
2332         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2333     }
2334
2335
2336     else if (strCommand == "addr")
2337     {
2338         vector<CAddress> vAddr;
2339         vRecv >> vAddr;
2340
2341         // Don't want addr from older versions unless seeding
2342         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2343             return true;
2344         if (vAddr.size() > 1000)
2345         {
2346             pfrom->Misbehaving(20);
2347             return error("message addr size() = %d", vAddr.size());
2348         }
2349
2350         // Store the new addresses
2351         int64 nNow = GetAdjustedTime();
2352         int64 nSince = nNow - 10 * 60;
2353         BOOST_FOREACH(CAddress& addr, vAddr)
2354         {
2355             if (fShutdown)
2356                 return true;
2357             // ignore IPv6 for now, since it isn't implemented anyway
2358             if (!addr.IsIPv4())
2359                 continue;
2360             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2361                 addr.nTime = nNow - 5 * 24 * 60 * 60;
2362             pfrom->AddAddressKnown(addr);
2363             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2364             {
2365                 // Relay to a limited number of other nodes
2366                 {
2367                     LOCK(cs_vNodes);
2368                     // Use deterministic randomness to send to the same nodes for 24 hours
2369                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2370                     static uint256 hashSalt;
2371                     if (hashSalt == 0)
2372                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2373                     int64 hashAddr = addr.GetHash();
2374                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2375                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2376                     multimap<uint256, CNode*> mapMix;
2377                     BOOST_FOREACH(CNode* pnode, vNodes)
2378                     {
2379                         if (pnode->nVersion < CADDR_TIME_VERSION)
2380                             continue;
2381                         unsigned int nPointer;
2382                         memcpy(&nPointer, &pnode, sizeof(nPointer));
2383                         uint256 hashKey = hashRand ^ nPointer;
2384                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
2385                         mapMix.insert(make_pair(hashKey, pnode));
2386                     }
2387                     int nRelayNodes = 2;
2388                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2389                         ((*mi).second)->PushAddress(addr);
2390                 }
2391             }
2392         }
2393         addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2394         if (vAddr.size() < 1000)
2395             pfrom->fGetAddr = false;
2396     }
2397
2398
2399     else if (strCommand == "inv")
2400     {
2401         vector<CInv> vInv;
2402         vRecv >> vInv;
2403         if (vInv.size() > 50000)
2404         {
2405             pfrom->Misbehaving(20);
2406             return error("message inv size() = %d", vInv.size());
2407         }
2408
2409         CTxDB txdb("r");
2410         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2411         {
2412             const CInv &inv = vInv[nInv];
2413
2414             if (fShutdown)
2415                 return true;
2416             pfrom->AddInventoryKnown(inv);
2417
2418             bool fAlreadyHave = AlreadyHave(txdb, inv);
2419             if (fDebug)
2420                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2421
2422             // Always request the last block in an inv bundle (even if we already have it), as it is the
2423             // trigger for the other side to send further invs. If we are stuck on a (very long) side chain,
2424             // this is necessary to connect earlier received orphan blocks to the chain again.
2425             if (!fAlreadyHave || (inv.type == MSG_BLOCK && nInv==vInv.size()-1))
2426                 pfrom->AskFor(inv);
2427             if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2428                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2429
2430             // Track requests for our stuff
2431             Inventory(inv.hash);
2432         }
2433     }
2434
2435
2436     else if (strCommand == "getdata")
2437     {
2438         vector<CInv> vInv;
2439         vRecv >> vInv;
2440         if (vInv.size() > 50000)
2441         {
2442             pfrom->Misbehaving(20);
2443             return error("message getdata size() = %d", vInv.size());
2444         }
2445
2446         BOOST_FOREACH(const CInv& inv, vInv)
2447         {
2448             if (fShutdown)
2449                 return true;
2450             printf("received getdata for: %s\n", inv.ToString().c_str());
2451
2452             if (inv.type == MSG_BLOCK)
2453             {
2454                 // Send block from disk
2455                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2456                 if (mi != mapBlockIndex.end())
2457                 {
2458                     CBlock block;
2459                     block.ReadFromDisk((*mi).second);
2460                     pfrom->PushMessage("block", block);
2461
2462                     // Trigger them to send a getblocks request for the next batch of inventory
2463                     if (inv.hash == pfrom->hashContinue)
2464                     {
2465                         // Bypass PushInventory, this must send even if redundant,
2466                         // and we want it right after the last block so they don't
2467                         // wait for other stuff first.
2468                         vector<CInv> vInv;
2469                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2470                         pfrom->PushMessage("inv", vInv);
2471                         pfrom->hashContinue = 0;
2472                     }
2473                 }
2474             }
2475             else if (inv.IsKnownType())
2476             {
2477                 // Send stream from relay memory
2478                 {
2479                     LOCK(cs_mapRelay);
2480                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2481                     if (mi != mapRelay.end())
2482                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2483                 }
2484             }
2485
2486             // Track requests for our stuff
2487             Inventory(inv.hash);
2488         }
2489     }
2490
2491
2492     else if (strCommand == "getblocks")
2493     {
2494         CBlockLocator locator;
2495         uint256 hashStop;
2496         vRecv >> locator >> hashStop;
2497
2498         // Find the last block the caller has in the main chain
2499         CBlockIndex* pindex = locator.GetBlockIndex();
2500
2501         // Send the rest of the chain
2502         if (pindex)
2503             pindex = pindex->pnext;
2504         int nLimit = 500 + locator.GetDistanceBack();
2505         unsigned int nBytes = 0;
2506         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2507         for (; pindex; pindex = pindex->pnext)
2508         {
2509             if (pindex->GetBlockHash() == hashStop)
2510             {
2511                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2512                 break;
2513             }
2514             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2515             CBlock block;
2516             block.ReadFromDisk(pindex, true);
2517             nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2518             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2519             {
2520                 // When this block is requested, we'll send an inv that'll make them
2521                 // getblocks the next batch of inventory.
2522                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2523                 pfrom->hashContinue = pindex->GetBlockHash();
2524                 break;
2525             }
2526         }
2527     }
2528
2529
2530     else if (strCommand == "getheaders")
2531     {
2532         CBlockLocator locator;
2533         uint256 hashStop;
2534         vRecv >> locator >> hashStop;
2535
2536         CBlockIndex* pindex = NULL;
2537         if (locator.IsNull())
2538         {
2539             // If locator is null, return the hashStop block
2540             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2541             if (mi == mapBlockIndex.end())
2542                 return true;
2543             pindex = (*mi).second;
2544         }
2545         else
2546         {
2547             // Find the last block the caller has in the main chain
2548             pindex = locator.GetBlockIndex();
2549             if (pindex)
2550                 pindex = pindex->pnext;
2551         }
2552
2553         vector<CBlock> vHeaders;
2554         int nLimit = 2000;
2555         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2556         for (; pindex; pindex = pindex->pnext)
2557         {
2558             vHeaders.push_back(pindex->GetBlockHeader());
2559             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2560                 break;
2561         }
2562         pfrom->PushMessage("headers", vHeaders);
2563     }
2564
2565
2566     else if (strCommand == "tx")
2567     {
2568         vector<uint256> vWorkQueue;
2569         vector<uint256> vEraseQueue;
2570         CDataStream vMsg(vRecv);
2571         CTxDB txdb("r");
2572         CTransaction tx;
2573         vRecv >> tx;
2574
2575         CInv inv(MSG_TX, tx.GetHash());
2576         pfrom->AddInventoryKnown(inv);
2577
2578         bool fMissingInputs = false;
2579         if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2580         {
2581             SyncWithWallets(tx, NULL, true);
2582             RelayMessage(inv, vMsg);
2583             mapAlreadyAskedFor.erase(inv);
2584             vWorkQueue.push_back(inv.hash);
2585             vEraseQueue.push_back(inv.hash);
2586
2587             // Recursively process any orphan transactions that depended on this one
2588             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2589             {
2590                 uint256 hashPrev = vWorkQueue[i];
2591                 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
2592                      mi != mapOrphanTransactionsByPrev[hashPrev].end();
2593                      ++mi)
2594                 {
2595                     const CDataStream& vMsg = *((*mi).second);
2596                     CTransaction tx;
2597                     CDataStream(vMsg) >> tx;
2598                     CInv inv(MSG_TX, tx.GetHash());
2599                     bool fMissingInputs2 = false;
2600
2601                     if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
2602                     {
2603                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2604                         SyncWithWallets(tx, NULL, true);
2605                         RelayMessage(inv, vMsg);
2606                         mapAlreadyAskedFor.erase(inv);
2607                         vWorkQueue.push_back(inv.hash);
2608                         vEraseQueue.push_back(inv.hash);
2609                     }
2610                     else if (!fMissingInputs2)
2611                     {
2612                         // invalid orphan
2613                         vEraseQueue.push_back(inv.hash);
2614                         printf("   removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2615                     }
2616                 }
2617             }
2618
2619             BOOST_FOREACH(uint256 hash, vEraseQueue)
2620                 EraseOrphanTx(hash);
2621         }
2622         else if (fMissingInputs)
2623         {
2624             AddOrphanTx(vMsg);
2625
2626             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2627             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2628             if (nEvicted > 0)
2629                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
2630         }
2631         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2632     }
2633
2634
2635     else if (strCommand == "block")
2636     {
2637         CBlock block;
2638         vRecv >> block;
2639
2640         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2641         // block.print();
2642
2643         CInv inv(MSG_BLOCK, block.GetHash());
2644         pfrom->AddInventoryKnown(inv);
2645
2646         if (ProcessBlock(pfrom, &block))
2647             mapAlreadyAskedFor.erase(inv);
2648         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2649     }
2650
2651
2652     else if (strCommand == "getaddr")
2653     {
2654         pfrom->vAddrToSend.clear();
2655         vector<CAddress> vAddr = addrman.GetAddr();
2656         BOOST_FOREACH(const CAddress &addr, vAddr)
2657             pfrom->PushAddress(addr);
2658     }
2659
2660
2661     else if (strCommand == "checkorder")
2662     {
2663         uint256 hashReply;
2664         vRecv >> hashReply;
2665
2666         if (!GetBoolArg("-allowreceivebyip"))
2667         {
2668             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2669             return true;
2670         }
2671
2672         CWalletTx order;
2673         vRecv >> order;
2674
2675         /// we have a chance to check the order here
2676
2677         // Keep giving the same key to the same ip until they use it
2678         if (!mapReuseKey.count(pfrom->addr))
2679             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2680
2681         // Send back approval of order and pubkey to use
2682         CScript scriptPubKey;
2683         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2684         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2685     }
2686
2687
2688     else if (strCommand == "reply")
2689     {
2690         uint256 hashReply;
2691         vRecv >> hashReply;
2692
2693         CRequestTracker tracker;
2694         {
2695             LOCK(pfrom->cs_mapRequests);
2696             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2697             if (mi != pfrom->mapRequests.end())
2698             {
2699                 tracker = (*mi).second;
2700                 pfrom->mapRequests.erase(mi);
2701             }
2702         }
2703         if (!tracker.IsNull())
2704             tracker.fn(tracker.param1, vRecv);
2705     }
2706
2707
2708     else if (strCommand == "ping")
2709     {
2710         if (pfrom->nVersion > BIP0031_VERSION)
2711         {
2712             uint64 nonce = 0;
2713             vRecv >> nonce;
2714             // Echo the message back with the nonce. This allows for two useful features:
2715             //
2716             // 1) A remote node can quickly check if the connection is operational
2717             // 2) Remote nodes can measure the latency of the network thread. If this node
2718             //    is overloaded it won't respond to pings quickly and the remote node can
2719             //    avoid sending us more work, like chain download requests.
2720             //
2721             // The nonce stops the remote getting confused between different pings: without
2722             // it, if the remote node sends a ping once per second and this node takes 5
2723             // seconds to respond to each, the 5th ping the remote sends would appear to
2724             // return very quickly.
2725             pfrom->PushMessage("pong", nonce);
2726         }
2727     }
2728
2729
2730     else if (strCommand == "alert")
2731     {
2732         CAlert alert;
2733         vRecv >> alert;
2734
2735         if (alert.ProcessAlert())
2736         {
2737             // Relay
2738             pfrom->setKnown.insert(alert.GetHash());
2739             {
2740                 LOCK(cs_vNodes);
2741                 BOOST_FOREACH(CNode* pnode, vNodes)
2742                     alert.RelayTo(pnode);
2743             }
2744         }
2745     }
2746
2747
2748     else
2749     {
2750         // Ignore unknown commands for extensibility
2751     }
2752
2753
2754     // Update the last seen time for this node's address
2755     if (pfrom->fNetworkNode)
2756         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2757             AddressCurrentlyConnected(pfrom->addr);
2758
2759
2760     return true;
2761 }
2762
2763 bool ProcessMessages(CNode* pfrom)
2764 {
2765     CDataStream& vRecv = pfrom->vRecv;
2766     if (vRecv.empty())
2767         return true;
2768     //if (fDebug)
2769     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2770
2771     //
2772     // Message format
2773     //  (4) message start
2774     //  (12) command
2775     //  (4) size
2776     //  (4) checksum
2777     //  (x) data
2778     //
2779
2780     loop
2781     {
2782         // Scan for message start
2783         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2784         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2785         if (vRecv.end() - pstart < nHeaderSize)
2786         {
2787             if ((int)vRecv.size() > nHeaderSize)
2788             {
2789                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2790                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2791             }
2792             break;
2793         }
2794         if (pstart - vRecv.begin() > 0)
2795             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2796         vRecv.erase(vRecv.begin(), pstart);
2797
2798         // Read header
2799         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2800         CMessageHeader hdr;
2801         vRecv >> hdr;
2802         if (!hdr.IsValid())
2803         {
2804             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2805             continue;
2806         }
2807         string strCommand = hdr.GetCommand();
2808
2809         // Message size
2810         unsigned int nMessageSize = hdr.nMessageSize;
2811         if (nMessageSize > MAX_SIZE)
2812         {
2813             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2814             continue;
2815         }
2816         if (nMessageSize > vRecv.size())
2817         {
2818             // Rewind and wait for rest of message
2819             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2820             break;
2821         }
2822
2823         // Checksum
2824         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2825         unsigned int nChecksum = 0;
2826         memcpy(&nChecksum, &hash, sizeof(nChecksum));
2827         if (nChecksum != hdr.nChecksum)
2828         {
2829             printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2830                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2831             continue;
2832         }
2833
2834         // Copy message to its own buffer
2835         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2836         vRecv.ignore(nMessageSize);
2837
2838         // Process message
2839         bool fRet = false;
2840         try
2841         {
2842             {
2843                 LOCK(cs_main);
2844                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2845             }
2846             if (fShutdown)
2847                 return true;
2848         }
2849         catch (std::ios_base::failure& e)
2850         {
2851             if (strstr(e.what(), "end of data"))
2852             {
2853                 // Allow exceptions from underlength message on vRecv
2854                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2855             }
2856             else if (strstr(e.what(), "size too large"))
2857             {
2858                 // Allow exceptions from overlong size
2859                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2860             }
2861             else
2862             {
2863                 PrintExceptionContinue(&e, "ProcessMessage()");
2864             }
2865         }
2866         catch (std::exception& e) {
2867             PrintExceptionContinue(&e, "ProcessMessage()");
2868         } catch (...) {
2869             PrintExceptionContinue(NULL, "ProcessMessage()");
2870         }
2871
2872         if (!fRet)
2873             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2874     }
2875
2876     vRecv.Compact();
2877     return true;
2878 }
2879
2880
2881 bool SendMessages(CNode* pto, bool fSendTrickle)
2882 {
2883     TRY_LOCK(cs_main, lockMain);
2884     if (lockMain) {
2885         // Don't send anything until we get their version message
2886         if (pto->nVersion == 0)
2887             return true;
2888
2889         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
2890         // right now.
2891         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
2892             if (pto->nVersion > BIP0031_VERSION)
2893                 pto->PushMessage("ping", 0);
2894             else
2895                 pto->PushMessage("ping");
2896         }
2897
2898         // Resend wallet transactions that haven't gotten in a block yet
2899         ResendWalletTransactions();
2900
2901         // Address refresh broadcast
2902         static int64 nLastRebroadcast;
2903         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
2904         {
2905             {
2906                 LOCK(cs_vNodes);
2907                 BOOST_FOREACH(CNode* pnode, vNodes)
2908                 {
2909                     // Periodically clear setAddrKnown to allow refresh broadcasts
2910                     if (nLastRebroadcast)
2911                         pnode->setAddrKnown.clear();
2912
2913                     // Rebroadcast our address
2914                     if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
2915                     {
2916                         CAddress addr(addrLocalHost);
2917                         addr.nTime = GetAdjustedTime();
2918                         pnode->PushAddress(addr);
2919                     }
2920                 }
2921             }
2922             nLastRebroadcast = GetTime();
2923         }
2924
2925         //
2926         // Message: addr
2927         //
2928         if (fSendTrickle)
2929         {
2930             vector<CAddress> vAddr;
2931             vAddr.reserve(pto->vAddrToSend.size());
2932             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2933             {
2934                 // returns true if wasn't already contained in the set
2935                 if (pto->setAddrKnown.insert(addr).second)
2936                 {
2937                     vAddr.push_back(addr);
2938                     // receiver rejects addr messages larger than 1000
2939                     if (vAddr.size() >= 1000)
2940                     {
2941                         pto->PushMessage("addr", vAddr);
2942                         vAddr.clear();
2943                     }
2944                 }
2945             }
2946             pto->vAddrToSend.clear();
2947             if (!vAddr.empty())
2948                 pto->PushMessage("addr", vAddr);
2949         }
2950
2951
2952         //
2953         // Message: inventory
2954         //
2955         vector<CInv> vInv;
2956         vector<CInv> vInvWait;
2957         {
2958             LOCK(pto->cs_inventory);
2959             vInv.reserve(pto->vInventoryToSend.size());
2960             vInvWait.reserve(pto->vInventoryToSend.size());
2961             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2962             {
2963                 if (pto->setInventoryKnown.count(inv))
2964                     continue;
2965
2966                 // trickle out tx inv to protect privacy
2967                 if (inv.type == MSG_TX && !fSendTrickle)
2968                 {
2969                     // 1/4 of tx invs blast to all immediately
2970                     static uint256 hashSalt;
2971                     if (hashSalt == 0)
2972                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2973                     uint256 hashRand = inv.hash ^ hashSalt;
2974                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2975                     bool fTrickleWait = ((hashRand & 3) != 0);
2976
2977                     // always trickle our own transactions
2978                     if (!fTrickleWait)
2979                     {
2980                         CWalletTx wtx;
2981                         if (GetTransaction(inv.hash, wtx))
2982                             if (wtx.fFromMe)
2983                                 fTrickleWait = true;
2984                     }
2985
2986                     if (fTrickleWait)
2987                     {
2988                         vInvWait.push_back(inv);
2989                         continue;
2990                     }
2991                 }
2992
2993                 // returns true if wasn't already contained in the set
2994                 if (pto->setInventoryKnown.insert(inv).second)
2995                 {
2996                     vInv.push_back(inv);
2997                     if (vInv.size() >= 1000)
2998                     {
2999                         pto->PushMessage("inv", vInv);
3000                         vInv.clear();
3001                     }
3002                 }
3003             }
3004             pto->vInventoryToSend = vInvWait;
3005         }
3006         if (!vInv.empty())
3007             pto->PushMessage("inv", vInv);
3008
3009
3010         //
3011         // Message: getdata
3012         //
3013         vector<CInv> vGetData;
3014         int64 nNow = GetTime() * 1000000;
3015         CTxDB txdb("r");
3016         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3017         {
3018             const CInv& inv = (*pto->mapAskFor.begin()).second;
3019             if (!AlreadyHave(txdb, inv))
3020             {
3021                 printf("sending getdata: %s\n", inv.ToString().c_str());
3022                 vGetData.push_back(inv);
3023                 if (vGetData.size() >= 1000)
3024                 {
3025                     pto->PushMessage("getdata", vGetData);
3026                     vGetData.clear();
3027                 }
3028             }
3029             mapAlreadyAskedFor[inv] = nNow;
3030             pto->mapAskFor.erase(pto->mapAskFor.begin());
3031         }
3032         if (!vGetData.empty())
3033             pto->PushMessage("getdata", vGetData);
3034
3035     }
3036     return true;
3037 }
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052 //////////////////////////////////////////////////////////////////////////////
3053 //
3054 // BitcoinMiner
3055 //
3056
3057 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3058 {
3059     unsigned char* pdata = (unsigned char*)pbuffer;
3060     unsigned int blocks = 1 + ((len + 8) / 64);
3061     unsigned char* pend = pdata + 64 * blocks;
3062     memset(pdata + len, 0, 64 * blocks - len);
3063     pdata[len] = 0x80;
3064     unsigned int bits = len * 8;
3065     pend[-1] = (bits >> 0) & 0xff;
3066     pend[-2] = (bits >> 8) & 0xff;
3067     pend[-3] = (bits >> 16) & 0xff;
3068     pend[-4] = (bits >> 24) & 0xff;
3069     return blocks;
3070 }
3071
3072 static const unsigned int pSHA256InitState[8] =
3073 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3074
3075 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3076 {
3077     SHA256_CTX ctx;
3078     unsigned char data[64];
3079
3080     SHA256_Init(&ctx);
3081
3082     for (int i = 0; i < 16; i++)
3083         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3084
3085     for (int i = 0; i < 8; i++)
3086         ctx.h[i] = ((uint32_t*)pinit)[i];
3087
3088     SHA256_Update(&ctx, data, sizeof(data));
3089     for (int i = 0; i < 8; i++)
3090         ((uint32_t*)pstate)[i] = ctx.h[i];
3091 }
3092
3093 //
3094 // ScanHash scans nonces looking for a hash with at least some zero bits.
3095 // It operates on big endian data.  Caller does the byte reversing.
3096 // All input buffers are 16-byte aligned.  nNonce is usually preserved
3097 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3098 // the block is rebuilt and nNonce starts over at zero.
3099 //
3100 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3101 {
3102     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3103     for (;;)
3104     {
3105         // Crypto++ SHA-256
3106         // Hash pdata using pmidstate as the starting state into
3107         // preformatted buffer phash1, then hash phash1 into phash
3108         nNonce++;
3109         SHA256Transform(phash1, pdata, pmidstate);
3110         SHA256Transform(phash, phash1, pSHA256InitState);
3111
3112         // Return the nonce if the hash has at least some zero bits,
3113         // caller will check if it has enough to reach the target
3114         if (((unsigned short*)phash)[14] == 0)
3115             return nNonce;
3116
3117         // If nothing found after trying for a while, return -1
3118         if ((nNonce & 0xffff) == 0)
3119         {
3120             nHashesDone = 0xffff+1;
3121             return (unsigned int) -1;
3122         }
3123     }
3124 }
3125
3126 // Some explaining would be appreciated
3127 class COrphan
3128 {
3129 public:
3130     CTransaction* ptx;
3131     set<uint256> setDependsOn;
3132     double dPriority;
3133
3134     COrphan(CTransaction* ptxIn)
3135     {
3136         ptx = ptxIn;
3137         dPriority = 0;
3138     }
3139
3140     void print() const
3141     {
3142         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3143         BOOST_FOREACH(uint256 hash, setDependsOn)
3144             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3145     }
3146 };
3147
3148
3149 uint64 nLastBlockTx = 0;
3150 uint64 nLastBlockSize = 0;
3151
3152 CBlock* CreateNewBlock(CReserveKey& reservekey)
3153 {
3154     CBlockIndex* pindexPrev = pindexBest;
3155
3156     // Create new block
3157     auto_ptr<CBlock> pblock(new CBlock());
3158     if (!pblock.get())
3159         return NULL;
3160
3161     // Create coinbase tx
3162     CTransaction txNew;
3163     txNew.vin.resize(1);
3164     txNew.vin[0].prevout.SetNull();
3165     txNew.vout.resize(1);
3166     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3167
3168     // Add our coinbase tx as first transaction
3169     pblock->vtx.push_back(txNew);
3170
3171     // Collect memory pool transactions into the block
3172     int64 nFees = 0;
3173     {
3174         LOCK2(cs_main, mempool.cs);
3175         CTxDB txdb("r");
3176
3177         // Priority order to process transactions
3178         list<COrphan> vOrphan; // list memory doesn't move
3179         map<uint256, vector<COrphan*> > mapDependers;
3180         multimap<double, CTransaction*> mapPriority;
3181         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3182         {
3183             CTransaction& tx = (*mi).second;
3184             if (tx.IsCoinBase() || !tx.IsFinal())
3185                 continue;
3186
3187             COrphan* porphan = NULL;
3188             double dPriority = 0;
3189             BOOST_FOREACH(const CTxIn& txin, tx.vin)
3190             {
3191                 // Read prev transaction
3192                 CTransaction txPrev;
3193                 CTxIndex txindex;
3194                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3195                 {
3196                     // Has to wait for dependencies
3197                     if (!porphan)
3198                     {
3199                         // Use list for automatic deletion
3200                         vOrphan.push_back(COrphan(&tx));
3201                         porphan = &vOrphan.back();
3202                     }
3203                     mapDependers[txin.prevout.hash].push_back(porphan);
3204                     porphan->setDependsOn.insert(txin.prevout.hash);
3205                     continue;
3206                 }
3207                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3208
3209                 // Read block header
3210                 int nConf = txindex.GetDepthInMainChain();
3211
3212                 dPriority += (double)nValueIn * nConf;
3213
3214                 if (fDebug && GetBoolArg("-printpriority"))
3215                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3216             }
3217
3218             // Priority is sum(valuein * age) / txsize
3219             dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3220
3221             if (porphan)
3222                 porphan->dPriority = dPriority;
3223             else
3224                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3225
3226             if (fDebug && GetBoolArg("-printpriority"))
3227             {
3228                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3229                 if (porphan)
3230                     porphan->print();
3231                 printf("\n");
3232             }
3233         }
3234
3235         // Collect transactions into block
3236         map<uint256, CTxIndex> mapTestPool;
3237         uint64 nBlockSize = 1000;
3238         uint64 nBlockTx = 0;
3239         int nBlockSigOps = 100;
3240         while (!mapPriority.empty())
3241         {
3242             // Take highest priority transaction off priority queue
3243             double dPriority = -(*mapPriority.begin()).first;
3244             CTransaction& tx = *(*mapPriority.begin()).second;
3245             mapPriority.erase(mapPriority.begin());
3246
3247             // Size limits
3248             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3249             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3250                 continue;
3251
3252             // Legacy limits on sigOps:
3253             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3254             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3255                 continue;
3256
3257             // Transaction fee required depends on block size
3258             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3259             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
3260
3261             // Connecting shouldn't fail due to dependency on other memory pool transactions
3262             // because we're already processing them in order of dependency
3263             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3264             MapPrevTx mapInputs;
3265             bool fInvalid;
3266             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3267                 continue;
3268
3269             int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3270             if (nTxFees < nMinFee)
3271                 continue;
3272
3273             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3274             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3275                 continue;
3276
3277             if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3278                 continue;
3279             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3280             swap(mapTestPool, mapTestPoolTmp);
3281
3282             // Added
3283             pblock->vtx.push_back(tx);
3284             nBlockSize += nTxSize;
3285             ++nBlockTx;
3286             nBlockSigOps += nTxSigOps;
3287             nFees += nTxFees;
3288
3289             // Add transactions that depend on this one to the priority queue
3290             uint256 hash = tx.GetHash();
3291             if (mapDependers.count(hash))
3292             {
3293                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3294                 {
3295                     if (!porphan->setDependsOn.empty())
3296                     {
3297                         porphan->setDependsOn.erase(hash);
3298                         if (porphan->setDependsOn.empty())
3299                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3300                     }
3301                 }
3302             }
3303         }
3304
3305         nLastBlockTx = nBlockTx;
3306         nLastBlockSize = nBlockSize;
3307         printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3308
3309     }
3310     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3311
3312     // Fill in header
3313     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3314     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3315     pblock->UpdateTime(pindexPrev);
3316     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock.get());
3317     pblock->nNonce         = 0;
3318
3319     return pblock.release();
3320 }
3321
3322
3323 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3324 {
3325     // Update nExtraNonce
3326     static uint256 hashPrevBlock;
3327     if (hashPrevBlock != pblock->hashPrevBlock)
3328     {
3329         nExtraNonce = 0;
3330         hashPrevBlock = pblock->hashPrevBlock;
3331     }
3332     ++nExtraNonce;
3333     pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3334     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3335
3336     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3337 }
3338
3339
3340 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3341 {
3342     //
3343     // Prebuild hash buffers
3344     //
3345     struct
3346     {
3347         struct unnamed2
3348         {
3349             int nVersion;
3350             uint256 hashPrevBlock;
3351             uint256 hashMerkleRoot;
3352             unsigned int nTime;
3353             unsigned int nBits;
3354             unsigned int nNonce;
3355         }
3356         block;
3357         unsigned char pchPadding0[64];
3358         uint256 hash1;
3359         unsigned char pchPadding1[64];
3360     }
3361     tmp;
3362     memset(&tmp, 0, sizeof(tmp));
3363
3364     tmp.block.nVersion       = pblock->nVersion;
3365     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
3366     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3367     tmp.block.nTime          = pblock->nTime;
3368     tmp.block.nBits          = pblock->nBits;
3369     tmp.block.nNonce         = pblock->nNonce;
3370
3371     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3372     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3373
3374     // Byte swap all the input buffer
3375     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3376         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3377
3378     // Precalc the first half of the first hash, which stays constant
3379     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3380
3381     memcpy(pdata, &tmp.block, 128);
3382     memcpy(phash1, &tmp.hash1, 64);
3383 }
3384
3385
3386 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3387 {
3388     uint256 hash = pblock->GetHash();
3389     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3390
3391     if (hash > hashTarget)
3392         return false;
3393
3394     //// debug print
3395     printf("BitcoinMiner:\n");
3396     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3397     pblock->print();
3398     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3399     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3400
3401     // Found a solution
3402     {
3403         LOCK(cs_main);
3404         if (pblock->hashPrevBlock != hashBestChain)
3405             return error("BitcoinMiner : generated block is stale");
3406
3407         // Remove key from key pool
3408         reservekey.KeepKey();
3409
3410         // Track how many getdata requests this block gets
3411         {
3412             LOCK(wallet.cs_wallet);
3413             wallet.mapRequestCount[pblock->GetHash()] = 0;
3414         }
3415
3416         // Process this block the same as if we had received it from another node
3417         if (!ProcessBlock(NULL, pblock))
3418             return error("BitcoinMiner : ProcessBlock, block not accepted");
3419     }
3420
3421     return true;
3422 }
3423
3424 void static ThreadBitcoinMiner(void* parg);
3425
3426 static bool fGenerateBitcoins = false;
3427 static bool fLimitProcessors = false;
3428 static int nLimitProcessors = -1;
3429
3430 void static BitcoinMiner(CWallet *pwallet)
3431 {
3432     printf("BitcoinMiner started\n");
3433     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3434
3435     // Each thread has its own key and counter
3436     CReserveKey reservekey(pwallet);
3437     unsigned int nExtraNonce = 0;
3438
3439     while (fGenerateBitcoins)
3440     {
3441         if (fShutdown)
3442             return;
3443         while (vNodes.empty() || IsInitialBlockDownload())
3444         {
3445             Sleep(1000);
3446             if (fShutdown)
3447                 return;
3448             if (!fGenerateBitcoins)
3449                 return;
3450         }
3451
3452
3453         //
3454         // Create new block
3455         //
3456         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3457         CBlockIndex* pindexPrev = pindexBest;
3458
3459         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3460         if (!pblock.get())
3461             return;
3462         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3463
3464         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3465
3466
3467         //
3468         // Prebuild hash buffers
3469         //
3470         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3471         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3472         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3473
3474         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3475
3476         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3477         unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3478         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3479
3480
3481         //
3482         // Search
3483         //
3484         int64 nStart = GetTime();
3485         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3486         uint256 hashbuf[2];
3487         uint256& hash = *alignup<16>(hashbuf);
3488         loop
3489         {
3490             unsigned int nHashesDone = 0;
3491             unsigned int nNonceFound;
3492
3493             // Crypto++ SHA-256
3494             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3495                                             (char*)&hash, nHashesDone);
3496
3497             // Check if something found
3498             if (nNonceFound != (unsigned int) -1)
3499             {
3500                 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3501                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3502
3503                 if (hash <= hashTarget)
3504                 {
3505                     // Found a solution
3506                     pblock->nNonce = ByteReverse(nNonceFound);
3507                     assert(hash == pblock->GetHash());
3508
3509                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3510                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3511                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3512                     break;
3513                 }
3514             }
3515
3516             // Meter hashes/sec
3517             static int64 nHashCounter;
3518             if (nHPSTimerStart == 0)
3519             {
3520                 nHPSTimerStart = GetTimeMillis();
3521                 nHashCounter = 0;
3522             }
3523             else
3524                 nHashCounter += nHashesDone;
3525             if (GetTimeMillis() - nHPSTimerStart > 4000)
3526             {
3527                 static CCriticalSection cs;
3528                 {
3529                     LOCK(cs);
3530                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3531                     {
3532                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3533                         nHPSTimerStart = GetTimeMillis();
3534                         nHashCounter = 0;
3535                         static int64 nLogTime;
3536                         if (GetTime() - nLogTime > 30 * 60)
3537                         {
3538                             nLogTime = GetTime();
3539                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3540                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3541                         }
3542                     }
3543                 }
3544             }
3545
3546             // Check for stop or if block needs to be rebuilt
3547             if (fShutdown)
3548                 return;
3549             if (!fGenerateBitcoins)
3550                 return;
3551             if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3552                 return;
3553             if (vNodes.empty())
3554                 break;
3555             if (nBlockNonce >= 0xffff0000)
3556                 break;
3557             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3558                 break;
3559             if (pindexPrev != pindexBest)
3560                 break;
3561
3562             // Update nTime every few seconds
3563             pblock->UpdateTime(pindexPrev);
3564             nBlockTime = ByteReverse(pblock->nTime);
3565             if (fTestNet)
3566             {
3567                 // Changing pblock->nTime can change work required on testnet:
3568                 nBlockBits = ByteReverse(pblock->nBits);
3569                 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3570             }
3571         }
3572     }
3573 }
3574
3575 void static ThreadBitcoinMiner(void* parg)
3576 {
3577     CWallet* pwallet = (CWallet*)parg;
3578     try
3579     {
3580         vnThreadsRunning[THREAD_MINER]++;
3581         BitcoinMiner(pwallet);
3582         vnThreadsRunning[THREAD_MINER]--;
3583     }
3584     catch (std::exception& e) {
3585         vnThreadsRunning[THREAD_MINER]--;
3586         PrintException(&e, "ThreadBitcoinMiner()");
3587     } catch (...) {
3588         vnThreadsRunning[THREAD_MINER]--;
3589         PrintException(NULL, "ThreadBitcoinMiner()");
3590     }
3591     nHPSTimerStart = 0;
3592     if (vnThreadsRunning[THREAD_MINER] == 0)
3593         dHashesPerSec = 0;
3594     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
3595 }
3596
3597
3598 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3599 {
3600     fGenerateBitcoins = fGenerate;
3601     nLimitProcessors = GetArg("-genproclimit", -1);
3602     if (nLimitProcessors == 0)
3603         fGenerateBitcoins = false;
3604     fLimitProcessors = (nLimitProcessors != -1);
3605
3606     if (fGenerate)
3607     {
3608         int nProcessors = boost::thread::hardware_concurrency();
3609         printf("%d processors\n", nProcessors);
3610         if (nProcessors < 1)
3611             nProcessors = 1;
3612         if (fLimitProcessors && nProcessors > nLimitProcessors)
3613             nProcessors = nLimitProcessors;
3614         int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
3615         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3616         for (int i = 0; i < nAddThreads; i++)
3617         {
3618             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3619                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3620             Sleep(10);
3621         }
3622     }
3623 }