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