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