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