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