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