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