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