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