Add casts for unavoidable signed/unsigned comparisons
[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     unsigned int nSigOps = 0;
1656     BOOST_FOREACH(const CTransaction& tx, vtx)
1657     {
1658         nSigOps += tx.GetLegacySigOpCount();
1659     }
1660     if (nSigOps > MAX_BLOCK_SIGOPS)
1661         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1662
1663     // Check merkleroot
1664     if (hashMerkleRoot != BuildMerkleTree())
1665         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1666
1667     return true;
1668 }
1669
1670 bool CBlock::AcceptBlock()
1671 {
1672     // Check for duplicate
1673     uint256 hash = GetHash();
1674     if (mapBlockIndex.count(hash))
1675         return error("AcceptBlock() : block already in mapBlockIndex");
1676
1677     // Get prev block index
1678     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1679     if (mi == mapBlockIndex.end())
1680         return DoS(10, error("AcceptBlock() : prev block not found"));
1681     CBlockIndex* pindexPrev = (*mi).second;
1682     int nHeight = pindexPrev->nHeight+1;
1683
1684     // Check proof of work
1685     if (nBits != GetNextWorkRequired(pindexPrev, this))
1686         return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1687
1688     // Check timestamp against prev
1689     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1690         return error("AcceptBlock() : block's timestamp is too early");
1691
1692     // Check that all transactions are finalized
1693     BOOST_FOREACH(const CTransaction& tx, vtx)
1694         if (!tx.IsFinal(nHeight, GetBlockTime()))
1695             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1696
1697     // Check that the block chain matches the known block chain up to a checkpoint
1698     if (!Checkpoints::CheckBlock(nHeight, hash))
1699         return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1700
1701     // Write block to history file
1702     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1703         return error("AcceptBlock() : out of disk space");
1704     unsigned int nFile = -1;
1705     unsigned int nBlockPos = 0;
1706     if (!WriteToDisk(nFile, nBlockPos))
1707         return error("AcceptBlock() : WriteToDisk failed");
1708     if (!AddToBlockIndex(nFile, nBlockPos))
1709         return error("AcceptBlock() : AddToBlockIndex failed");
1710
1711     // Relay inventory, but don't relay old inventory during initial block download
1712     int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1713     if (hashBestChain == hash)
1714     {
1715         LOCK(cs_vNodes);
1716         BOOST_FOREACH(CNode* pnode, vNodes)
1717             if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1718                 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1719     }
1720
1721     return true;
1722 }
1723
1724 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1725 {
1726     // Check for duplicate
1727     uint256 hash = pblock->GetHash();
1728     if (mapBlockIndex.count(hash))
1729         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1730     if (mapOrphanBlocks.count(hash))
1731         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1732
1733     // Preliminary checks
1734     if (!pblock->CheckBlock())
1735         return error("ProcessBlock() : CheckBlock FAILED");
1736
1737     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1738     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1739     {
1740         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1741         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1742         if (deltaTime < 0)
1743         {
1744             if (pfrom)
1745                 pfrom->Misbehaving(100);
1746             return error("ProcessBlock() : block with timestamp before last checkpoint");
1747         }
1748         CBigNum bnNewBlock;
1749         bnNewBlock.SetCompact(pblock->nBits);
1750         CBigNum bnRequired;
1751         bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1752         if (bnNewBlock > bnRequired)
1753         {
1754             if (pfrom)
1755                 pfrom->Misbehaving(100);
1756             return error("ProcessBlock() : block with too little proof-of-work");
1757         }
1758     }
1759
1760
1761     // If don't already have its previous block, shunt it off to holding area until we get it
1762     if (!mapBlockIndex.count(pblock->hashPrevBlock))
1763     {
1764         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1765         CBlock* pblock2 = new CBlock(*pblock);
1766         mapOrphanBlocks.insert(make_pair(hash, pblock2));
1767         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1768
1769         // Ask this guy to fill in what we're missing
1770         if (pfrom)
1771             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1772         return true;
1773     }
1774
1775     // Store to disk
1776     if (!pblock->AcceptBlock())
1777         return error("ProcessBlock() : AcceptBlock FAILED");
1778
1779     // Recursively process any orphan blocks that depended on this one
1780     vector<uint256> vWorkQueue;
1781     vWorkQueue.push_back(hash);
1782     for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1783     {
1784         uint256 hashPrev = vWorkQueue[i];
1785         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1786              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1787              ++mi)
1788         {
1789             CBlock* pblockOrphan = (*mi).second;
1790             if (pblockOrphan->AcceptBlock())
1791                 vWorkQueue.push_back(pblockOrphan->GetHash());
1792             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1793             delete pblockOrphan;
1794         }
1795         mapOrphanBlocksByPrev.erase(hashPrev);
1796     }
1797
1798     printf("ProcessBlock: ACCEPTED\n");
1799     return true;
1800 }
1801
1802
1803
1804
1805
1806
1807
1808
1809 bool CheckDiskSpace(uint64 nAdditionalBytes)
1810 {
1811     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1812
1813     // Check for 15MB because database could create another 10MB log file at any time
1814     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1815     {
1816         fShutdown = true;
1817         string strMessage = _("Warning: Disk space is low  ");
1818         strMiscWarning = strMessage;
1819         printf("*** %s\n", strMessage.c_str());
1820         ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
1821         QueueShutdown();
1822         return false;
1823     }
1824     return true;
1825 }
1826
1827 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1828 {
1829     if (nFile == -1)
1830         return NULL;
1831     FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
1832     if (!file)
1833         return NULL;
1834     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1835     {
1836         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1837         {
1838             fclose(file);
1839             return NULL;
1840         }
1841     }
1842     return file;
1843 }
1844
1845 static unsigned int nCurrentBlockFile = 1;
1846
1847 FILE* AppendBlockFile(unsigned int& nFileRet)
1848 {
1849     nFileRet = 0;
1850     loop
1851     {
1852         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1853         if (!file)
1854             return NULL;
1855         if (fseek(file, 0, SEEK_END) != 0)
1856             return NULL;
1857         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1858         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1859         {
1860             nFileRet = nCurrentBlockFile;
1861             return file;
1862         }
1863         fclose(file);
1864         nCurrentBlockFile++;
1865     }
1866 }
1867
1868 bool LoadBlockIndex(bool fAllowNew)
1869 {
1870     if (fTestNet)
1871     {
1872         hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1873         bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1874         pchMessageStart[0] = 0xfa;
1875         pchMessageStart[1] = 0xbf;
1876         pchMessageStart[2] = 0xb5;
1877         pchMessageStart[3] = 0xda;
1878     }
1879
1880     //
1881     // Load block index
1882     //
1883     CTxDB txdb("cr");
1884     if (!txdb.LoadBlockIndex())
1885         return false;
1886     txdb.Close();
1887
1888     //
1889     // Init with genesis block
1890     //
1891     if (mapBlockIndex.empty())
1892     {
1893         if (!fAllowNew)
1894             return false;
1895
1896         // Genesis Block:
1897         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1898         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1899         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1900         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1901         //   vMerkleTree: 4a5e1e
1902
1903         // Genesis block
1904         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1905         CTransaction txNew;
1906         txNew.vin.resize(1);
1907         txNew.vout.resize(1);
1908         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1909         txNew.vout[0].nValue = 50 * COIN;
1910         txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1911         CBlock block;
1912         block.vtx.push_back(txNew);
1913         block.hashPrevBlock = 0;
1914         block.hashMerkleRoot = block.BuildMerkleTree();
1915         block.nVersion = 1;
1916         block.nTime    = 1231006505;
1917         block.nBits    = 0x1d00ffff;
1918         block.nNonce   = 2083236893;
1919
1920         if (fTestNet)
1921         {
1922             block.nTime    = 1296688602;
1923             block.nBits    = 0x1d07fff8;
1924             block.nNonce   = 384568319;
1925         }
1926
1927         //// debug print
1928         printf("%s\n", block.GetHash().ToString().c_str());
1929         printf("%s\n", hashGenesisBlock.ToString().c_str());
1930         printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1931         assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1932         block.print();
1933         assert(block.GetHash() == hashGenesisBlock);
1934
1935         // Start new block file
1936         unsigned int nFile;
1937         unsigned int nBlockPos;
1938         if (!block.WriteToDisk(nFile, nBlockPos))
1939             return error("LoadBlockIndex() : writing genesis block to disk failed");
1940         if (!block.AddToBlockIndex(nFile, nBlockPos))
1941             return error("LoadBlockIndex() : genesis block not accepted");
1942     }
1943
1944     return true;
1945 }
1946
1947
1948
1949 void PrintBlockTree()
1950 {
1951     // precompute tree structure
1952     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1953     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1954     {
1955         CBlockIndex* pindex = (*mi).second;
1956         mapNext[pindex->pprev].push_back(pindex);
1957         // test
1958         //while (rand() % 3 == 0)
1959         //    mapNext[pindex->pprev].push_back(pindex);
1960     }
1961
1962     vector<pair<int, CBlockIndex*> > vStack;
1963     vStack.push_back(make_pair(0, pindexGenesisBlock));
1964
1965     int nPrevCol = 0;
1966     while (!vStack.empty())
1967     {
1968         int nCol = vStack.back().first;
1969         CBlockIndex* pindex = vStack.back().second;
1970         vStack.pop_back();
1971
1972         // print split or gap
1973         if (nCol > nPrevCol)
1974         {
1975             for (int i = 0; i < nCol-1; i++)
1976                 printf("| ");
1977             printf("|\\\n");
1978         }
1979         else if (nCol < nPrevCol)
1980         {
1981             for (int i = 0; i < nCol; i++)
1982                 printf("| ");
1983             printf("|\n");
1984        }
1985         nPrevCol = nCol;
1986
1987         // print columns
1988         for (int i = 0; i < nCol; i++)
1989             printf("| ");
1990
1991         // print item
1992         CBlock block;
1993         block.ReadFromDisk(pindex);
1994         printf("%d (%u,%u) %s  %s  tx %d",
1995             pindex->nHeight,
1996             pindex->nFile,
1997             pindex->nBlockPos,
1998             block.GetHash().ToString().substr(0,20).c_str(),
1999             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2000             block.vtx.size());
2001
2002         PrintWallets(block);
2003
2004         // put the main timechain first
2005         vector<CBlockIndex*>& vNext = mapNext[pindex];
2006         for (unsigned int i = 0; i < vNext.size(); i++)
2007         {
2008             if (vNext[i]->pnext)
2009             {
2010                 swap(vNext[0], vNext[i]);
2011                 break;
2012             }
2013         }
2014
2015         // iterate children
2016         for (unsigned int i = 0; i < vNext.size(); i++)
2017             vStack.push_back(make_pair(nCol+i, vNext[i]));
2018     }
2019 }
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030 //////////////////////////////////////////////////////////////////////////////
2031 //
2032 // CAlert
2033 //
2034
2035 map<uint256, CAlert> mapAlerts;
2036 CCriticalSection cs_mapAlerts;
2037
2038 string GetWarnings(string strFor)
2039 {
2040     int nPriority = 0;
2041     string strStatusBar;
2042     string strRPC;
2043     if (GetBoolArg("-testsafemode"))
2044         strRPC = "test";
2045
2046     // Misc warnings like out of disk space and clock is wrong
2047     if (strMiscWarning != "")
2048     {
2049         nPriority = 1000;
2050         strStatusBar = strMiscWarning;
2051     }
2052
2053     // Longer invalid proof-of-work chain
2054     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2055     {
2056         nPriority = 2000;
2057         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
2058     }
2059
2060     // Alerts
2061     {
2062         LOCK(cs_mapAlerts);
2063         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2064         {
2065             const CAlert& alert = item.second;
2066             if (alert.AppliesToMe() && alert.nPriority > nPriority)
2067             {
2068                 nPriority = alert.nPriority;
2069                 strStatusBar = alert.strStatusBar;
2070             }
2071         }
2072     }
2073
2074     if (strFor == "statusbar")
2075         return strStatusBar;
2076     else if (strFor == "rpc")
2077         return strRPC;
2078     assert(!"GetWarnings() : invalid parameter");
2079     return "error";
2080 }
2081
2082 bool CAlert::ProcessAlert()
2083 {
2084     if (!CheckSignature())
2085         return false;
2086     if (!IsInEffect())
2087         return false;
2088
2089     {
2090         LOCK(cs_mapAlerts);
2091         // Cancel previous alerts
2092         for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2093         {
2094             const CAlert& alert = (*mi).second;
2095             if (Cancels(alert))
2096             {
2097                 printf("cancelling alert %d\n", alert.nID);
2098                 mapAlerts.erase(mi++);
2099             }
2100             else if (!alert.IsInEffect())
2101             {
2102                 printf("expiring alert %d\n", alert.nID);
2103                 mapAlerts.erase(mi++);
2104             }
2105             else
2106                 mi++;
2107         }
2108
2109         // Check if this alert has been cancelled
2110         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2111         {
2112             const CAlert& alert = item.second;
2113             if (alert.Cancels(*this))
2114             {
2115                 printf("alert already cancelled by %d\n", alert.nID);
2116                 return false;
2117             }
2118         }
2119
2120         // Add to mapAlerts
2121         mapAlerts.insert(make_pair(GetHash(), *this));
2122     }
2123
2124     printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2125     MainFrameRepaint();
2126     return true;
2127 }
2128
2129
2130
2131
2132
2133
2134
2135
2136 //////////////////////////////////////////////////////////////////////////////
2137 //
2138 // Messages
2139 //
2140
2141
2142 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2143 {
2144     switch (inv.type)
2145     {
2146     case MSG_TX:
2147         {
2148         bool txInMap = false;
2149             {
2150             LOCK(mempool.cs);
2151             txInMap = (mempool.exists(inv.hash));
2152             }
2153         return txInMap ||
2154                mapOrphanTransactions.count(inv.hash) ||
2155                txdb.ContainsTx(inv.hash);
2156         }
2157
2158     case MSG_BLOCK:
2159         return mapBlockIndex.count(inv.hash) ||
2160                mapOrphanBlocks.count(inv.hash);
2161     }
2162     // Don't know what it is, just say we already got one
2163     return true;
2164 }
2165
2166
2167
2168
2169 // The message start string is designed to be unlikely to occur in normal data.
2170 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2171 // a large 4-byte int at any alignment.
2172 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2173
2174
2175 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2176 {
2177     static map<CService, vector<unsigned char> > mapReuseKey;
2178     RandAddSeedPerfmon();
2179     if (fDebug) {
2180         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2181         printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2182     }
2183     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2184     {
2185         printf("dropmessagestest DROPPING RECV MESSAGE\n");
2186         return true;
2187     }
2188
2189
2190
2191
2192
2193     if (strCommand == "version")
2194     {
2195         // Each connection can only send one version message
2196         if (pfrom->nVersion != 0)
2197         {
2198             pfrom->Misbehaving(1);
2199             return false;
2200         }
2201
2202         int64 nTime;
2203         CAddress addrMe;
2204         CAddress addrFrom;
2205         uint64 nNonce = 1;
2206         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2207         if (pfrom->nVersion < MIN_PROTO_VERSION)
2208         {
2209             // Since February 20, 2012, the protocol is initiated at version 209,
2210             // and earlier versions are no longer supported
2211             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2212             pfrom->fDisconnect = true;
2213             return false;
2214         }
2215
2216         if (pfrom->nVersion == 10300)
2217             pfrom->nVersion = 300;
2218         if (!vRecv.empty())
2219             vRecv >> addrFrom >> nNonce;
2220         if (!vRecv.empty())
2221             vRecv >> pfrom->strSubVer;
2222         if (!vRecv.empty())
2223             vRecv >> pfrom->nStartingHeight;
2224
2225         // Disconnect if we connected to ourself
2226         if (nNonce == nLocalHostNonce && nNonce > 1)
2227         {
2228             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2229             pfrom->fDisconnect = true;
2230             return true;
2231         }
2232
2233         // Be shy and don't send version until we hear
2234         if (pfrom->fInbound)
2235             pfrom->PushVersion();
2236
2237         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2238
2239         AddTimeData(pfrom->addr, nTime);
2240
2241         // Change version
2242         pfrom->PushMessage("verack");
2243         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2244
2245         if (!pfrom->fInbound)
2246         {
2247             // Advertise our address
2248             if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2249                 !IsInitialBlockDownload())
2250             {
2251                 CAddress addr(addrLocalHost);
2252                 addr.nTime = GetAdjustedTime();
2253                 pfrom->PushAddress(addr);
2254             }
2255
2256             // Get recent addresses
2257             if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2258             {
2259                 pfrom->PushMessage("getaddr");
2260                 pfrom->fGetAddr = true;
2261             }
2262             addrman.Good(pfrom->addr);
2263         } else {
2264             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2265             {
2266                 addrman.Add(addrFrom, addrFrom);
2267                 addrman.Good(addrFrom);
2268             }
2269         }
2270
2271         // Ask the first connected node for block updates
2272         static int nAskedForBlocks = 0;
2273         if (!pfrom->fClient &&
2274             (pfrom->nVersion < NOBLKS_VERSION_START ||
2275              pfrom->nVersion >= NOBLKS_VERSION_END) &&
2276              (nAskedForBlocks < 1 || vNodes.size() <= 1))
2277         {
2278             nAskedForBlocks++;
2279             pfrom->PushGetBlocks(pindexBest, uint256(0));
2280         }
2281
2282         // Relay alerts
2283         {
2284             LOCK(cs_mapAlerts);
2285             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2286                 item.second.RelayTo(pfrom);
2287         }
2288
2289         pfrom->fSuccessfullyConnected = true;
2290
2291         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2292
2293         cPeerBlockCounts.input(pfrom->nStartingHeight);
2294     }
2295
2296
2297     else if (pfrom->nVersion == 0)
2298     {
2299         // Must have a version message before anything else
2300         pfrom->Misbehaving(1);
2301         return false;
2302     }
2303
2304
2305     else if (strCommand == "verack")
2306     {
2307         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2308     }
2309
2310
2311     else if (strCommand == "addr")
2312     {
2313         vector<CAddress> vAddr;
2314         vRecv >> vAddr;
2315
2316         // Don't want addr from older versions unless seeding
2317         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2318             return true;
2319         if (vAddr.size() > 1000)
2320         {
2321             pfrom->Misbehaving(20);
2322             return error("message addr size() = %d", vAddr.size());
2323         }
2324
2325         // Store the new addresses
2326         int64 nNow = GetAdjustedTime();
2327         int64 nSince = nNow - 10 * 60;
2328         BOOST_FOREACH(CAddress& addr, vAddr)
2329         {
2330             if (fShutdown)
2331                 return true;
2332             // ignore IPv6 for now, since it isn't implemented anyway
2333             if (!addr.IsIPv4())
2334                 continue;
2335             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2336                 addr.nTime = nNow - 5 * 24 * 60 * 60;
2337             pfrom->AddAddressKnown(addr);
2338             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2339             {
2340                 // Relay to a limited number of other nodes
2341                 {
2342                     LOCK(cs_vNodes);
2343                     // Use deterministic randomness to send to the same nodes for 24 hours
2344                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2345                     static uint256 hashSalt;
2346                     if (hashSalt == 0)
2347                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2348                     int64 hashAddr = addr.GetHash();
2349                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2350                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2351                     multimap<uint256, CNode*> mapMix;
2352                     BOOST_FOREACH(CNode* pnode, vNodes)
2353                     {
2354                         if (pnode->nVersion < CADDR_TIME_VERSION)
2355                             continue;
2356                         unsigned int nPointer;
2357                         memcpy(&nPointer, &pnode, sizeof(nPointer));
2358                         uint256 hashKey = hashRand ^ nPointer;
2359                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
2360                         mapMix.insert(make_pair(hashKey, pnode));
2361                     }
2362                     int nRelayNodes = 2;
2363                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2364                         ((*mi).second)->PushAddress(addr);
2365                 }
2366             }
2367         }
2368         addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2369         if (vAddr.size() < 1000)
2370             pfrom->fGetAddr = false;
2371     }
2372
2373
2374     else if (strCommand == "inv")
2375     {
2376         vector<CInv> vInv;
2377         vRecv >> vInv;
2378         if (vInv.size() > 50000)
2379         {
2380             pfrom->Misbehaving(20);
2381             return error("message inv size() = %d", vInv.size());
2382         }
2383
2384         CTxDB txdb("r");
2385         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2386         {
2387             const CInv &inv = vInv[nInv];
2388
2389             if (fShutdown)
2390                 return true;
2391             pfrom->AddInventoryKnown(inv);
2392
2393             bool fAlreadyHave = AlreadyHave(txdb, inv);
2394             if (fDebug)
2395                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2396
2397             // Always request the last block in an inv bundle (even if we already have it), as it is the
2398             // trigger for the other side to send further invs. If we are stuck on a (very long) side chain,
2399             // this is necessary to connect earlier received orphan blocks to the chain again.
2400             if (!fAlreadyHave || (inv.type == MSG_BLOCK && nInv==vInv.size()-1))
2401                 pfrom->AskFor(inv);
2402             if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2403                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2404
2405             // Track requests for our stuff
2406             Inventory(inv.hash);
2407         }
2408     }
2409
2410
2411     else if (strCommand == "getdata")
2412     {
2413         vector<CInv> vInv;
2414         vRecv >> vInv;
2415         if (vInv.size() > 50000)
2416         {
2417             pfrom->Misbehaving(20);
2418             return error("message getdata size() = %d", vInv.size());
2419         }
2420
2421         BOOST_FOREACH(const CInv& inv, vInv)
2422         {
2423             if (fShutdown)
2424                 return true;
2425             printf("received getdata for: %s\n", inv.ToString().c_str());
2426
2427             if (inv.type == MSG_BLOCK)
2428             {
2429                 // Send block from disk
2430                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2431                 if (mi != mapBlockIndex.end())
2432                 {
2433                     CBlock block;
2434                     block.ReadFromDisk((*mi).second);
2435                     pfrom->PushMessage("block", block);
2436
2437                     // Trigger them to send a getblocks request for the next batch of inventory
2438                     if (inv.hash == pfrom->hashContinue)
2439                     {
2440                         // Bypass PushInventory, this must send even if redundant,
2441                         // and we want it right after the last block so they don't
2442                         // wait for other stuff first.
2443                         vector<CInv> vInv;
2444                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2445                         pfrom->PushMessage("inv", vInv);
2446                         pfrom->hashContinue = 0;
2447                     }
2448                 }
2449             }
2450             else if (inv.IsKnownType())
2451             {
2452                 // Send stream from relay memory
2453                 {
2454                     LOCK(cs_mapRelay);
2455                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2456                     if (mi != mapRelay.end())
2457                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2458                 }
2459             }
2460
2461             // Track requests for our stuff
2462             Inventory(inv.hash);
2463         }
2464     }
2465
2466
2467     else if (strCommand == "getblocks")
2468     {
2469         CBlockLocator locator;
2470         uint256 hashStop;
2471         vRecv >> locator >> hashStop;
2472
2473         // Find the last block the caller has in the main chain
2474         CBlockIndex* pindex = locator.GetBlockIndex();
2475
2476         // Send the rest of the chain
2477         if (pindex)
2478             pindex = pindex->pnext;
2479         int nLimit = 500 + locator.GetDistanceBack();
2480         unsigned int nBytes = 0;
2481         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2482         for (; pindex; pindex = pindex->pnext)
2483         {
2484             if (pindex->GetBlockHash() == hashStop)
2485             {
2486                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2487                 break;
2488             }
2489             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2490             CBlock block;
2491             block.ReadFromDisk(pindex, true);
2492             nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2493             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2494             {
2495                 // When this block is requested, we'll send an inv that'll make them
2496                 // getblocks the next batch of inventory.
2497                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2498                 pfrom->hashContinue = pindex->GetBlockHash();
2499                 break;
2500             }
2501         }
2502     }
2503
2504
2505     else if (strCommand == "getheaders")
2506     {
2507         CBlockLocator locator;
2508         uint256 hashStop;
2509         vRecv >> locator >> hashStop;
2510
2511         CBlockIndex* pindex = NULL;
2512         if (locator.IsNull())
2513         {
2514             // If locator is null, return the hashStop block
2515             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2516             if (mi == mapBlockIndex.end())
2517                 return true;
2518             pindex = (*mi).second;
2519         }
2520         else
2521         {
2522             // Find the last block the caller has in the main chain
2523             pindex = locator.GetBlockIndex();
2524             if (pindex)
2525                 pindex = pindex->pnext;
2526         }
2527
2528         vector<CBlock> vHeaders;
2529         int nLimit = 2000;
2530         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2531         for (; pindex; pindex = pindex->pnext)
2532         {
2533             vHeaders.push_back(pindex->GetBlockHeader());
2534             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2535                 break;
2536         }
2537         pfrom->PushMessage("headers", vHeaders);
2538     }
2539
2540
2541     else if (strCommand == "tx")
2542     {
2543         vector<uint256> vWorkQueue;
2544         CDataStream vMsg(vRecv);
2545         CTxDB txdb("r");
2546         CTransaction tx;
2547         vRecv >> tx;
2548
2549         CInv inv(MSG_TX, tx.GetHash());
2550         pfrom->AddInventoryKnown(inv);
2551
2552         bool fMissingInputs = false;
2553         if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2554         {
2555             SyncWithWallets(tx, NULL, true);
2556             RelayMessage(inv, vMsg);
2557             mapAlreadyAskedFor.erase(inv);
2558             vWorkQueue.push_back(inv.hash);
2559
2560             // Recursively process any orphan transactions that depended on this one
2561             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2562             {
2563                 uint256 hashPrev = vWorkQueue[i];
2564                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2565                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2566                      ++mi)
2567                 {
2568                     const CDataStream& vMsg = *((*mi).second);
2569                     CTransaction tx;
2570                     CDataStream(vMsg) >> tx;
2571                     CInv inv(MSG_TX, tx.GetHash());
2572
2573                     if (tx.AcceptToMemoryPool(txdb, true))
2574                     {
2575                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2576                         SyncWithWallets(tx, NULL, true);
2577                         RelayMessage(inv, vMsg);
2578                         mapAlreadyAskedFor.erase(inv);
2579                         vWorkQueue.push_back(inv.hash);
2580                     }
2581                 }
2582             }
2583
2584             BOOST_FOREACH(uint256 hash, vWorkQueue)
2585                 EraseOrphanTx(hash);
2586         }
2587         else if (fMissingInputs)
2588         {
2589             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2590             AddOrphanTx(vMsg);
2591
2592             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2593             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2594             if (nEvicted > 0)
2595                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
2596         }
2597         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2598     }
2599
2600
2601     else if (strCommand == "block")
2602     {
2603         CBlock block;
2604         vRecv >> block;
2605
2606         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2607         // block.print();
2608
2609         CInv inv(MSG_BLOCK, block.GetHash());
2610         pfrom->AddInventoryKnown(inv);
2611
2612         if (ProcessBlock(pfrom, &block))
2613             mapAlreadyAskedFor.erase(inv);
2614         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2615     }
2616
2617
2618     else if (strCommand == "getaddr")
2619     {
2620         pfrom->vAddrToSend.clear();
2621         vector<CAddress> vAddr = addrman.GetAddr();
2622         BOOST_FOREACH(const CAddress &addr, vAddr)
2623             pfrom->PushAddress(addr);
2624     }
2625
2626
2627     else if (strCommand == "checkorder")
2628     {
2629         uint256 hashReply;
2630         vRecv >> hashReply;
2631
2632         if (!GetBoolArg("-allowreceivebyip"))
2633         {
2634             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2635             return true;
2636         }
2637
2638         CWalletTx order;
2639         vRecv >> order;
2640
2641         /// we have a chance to check the order here
2642
2643         // Keep giving the same key to the same ip until they use it
2644         if (!mapReuseKey.count(pfrom->addr))
2645             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2646
2647         // Send back approval of order and pubkey to use
2648         CScript scriptPubKey;
2649         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2650         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2651     }
2652
2653
2654     else if (strCommand == "reply")
2655     {
2656         uint256 hashReply;
2657         vRecv >> hashReply;
2658
2659         CRequestTracker tracker;
2660         {
2661             LOCK(pfrom->cs_mapRequests);
2662             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2663             if (mi != pfrom->mapRequests.end())
2664             {
2665                 tracker = (*mi).second;
2666                 pfrom->mapRequests.erase(mi);
2667             }
2668         }
2669         if (!tracker.IsNull())
2670             tracker.fn(tracker.param1, vRecv);
2671     }
2672
2673
2674     else if (strCommand == "ping")
2675     {
2676         if (pfrom->nVersion > BIP0031_VERSION)
2677         {
2678             uint64 nonce = 0;
2679             vRecv >> nonce;
2680             // Echo the message back with the nonce. This allows for two useful features:
2681             //
2682             // 1) A remote node can quickly check if the connection is operational
2683             // 2) Remote nodes can measure the latency of the network thread. If this node
2684             //    is overloaded it won't respond to pings quickly and the remote node can
2685             //    avoid sending us more work, like chain download requests.
2686             //
2687             // The nonce stops the remote getting confused between different pings: without
2688             // it, if the remote node sends a ping once per second and this node takes 5
2689             // seconds to respond to each, the 5th ping the remote sends would appear to
2690             // return very quickly.
2691             pfrom->PushMessage("pong", nonce);
2692         }
2693     }
2694
2695
2696     else if (strCommand == "alert")
2697     {
2698         CAlert alert;
2699         vRecv >> alert;
2700
2701         if (alert.ProcessAlert())
2702         {
2703             // Relay
2704             pfrom->setKnown.insert(alert.GetHash());
2705             {
2706                 LOCK(cs_vNodes);
2707                 BOOST_FOREACH(CNode* pnode, vNodes)
2708                     alert.RelayTo(pnode);
2709             }
2710         }
2711     }
2712
2713
2714     else
2715     {
2716         // Ignore unknown commands for extensibility
2717     }
2718
2719
2720     // Update the last seen time for this node's address
2721     if (pfrom->fNetworkNode)
2722         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2723             AddressCurrentlyConnected(pfrom->addr);
2724
2725
2726     return true;
2727 }
2728
2729 bool ProcessMessages(CNode* pfrom)
2730 {
2731     CDataStream& vRecv = pfrom->vRecv;
2732     if (vRecv.empty())
2733         return true;
2734     //if (fDebug)
2735     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2736
2737     //
2738     // Message format
2739     //  (4) message start
2740     //  (12) command
2741     //  (4) size
2742     //  (4) checksum
2743     //  (x) data
2744     //
2745
2746     loop
2747     {
2748         // Scan for message start
2749         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2750         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2751         if (vRecv.end() - pstart < nHeaderSize)
2752         {
2753             if ((int)vRecv.size() > nHeaderSize)
2754             {
2755                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2756                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2757             }
2758             break;
2759         }
2760         if (pstart - vRecv.begin() > 0)
2761             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2762         vRecv.erase(vRecv.begin(), pstart);
2763
2764         // Read header
2765         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2766         CMessageHeader hdr;
2767         vRecv >> hdr;
2768         if (!hdr.IsValid())
2769         {
2770             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2771             continue;
2772         }
2773         string strCommand = hdr.GetCommand();
2774
2775         // Message size
2776         unsigned int nMessageSize = hdr.nMessageSize;
2777         if (nMessageSize > MAX_SIZE)
2778         {
2779             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2780             continue;
2781         }
2782         if (nMessageSize > vRecv.size())
2783         {
2784             // Rewind and wait for rest of message
2785             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2786             break;
2787         }
2788
2789         // Checksum
2790         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2791         unsigned int nChecksum = 0;
2792         memcpy(&nChecksum, &hash, sizeof(nChecksum));
2793         if (nChecksum != hdr.nChecksum)
2794         {
2795             printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2796                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2797             continue;
2798         }
2799
2800         // Copy message to its own buffer
2801         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2802         vRecv.ignore(nMessageSize);
2803
2804         // Process message
2805         bool fRet = false;
2806         try
2807         {
2808             {
2809                 LOCK(cs_main);
2810                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2811             }
2812             if (fShutdown)
2813                 return true;
2814         }
2815         catch (std::ios_base::failure& e)
2816         {
2817             if (strstr(e.what(), "end of data"))
2818             {
2819                 // Allow exceptions from underlength message on vRecv
2820                 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());
2821             }
2822             else if (strstr(e.what(), "size too large"))
2823             {
2824                 // Allow exceptions from overlong size
2825                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2826             }
2827             else
2828             {
2829                 PrintExceptionContinue(&e, "ProcessMessage()");
2830             }
2831         }
2832         catch (std::exception& e) {
2833             PrintExceptionContinue(&e, "ProcessMessage()");
2834         } catch (...) {
2835             PrintExceptionContinue(NULL, "ProcessMessage()");
2836         }
2837
2838         if (!fRet)
2839             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2840     }
2841
2842     vRecv.Compact();
2843     return true;
2844 }
2845
2846
2847 bool SendMessages(CNode* pto, bool fSendTrickle)
2848 {
2849     TRY_LOCK(cs_main, lockMain);
2850     if (lockMain) {
2851         // Don't send anything until we get their version message
2852         if (pto->nVersion == 0)
2853             return true;
2854
2855         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere 
2856         // right now.
2857         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
2858             if (pto->nVersion > BIP0031_VERSION)
2859                 pto->PushMessage("ping", 0);
2860             else
2861                 pto->PushMessage("ping");
2862         }
2863
2864         // Resend wallet transactions that haven't gotten in a block yet
2865         ResendWalletTransactions();
2866
2867         // Address refresh broadcast
2868         static int64 nLastRebroadcast;
2869         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
2870         {
2871             {
2872                 LOCK(cs_vNodes);
2873                 BOOST_FOREACH(CNode* pnode, vNodes)
2874                 {
2875                     // Periodically clear setAddrKnown to allow refresh broadcasts
2876                     if (nLastRebroadcast)
2877                         pnode->setAddrKnown.clear();
2878
2879                     // Rebroadcast our address
2880                     if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
2881                     {
2882                         CAddress addr(addrLocalHost);
2883                         addr.nTime = GetAdjustedTime();
2884                         pnode->PushAddress(addr);
2885                     }
2886                 }
2887             }
2888             nLastRebroadcast = GetTime();
2889         }
2890
2891         //
2892         // Message: addr
2893         //
2894         if (fSendTrickle)
2895         {
2896             vector<CAddress> vAddr;
2897             vAddr.reserve(pto->vAddrToSend.size());
2898             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2899             {
2900                 // returns true if wasn't already contained in the set
2901                 if (pto->setAddrKnown.insert(addr).second)
2902                 {
2903                     vAddr.push_back(addr);
2904                     // receiver rejects addr messages larger than 1000
2905                     if (vAddr.size() >= 1000)
2906                     {
2907                         pto->PushMessage("addr", vAddr);
2908                         vAddr.clear();
2909                     }
2910                 }
2911             }
2912             pto->vAddrToSend.clear();
2913             if (!vAddr.empty())
2914                 pto->PushMessage("addr", vAddr);
2915         }
2916
2917
2918         //
2919         // Message: inventory
2920         //
2921         vector<CInv> vInv;
2922         vector<CInv> vInvWait;
2923         {
2924             LOCK(pto->cs_inventory);
2925             vInv.reserve(pto->vInventoryToSend.size());
2926             vInvWait.reserve(pto->vInventoryToSend.size());
2927             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2928             {
2929                 if (pto->setInventoryKnown.count(inv))
2930                     continue;
2931
2932                 // trickle out tx inv to protect privacy
2933                 if (inv.type == MSG_TX && !fSendTrickle)
2934                 {
2935                     // 1/4 of tx invs blast to all immediately
2936                     static uint256 hashSalt;
2937                     if (hashSalt == 0)
2938                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2939                     uint256 hashRand = inv.hash ^ hashSalt;
2940                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2941                     bool fTrickleWait = ((hashRand & 3) != 0);
2942
2943                     // always trickle our own transactions
2944                     if (!fTrickleWait)
2945                     {
2946                         CWalletTx wtx;
2947                         if (GetTransaction(inv.hash, wtx))
2948                             if (wtx.fFromMe)
2949                                 fTrickleWait = true;
2950                     }
2951
2952                     if (fTrickleWait)
2953                     {
2954                         vInvWait.push_back(inv);
2955                         continue;
2956                     }
2957                 }
2958
2959                 // returns true if wasn't already contained in the set
2960                 if (pto->setInventoryKnown.insert(inv).second)
2961                 {
2962                     vInv.push_back(inv);
2963                     if (vInv.size() >= 1000)
2964                     {
2965                         pto->PushMessage("inv", vInv);
2966                         vInv.clear();
2967                     }
2968                 }
2969             }
2970             pto->vInventoryToSend = vInvWait;
2971         }
2972         if (!vInv.empty())
2973             pto->PushMessage("inv", vInv);
2974
2975
2976         //
2977         // Message: getdata
2978         //
2979         vector<CInv> vGetData;
2980         int64 nNow = GetTime() * 1000000;
2981         CTxDB txdb("r");
2982         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2983         {
2984             const CInv& inv = (*pto->mapAskFor.begin()).second;
2985             if (!AlreadyHave(txdb, inv))
2986             {
2987                 printf("sending getdata: %s\n", inv.ToString().c_str());
2988                 vGetData.push_back(inv);
2989                 if (vGetData.size() >= 1000)
2990                 {
2991                     pto->PushMessage("getdata", vGetData);
2992                     vGetData.clear();
2993                 }
2994             }
2995             mapAlreadyAskedFor[inv] = nNow;
2996             pto->mapAskFor.erase(pto->mapAskFor.begin());
2997         }
2998         if (!vGetData.empty())
2999             pto->PushMessage("getdata", vGetData);
3000
3001     }
3002     return true;
3003 }
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018 //////////////////////////////////////////////////////////////////////////////
3019 //
3020 // BitcoinMiner
3021 //
3022
3023 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3024 {
3025     unsigned char* pdata = (unsigned char*)pbuffer;
3026     unsigned int blocks = 1 + ((len + 8) / 64);
3027     unsigned char* pend = pdata + 64 * blocks;
3028     memset(pdata + len, 0, 64 * blocks - len);
3029     pdata[len] = 0x80;
3030     unsigned int bits = len * 8;
3031     pend[-1] = (bits >> 0) & 0xff;
3032     pend[-2] = (bits >> 8) & 0xff;
3033     pend[-3] = (bits >> 16) & 0xff;
3034     pend[-4] = (bits >> 24) & 0xff;
3035     return blocks;
3036 }
3037
3038 static const unsigned int pSHA256InitState[8] =
3039 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3040
3041 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3042 {
3043     SHA256_CTX ctx;
3044     unsigned char data[64];
3045
3046     SHA256_Init(&ctx);
3047
3048     for (int i = 0; i < 16; i++)
3049         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3050
3051     for (int i = 0; i < 8; i++)
3052         ctx.h[i] = ((uint32_t*)pinit)[i];
3053
3054     SHA256_Update(&ctx, data, sizeof(data));
3055     for (int i = 0; i < 8; i++) 
3056         ((uint32_t*)pstate)[i] = ctx.h[i];
3057 }
3058
3059 //
3060 // ScanHash scans nonces looking for a hash with at least some zero bits.
3061 // It operates on big endian data.  Caller does the byte reversing.
3062 // All input buffers are 16-byte aligned.  nNonce is usually preserved
3063 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3064 // the block is rebuilt and nNonce starts over at zero.
3065 //
3066 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3067 {
3068     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3069     for (;;)
3070     {
3071         // Crypto++ SHA-256
3072         // Hash pdata using pmidstate as the starting state into
3073         // preformatted buffer phash1, then hash phash1 into phash
3074         nNonce++;
3075         SHA256Transform(phash1, pdata, pmidstate);
3076         SHA256Transform(phash, phash1, pSHA256InitState);
3077
3078         // Return the nonce if the hash has at least some zero bits,
3079         // caller will check if it has enough to reach the target
3080         if (((unsigned short*)phash)[14] == 0)
3081             return nNonce;
3082
3083         // If nothing found after trying for a while, return -1
3084         if ((nNonce & 0xffff) == 0)
3085         {
3086             nHashesDone = 0xffff+1;
3087             return (unsigned int) -1;
3088         }
3089     }
3090 }
3091
3092 // Some explaining would be appreciated
3093 class COrphan
3094 {
3095 public:
3096     CTransaction* ptx;
3097     set<uint256> setDependsOn;
3098     double dPriority;
3099
3100     COrphan(CTransaction* ptxIn)
3101     {
3102         ptx = ptxIn;
3103         dPriority = 0;
3104     }
3105
3106     void print() const
3107     {
3108         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3109         BOOST_FOREACH(uint256 hash, setDependsOn)
3110             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3111     }
3112 };
3113
3114
3115 uint64 nLastBlockTx = 0;
3116 uint64 nLastBlockSize = 0;
3117
3118 CBlock* CreateNewBlock(CReserveKey& reservekey)
3119 {
3120     CBlockIndex* pindexPrev = pindexBest;
3121
3122     // Create new block
3123     auto_ptr<CBlock> pblock(new CBlock());
3124     if (!pblock.get())
3125         return NULL;
3126
3127     // Create coinbase tx
3128     CTransaction txNew;
3129     txNew.vin.resize(1);
3130     txNew.vin[0].prevout.SetNull();
3131     txNew.vout.resize(1);
3132     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3133
3134     // Add our coinbase tx as first transaction
3135     pblock->vtx.push_back(txNew);
3136
3137     // Collect memory pool transactions into the block
3138     int64 nFees = 0;
3139     {
3140         LOCK2(cs_main, mempool.cs);
3141         CTxDB txdb("r");
3142
3143         // Priority order to process transactions
3144         list<COrphan> vOrphan; // list memory doesn't move
3145         map<uint256, vector<COrphan*> > mapDependers;
3146         multimap<double, CTransaction*> mapPriority;
3147         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3148         {
3149             CTransaction& tx = (*mi).second;
3150             if (tx.IsCoinBase() || !tx.IsFinal())
3151                 continue;
3152
3153             COrphan* porphan = NULL;
3154             double dPriority = 0;
3155             BOOST_FOREACH(const CTxIn& txin, tx.vin)
3156             {
3157                 // Read prev transaction
3158                 CTransaction txPrev;
3159                 CTxIndex txindex;
3160                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3161                 {
3162                     // Has to wait for dependencies
3163                     if (!porphan)
3164                     {
3165                         // Use list for automatic deletion
3166                         vOrphan.push_back(COrphan(&tx));
3167                         porphan = &vOrphan.back();
3168                     }
3169                     mapDependers[txin.prevout.hash].push_back(porphan);
3170                     porphan->setDependsOn.insert(txin.prevout.hash);
3171                     continue;
3172                 }
3173                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3174
3175                 // Read block header
3176                 int nConf = txindex.GetDepthInMainChain();
3177
3178                 dPriority += (double)nValueIn * nConf;
3179
3180                 if (fDebug && GetBoolArg("-printpriority"))
3181                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3182             }
3183
3184             // Priority is sum(valuein * age) / txsize
3185             dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3186
3187             if (porphan)
3188                 porphan->dPriority = dPriority;
3189             else
3190                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3191
3192             if (fDebug && GetBoolArg("-printpriority"))
3193             {
3194                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3195                 if (porphan)
3196                     porphan->print();
3197                 printf("\n");
3198             }
3199         }
3200
3201         // Collect transactions into block
3202         map<uint256, CTxIndex> mapTestPool;
3203         uint64 nBlockSize = 1000;
3204         uint64 nBlockTx = 0;
3205         int nBlockSigOps = 100;
3206         while (!mapPriority.empty())
3207         {
3208             // Take highest priority transaction off priority queue
3209             double dPriority = -(*mapPriority.begin()).first;
3210             CTransaction& tx = *(*mapPriority.begin()).second;
3211             mapPriority.erase(mapPriority.begin());
3212
3213             // Size limits
3214             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3215             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3216                 continue;
3217
3218             // Legacy limits on sigOps:
3219             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3220             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3221                 continue;
3222
3223             // Transaction fee required depends on block size
3224             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3225             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
3226
3227             // Connecting shouldn't fail due to dependency on other memory pool transactions
3228             // because we're already processing them in order of dependency
3229             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3230             MapPrevTx mapInputs;
3231             bool fInvalid;
3232             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3233                 continue;
3234
3235             int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3236             if (nTxFees < nMinFee)
3237                 continue;
3238
3239             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3240             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3241                 continue;
3242
3243             if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3244                 continue;
3245             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3246             swap(mapTestPool, mapTestPoolTmp);
3247
3248             // Added
3249             pblock->vtx.push_back(tx);
3250             nBlockSize += nTxSize;
3251             ++nBlockTx;
3252             nBlockSigOps += nTxSigOps;
3253             nFees += nTxFees;
3254
3255             // Add transactions that depend on this one to the priority queue
3256             uint256 hash = tx.GetHash();
3257             if (mapDependers.count(hash))
3258             {
3259                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3260                 {
3261                     if (!porphan->setDependsOn.empty())
3262                     {
3263                         porphan->setDependsOn.erase(hash);
3264                         if (porphan->setDependsOn.empty())
3265                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3266                     }
3267                 }
3268             }
3269         }
3270
3271         nLastBlockTx = nBlockTx;
3272         nLastBlockSize = nBlockSize;
3273         printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3274
3275     }
3276     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3277
3278     // Fill in header
3279     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3280     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3281     pblock->UpdateTime(pindexPrev);
3282     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock.get());
3283     pblock->nNonce         = 0;
3284
3285     return pblock.release();
3286 }
3287
3288
3289 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3290 {
3291     // Update nExtraNonce
3292     static uint256 hashPrevBlock;
3293     if (hashPrevBlock != pblock->hashPrevBlock)
3294     {
3295         nExtraNonce = 0;
3296         hashPrevBlock = pblock->hashPrevBlock;
3297     }
3298     ++nExtraNonce;
3299     pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3300     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3301
3302     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3303 }
3304
3305
3306 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3307 {
3308     //
3309     // Prebuild hash buffers
3310     //
3311     struct
3312     {
3313         struct unnamed2
3314         {
3315             int nVersion;
3316             uint256 hashPrevBlock;
3317             uint256 hashMerkleRoot;
3318             unsigned int nTime;
3319             unsigned int nBits;
3320             unsigned int nNonce;
3321         }
3322         block;
3323         unsigned char pchPadding0[64];
3324         uint256 hash1;
3325         unsigned char pchPadding1[64];
3326     }
3327     tmp;
3328     memset(&tmp, 0, sizeof(tmp));
3329
3330     tmp.block.nVersion       = pblock->nVersion;
3331     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
3332     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3333     tmp.block.nTime          = pblock->nTime;
3334     tmp.block.nBits          = pblock->nBits;
3335     tmp.block.nNonce         = pblock->nNonce;
3336
3337     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3338     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3339
3340     // Byte swap all the input buffer
3341     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3342         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3343
3344     // Precalc the first half of the first hash, which stays constant
3345     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3346
3347     memcpy(pdata, &tmp.block, 128);
3348     memcpy(phash1, &tmp.hash1, 64);
3349 }
3350
3351
3352 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3353 {
3354     uint256 hash = pblock->GetHash();
3355     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3356
3357     if (hash > hashTarget)
3358         return false;
3359
3360     //// debug print
3361     printf("BitcoinMiner:\n");
3362     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3363     pblock->print();
3364     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3365     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3366
3367     // Found a solution
3368     {
3369         LOCK(cs_main);
3370         if (pblock->hashPrevBlock != hashBestChain)
3371             return error("BitcoinMiner : generated block is stale");
3372
3373         // Remove key from key pool
3374         reservekey.KeepKey();
3375
3376         // Track how many getdata requests this block gets
3377         {
3378             LOCK(wallet.cs_wallet);
3379             wallet.mapRequestCount[pblock->GetHash()] = 0;
3380         }
3381
3382         // Process this block the same as if we had received it from another node
3383         if (!ProcessBlock(NULL, pblock))
3384             return error("BitcoinMiner : ProcessBlock, block not accepted");
3385     }
3386
3387     return true;
3388 }
3389
3390 void static ThreadBitcoinMiner(void* parg);
3391
3392 static bool fGenerateBitcoins = false;
3393 static bool fLimitProcessors = false;
3394 static int nLimitProcessors = -1;
3395
3396 void static BitcoinMiner(CWallet *pwallet)
3397 {
3398     printf("BitcoinMiner started\n");
3399     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3400
3401     // Each thread has its own key and counter
3402     CReserveKey reservekey(pwallet);
3403     unsigned int nExtraNonce = 0;
3404
3405     while (fGenerateBitcoins)
3406     {
3407         if (fShutdown)
3408             return;
3409         while (vNodes.empty() || IsInitialBlockDownload())
3410         {
3411             Sleep(1000);
3412             if (fShutdown)
3413                 return;
3414             if (!fGenerateBitcoins)
3415                 return;
3416         }
3417
3418
3419         //
3420         // Create new block
3421         //
3422         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3423         CBlockIndex* pindexPrev = pindexBest;
3424
3425         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3426         if (!pblock.get())
3427             return;
3428         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3429
3430         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3431
3432
3433         //
3434         // Prebuild hash buffers
3435         //
3436         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3437         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3438         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3439
3440         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3441
3442         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3443         unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3444         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3445
3446
3447         //
3448         // Search
3449         //
3450         int64 nStart = GetTime();
3451         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3452         uint256 hashbuf[2];
3453         uint256& hash = *alignup<16>(hashbuf);
3454         loop
3455         {
3456             unsigned int nHashesDone = 0;
3457             unsigned int nNonceFound;
3458
3459             // Crypto++ SHA-256
3460             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3461                                             (char*)&hash, nHashesDone);
3462
3463             // Check if something found
3464             if (nNonceFound != (unsigned int) -1)
3465             {
3466                 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3467                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3468
3469                 if (hash <= hashTarget)
3470                 {
3471                     // Found a solution
3472                     pblock->nNonce = ByteReverse(nNonceFound);
3473                     assert(hash == pblock->GetHash());
3474
3475                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3476                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3477                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3478                     break;
3479                 }
3480             }
3481
3482             // Meter hashes/sec
3483             static int64 nHashCounter;
3484             if (nHPSTimerStart == 0)
3485             {
3486                 nHPSTimerStart = GetTimeMillis();
3487                 nHashCounter = 0;
3488             }
3489             else
3490                 nHashCounter += nHashesDone;
3491             if (GetTimeMillis() - nHPSTimerStart > 4000)
3492             {
3493                 static CCriticalSection cs;
3494                 {
3495                     LOCK(cs);
3496                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3497                     {
3498                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3499                         nHPSTimerStart = GetTimeMillis();
3500                         nHashCounter = 0;
3501                         static int64 nLogTime;
3502                         if (GetTime() - nLogTime > 30 * 60)
3503                         {
3504                             nLogTime = GetTime();
3505                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3506                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3507                         }
3508                     }
3509                 }
3510             }
3511
3512             // Check for stop or if block needs to be rebuilt
3513             if (fShutdown)
3514                 return;
3515             if (!fGenerateBitcoins)
3516                 return;
3517             if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3518                 return;
3519             if (vNodes.empty())
3520                 break;
3521             if (nBlockNonce >= 0xffff0000)
3522                 break;
3523             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3524                 break;
3525             if (pindexPrev != pindexBest)
3526                 break;
3527
3528             // Update nTime every few seconds
3529             pblock->UpdateTime(pindexPrev);
3530             nBlockTime = ByteReverse(pblock->nTime);
3531             if (fTestNet)
3532             {
3533                 // Changing pblock->nTime can change work required on testnet:
3534                 nBlockBits = ByteReverse(pblock->nBits);
3535                 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3536             }
3537         }
3538     }
3539 }
3540
3541 void static ThreadBitcoinMiner(void* parg)
3542 {
3543     CWallet* pwallet = (CWallet*)parg;
3544     try
3545     {
3546         vnThreadsRunning[THREAD_MINER]++;
3547         BitcoinMiner(pwallet);
3548         vnThreadsRunning[THREAD_MINER]--;
3549     }
3550     catch (std::exception& e) {
3551         vnThreadsRunning[THREAD_MINER]--;
3552         PrintException(&e, "ThreadBitcoinMiner()");
3553     } catch (...) {
3554         vnThreadsRunning[THREAD_MINER]--;
3555         PrintException(NULL, "ThreadBitcoinMiner()");
3556     }
3557     nHPSTimerStart = 0;
3558     if (vnThreadsRunning[THREAD_MINER] == 0)
3559         dHashesPerSec = 0;
3560     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
3561 }
3562
3563
3564 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3565 {
3566     fGenerateBitcoins = fGenerate;
3567     nLimitProcessors = GetArg("-genproclimit", -1);
3568     if (nLimitProcessors == 0)
3569         fGenerateBitcoins = false;
3570     fLimitProcessors = (nLimitProcessors != -1);
3571
3572     if (fGenerate)
3573     {
3574         int nProcessors = boost::thread::hardware_concurrency();
3575         printf("%d processors\n", nProcessors);
3576         if (nProcessors < 1)
3577             nProcessors = 1;
3578         if (fLimitProcessors && nProcessors > nLimitProcessors)
3579             nProcessors = nLimitProcessors;
3580         int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
3581         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3582         for (int i = 0; i < nAddThreads; i++)
3583         {
3584             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3585                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3586             Sleep(10);
3587         }
3588     }
3589 }