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