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