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