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