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