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