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