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