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