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