PPCoin: Lower coinstake combine threshold to improve security
[novacoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_MAIN_H
7 #define BITCOIN_MAIN_H
8
9 #include "bignum.h"
10 #include "net.h"
11 #include "script.h"
12
13 #ifdef WIN32
14 #include <io.h> /* for _commit */
15 #endif
16
17 #include <list>
18
19 class CWallet;
20 class CBlock;
21 class CBlockIndex;
22 class CKeyItem;
23 class CReserveKey;
24 class COutPoint;
25
26 class CAddress;
27 class CInv;
28 class CRequestTracker;
29 class CNode;
30
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 static const int64 MIN_TX_FEE = CENT;
36 static const int64 MIN_RELAY_TX_FEE = CENT;
37 static const int64 MAX_MONEY = 2000000000 * COIN;
38 static const int64 MAX_MINT_PROOF_OF_WORK = 9999 * COIN;
39 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
40 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
41 static const int COINBASE_MATURITY = 500;
42 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
43 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
44 #ifdef USE_UPNP
45 static const int fHaveUPnP = true;
46 #else
47 static const int fHaveUPnP = false;
48 #endif
49
50 static const uint256 hashGenesisBlockOfficial("0x0000000032fe677166d54963b62a4677d8957e87c508eaa4fd7eb1c880cd27e3");
51 static const uint256 hashGenesisBlockTestNet("0x00000001f757bb737f6596503e17cd17b0658ce630cc727c0cca81aec47c9f06");
52
53 extern CScript COINBASE_FLAGS;
54
55
56
57
58
59
60 extern CCriticalSection cs_main;
61 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
62 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
63 extern uint256 hashGenesisBlock;
64 extern CBlockIndex* pindexGenesisBlock;
65 extern int nBestHeight;
66 extern CBigNum bnBestChainTrust;
67 extern CBigNum bnBestInvalidTrust;
68 extern uint256 hashBestChain;
69 extern CBlockIndex* pindexBest;
70 extern unsigned int nTransactionsUpdated;
71 extern uint64 nLastBlockTx;
72 extern uint64 nLastBlockSize;
73 extern const std::string strMessageMagic;
74 extern double dHashesPerSec;
75 extern int64 nHPSTimerStart;
76 extern int64 nTimeBestReceived;
77 extern CCriticalSection cs_setpwalletRegistered;
78 extern std::set<CWallet*> setpwalletRegistered;
79 extern std::map<uint256, CBlock*> mapOrphanBlocks;
80
81 // Settings
82 extern int64 nTransactionFee;
83
84
85
86
87
88 class CReserveKey;
89 class CTxDB;
90 class CTxIndex;
91
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 int64 GetProofOfWorkReward(unsigned int nBits);
109 int64 GetProofOfStakeReward(int64 nCoinAge);
110 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
111 int GetNumBlocksOfPeers();
112 bool IsInitialBlockDownload();
113 std::string GetWarnings(std::string strFor);
114 uint256 WantedByOrphan(const CBlock* pblockOrphan);
115 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
116 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
117
118
119
120
121
122
123
124
125
126
127
128 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
129
130 /** Position on disk for a particular transaction. */
131 class CDiskTxPos
132 {
133 public:
134     unsigned int nFile;
135     unsigned int nBlockPos;
136     unsigned int nTxPos;
137
138     CDiskTxPos()
139     {
140         SetNull();
141     }
142
143     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
144     {
145         nFile = nFileIn;
146         nBlockPos = nBlockPosIn;
147         nTxPos = nTxPosIn;
148     }
149
150     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
151     void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
152     bool IsNull() const { return (nFile == -1); }
153
154     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
155     {
156         return (a.nFile     == b.nFile &&
157                 a.nBlockPos == b.nBlockPos &&
158                 a.nTxPos    == b.nTxPos);
159     }
160
161     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
162     {
163         return !(a == b);
164     }
165
166     std::string ToString() const
167     {
168         if (IsNull())
169             return "null";
170         else
171             return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
172     }
173
174     void print() const
175     {
176         printf("%s", ToString().c_str());
177     }
178 };
179
180
181
182 /** An inpoint - a combination of a transaction and an index n into its vin */
183 class CInPoint
184 {
185 public:
186     CTransaction* ptx;
187     unsigned int n;
188
189     CInPoint() { SetNull(); }
190     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
191     void SetNull() { ptx = NULL; n = -1; }
192     bool IsNull() const { return (ptx == NULL && n == -1); }
193 };
194
195
196
197 /** An outpoint - a combination of a transaction hash and an index n into its vout */
198 class COutPoint
199 {
200 public:
201     uint256 hash;
202     unsigned int n;
203
204     COutPoint() { SetNull(); }
205     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
206     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
207     void SetNull() { hash = 0; n = -1; }
208     bool IsNull() const { return (hash == 0 && n == -1); }
209
210     friend bool operator<(const COutPoint& a, const COutPoint& b)
211     {
212         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
213     }
214
215     friend bool operator==(const COutPoint& a, const COutPoint& b)
216     {
217         return (a.hash == b.hash && a.n == b.n);
218     }
219
220     friend bool operator!=(const COutPoint& a, const COutPoint& b)
221     {
222         return !(a == b);
223     }
224
225     std::string ToString() const
226     {
227         return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
228     }
229
230     void print() const
231     {
232         printf("%s\n", ToString().c_str());
233     }
234 };
235
236
237
238
239 /** An input of a transaction.  It contains the location of the previous
240  * transaction's output that it claims and a signature that matches the
241  * output's public key.
242  */
243 class CTxIn
244 {
245 public:
246     COutPoint prevout;
247     CScript scriptSig;
248     unsigned int nSequence;
249
250     CTxIn()
251     {
252         nSequence = std::numeric_limits<unsigned int>::max();
253     }
254
255     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
256     {
257         prevout = prevoutIn;
258         scriptSig = scriptSigIn;
259         nSequence = nSequenceIn;
260     }
261
262     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
263     {
264         prevout = COutPoint(hashPrevTx, nOut);
265         scriptSig = scriptSigIn;
266         nSequence = nSequenceIn;
267     }
268
269     IMPLEMENT_SERIALIZE
270     (
271         READWRITE(prevout);
272         READWRITE(scriptSig);
273         READWRITE(nSequence);
274     )
275
276     bool IsFinal() const
277     {
278         return (nSequence == std::numeric_limits<unsigned int>::max());
279     }
280
281     friend bool operator==(const CTxIn& a, const CTxIn& b)
282     {
283         return (a.prevout   == b.prevout &&
284                 a.scriptSig == b.scriptSig &&
285                 a.nSequence == b.nSequence);
286     }
287
288     friend bool operator!=(const CTxIn& a, const CTxIn& b)
289     {
290         return !(a == b);
291     }
292
293     std::string ToString() const
294     {
295         std::string str;
296         str += "CTxIn(";
297         str += prevout.ToString();
298         if (prevout.IsNull())
299             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
300         else
301             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
302         if (nSequence != std::numeric_limits<unsigned int>::max())
303             str += strprintf(", nSequence=%u", nSequence);
304         str += ")";
305         return str;
306     }
307
308     void print() const
309     {
310         printf("%s\n", ToString().c_str());
311     }
312 };
313
314
315
316
317 /** An output of a transaction.  It contains the public key that the next input
318  * must be able to sign with to claim it.
319  */
320 class CTxOut
321 {
322 public:
323     int64 nValue;
324     CScript scriptPubKey;
325
326     CTxOut()
327     {
328         SetNull();
329     }
330
331     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
332     {
333         nValue = nValueIn;
334         scriptPubKey = scriptPubKeyIn;
335     }
336
337     IMPLEMENT_SERIALIZE
338     (
339         READWRITE(nValue);
340         READWRITE(scriptPubKey);
341     )
342
343     void SetNull()
344     {
345         nValue = -1;
346         scriptPubKey.clear();
347     }
348
349     bool IsNull()
350     {
351         return (nValue == -1);
352     }
353
354     void SetEmpty()
355     {
356         nValue = 0;
357         scriptPubKey.clear();
358     }
359
360     bool IsEmpty() const
361     {
362         return (nValue == 0 && scriptPubKey.empty());
363     }
364
365     uint256 GetHash() const
366     {
367         return SerializeHash(*this);
368     }
369
370     friend bool operator==(const CTxOut& a, const CTxOut& b)
371     {
372         return (a.nValue       == b.nValue &&
373                 a.scriptPubKey == b.scriptPubKey);
374     }
375
376     friend bool operator!=(const CTxOut& a, const CTxOut& b)
377     {
378         return !(a == b);
379     }
380
381     std::string ToString() const
382     {
383         if (IsEmpty()) return "CTxOut(empty)";
384         if (scriptPubKey.size() < 6)
385             return "CTxOut(error)";
386         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
387     }
388
389     void print() const
390     {
391         printf("%s\n", ToString().c_str());
392     }
393 };
394
395
396
397
398 enum GetMinFee_mode
399 {
400     GMF_BLOCK,
401     GMF_RELAY,
402     GMF_SEND,
403 };
404
405 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
406
407 /** The basic transaction that is broadcasted on the network and contained in
408  * blocks.  A transaction can contain multiple inputs and outputs.
409  */
410 class CTransaction
411 {
412 public:
413     int nVersion;
414     unsigned int nTime;
415     std::vector<CTxIn> vin;
416     std::vector<CTxOut> vout;
417     unsigned int nLockTime;
418
419     // Denial-of-service detection:
420     mutable int nDoS;
421     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
422
423     CTransaction()
424     {
425         SetNull();
426     }
427
428     IMPLEMENT_SERIALIZE
429     (
430         READWRITE(this->nVersion);
431         nVersion = this->nVersion;
432         READWRITE(nTime);
433         READWRITE(vin);
434         READWRITE(vout);
435         READWRITE(nLockTime);
436     )
437
438     void SetNull()
439     {
440         nVersion = 1;
441         nTime = GetAdjustedTime();
442         vin.clear();
443         vout.clear();
444         nLockTime = 0;
445         nDoS = 0;  // Denial-of-service prevention
446     }
447
448     bool IsNull() const
449     {
450         return (vin.empty() && vout.empty());
451     }
452
453     uint256 GetHash() const
454     {
455         return SerializeHash(*this);
456     }
457
458     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
459     {
460         // Time based nLockTime implemented in 0.1.6
461         if (nLockTime == 0)
462             return true;
463         if (nBlockHeight == 0)
464             nBlockHeight = nBestHeight;
465         if (nBlockTime == 0)
466             nBlockTime = GetAdjustedTime();
467         if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
468             return true;
469         BOOST_FOREACH(const CTxIn& txin, vin)
470             if (!txin.IsFinal())
471                 return false;
472         return true;
473     }
474
475     bool IsNewerThan(const CTransaction& old) const
476     {
477         if (vin.size() != old.vin.size())
478             return false;
479         for (unsigned int i = 0; i < vin.size(); i++)
480             if (vin[i].prevout != old.vin[i].prevout)
481                 return false;
482
483         bool fNewer = false;
484         unsigned int nLowest = std::numeric_limits<unsigned int>::max();
485         for (unsigned int i = 0; i < vin.size(); i++)
486         {
487             if (vin[i].nSequence != old.vin[i].nSequence)
488             {
489                 if (vin[i].nSequence <= nLowest)
490                 {
491                     fNewer = false;
492                     nLowest = vin[i].nSequence;
493                 }
494                 if (old.vin[i].nSequence < nLowest)
495                 {
496                     fNewer = true;
497                     nLowest = old.vin[i].nSequence;
498                 }
499             }
500         }
501         return fNewer;
502     }
503
504     bool IsCoinBase() const
505     {
506         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
507     }
508
509     bool IsCoinStake() const
510     {
511         // ppcoin: the coin stake transaction is marked with the first output empty
512         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
513     }
514
515     /** Check for standard transaction types
516         @return True if all outputs (scriptPubKeys) use only standard transaction forms
517     */
518     bool IsStandard() const;
519
520     /** Check for standard transaction types
521         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
522         @return True if all inputs (scriptSigs) use only standard transaction forms
523         @see CTransaction::FetchInputs
524     */
525     bool AreInputsStandard(const MapPrevTx& mapInputs) const;
526
527     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
528         @return number of sigops this transaction's outputs will produce when spent
529         @see CTransaction::FetchInputs
530     */
531     unsigned int GetLegacySigOpCount() const;
532
533     /** Count ECDSA signature operations in pay-to-script-hash inputs.
534
535         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
536         @return maximum number of sigops required to validate this transaction's inputs
537         @see CTransaction::FetchInputs
538      */
539     unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
540
541     /** Amount of bitcoins spent by this transaction.
542         @return sum of all outputs (note: does not include fees)
543      */
544     int64 GetValueOut() const
545     {
546         int64 nValueOut = 0;
547         BOOST_FOREACH(const CTxOut& txout, vout)
548         {
549             nValueOut += txout.nValue;
550             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
551                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
552         }
553         return nValueOut;
554     }
555
556     /** Amount of bitcoins coming in to this transaction
557         Note that lightweight clients may not know anything besides the hash of previous transactions,
558         so may not be able to calculate this.
559
560         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
561         @return Sum of value of all inputs (scriptSigs)
562         @see CTransaction::FetchInputs
563      */
564     int64 GetValueIn(const MapPrevTx& mapInputs) const;
565
566     static bool AllowFree(double dPriority)
567     {
568         // Large (in bytes) low-priority (new, small-coin) transactions
569         // need a fee.
570         return dPriority > COIN * 144 / 250;
571     }
572
573     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
574     {
575         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
576         int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577
578         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
579         unsigned int nNewBlockSize = nBlockSize + nBytes;
580         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
581
582         if (fAllowFree)
583         {
584             if (nBlockSize == 1)
585             {
586                 // Transactions under 10K are free
587                 // (about 4500bc if made of 50bc inputs)
588                 if (nBytes < 10000)
589                     nMinFee = 0;
590             }
591             else
592             {
593                 // Free transaction area
594                 if (nNewBlockSize < 27000)
595                     nMinFee = 0;
596             }
597         }
598
599         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
600         if (nMinFee < nBaseFee)
601         {
602             BOOST_FOREACH(const CTxOut& txout, vout)
603                 if (txout.nValue < CENT)
604                     nMinFee = nBaseFee;
605         }
606
607         // Raise the price as the block approaches full
608         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
609         {
610             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
611                 return MAX_MONEY;
612             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
613         }
614
615         if (!MoneyRange(nMinFee))
616             nMinFee = MAX_MONEY;
617         return nMinFee;
618     }
619
620
621     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
622     {
623         CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
624         if (!filein)
625             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
626
627         // Read transaction
628         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
629             return error("CTransaction::ReadFromDisk() : fseek failed");
630
631         try {
632             filein >> *this;
633         }
634         catch (std::exception &e) {
635             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
636         }
637
638         // Return file pointer
639         if (pfileRet)
640         {
641             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
642                 return error("CTransaction::ReadFromDisk() : second fseek failed");
643             *pfileRet = filein.release();
644         }
645         return true;
646     }
647
648     friend bool operator==(const CTransaction& a, const CTransaction& b)
649     {
650         return (a.nVersion  == b.nVersion &&
651                 a.nTime     == b.nTime &&
652                 a.vin       == b.vin &&
653                 a.vout      == b.vout &&
654                 a.nLockTime == b.nLockTime);
655     }
656
657     friend bool operator!=(const CTransaction& a, const CTransaction& b)
658     {
659         return !(a == b);
660     }
661
662
663     std::string ToString() const
664     {
665         std::string str;
666         str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
667         str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
668             GetHash().ToString().substr(0,10).c_str(),
669             nTime,
670             nVersion,
671             vin.size(),
672             vout.size(),
673             nLockTime);
674         for (unsigned int i = 0; i < vin.size(); i++)
675             str += "    " + vin[i].ToString() + "\n";
676         for (unsigned int i = 0; i < vout.size(); i++)
677             str += "    " + vout[i].ToString() + "\n";
678         return str;
679     }
680
681     void print() const
682     {
683         printf("%s", ToString().c_str());
684     }
685
686
687     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
688     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
689     bool ReadFromDisk(COutPoint prevout);
690     bool DisconnectInputs(CTxDB& txdb);
691
692     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
693
694      @param[in] txdb    Transaction database
695      @param[in] mapTestPool     List of pending changes to the transaction index database
696      @param[in] fBlock  True if being called to add a new best-block to the chain
697      @param[in] fMiner  True if being called by CreateNewBlock
698      @param[out] inputsRet      Pointers to this transaction's inputs
699      @param[out] fInvalid       returns true if transaction is invalid
700      @return    Returns true if all inputs are in txdb or mapTestPool
701      */
702     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
703                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
704
705     /** Sanity check previous transactions, then, if all checks succeed,
706         mark them as spent by this transaction.
707
708         @param[in] inputs       Previous transactions (from FetchInputs)
709         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
710         @param[in] posThisTx    Position of this transaction on disk
711         @param[in] pindexBlock
712         @param[in] fBlock       true if called from ConnectBlock
713         @param[in] fMiner       true if called from CreateNewBlock
714         @param[in] fStrictPayToScriptHash       true if fully validating p2sh transactions
715         @return Returns true if all checks succeed
716      */
717     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
718                        std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
719                        const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
720     bool ClientConnectInputs();
721     bool CheckTransaction() const;
722     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
723     bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const;  // ppcoin: get transaction coin age
724     bool CheckProofOfStake(unsigned int nBits) const;
725
726 protected:
727     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
728 };
729
730
731
732
733
734 /** A transaction with a merkle branch linking it to the block chain. */
735 class CMerkleTx : public CTransaction
736 {
737 public:
738     uint256 hashBlock;
739     std::vector<uint256> vMerkleBranch;
740     int nIndex;
741
742     // memory only
743     mutable bool fMerkleVerified;
744
745
746     CMerkleTx()
747     {
748         Init();
749     }
750
751     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
752     {
753         Init();
754     }
755
756     void Init()
757     {
758         hashBlock = 0;
759         nIndex = -1;
760         fMerkleVerified = false;
761     }
762
763
764     IMPLEMENT_SERIALIZE
765     (
766         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
767         nVersion = this->nVersion;
768         READWRITE(hashBlock);
769         READWRITE(vMerkleBranch);
770         READWRITE(nIndex);
771     )
772
773
774     int SetMerkleBranch(const CBlock* pblock=NULL);
775     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
776     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
777     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
778     int GetBlocksToMaturity() const;
779     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
780     bool AcceptToMemoryPool();
781 };
782
783
784
785
786 /**  A txdb record that contains the disk location of a transaction and the
787  * locations of transactions that spend its outputs.  vSpent is really only
788  * used as a flag, but having the location is very helpful for debugging.
789  */
790 class CTxIndex
791 {
792 public:
793     CDiskTxPos pos;
794     std::vector<CDiskTxPos> vSpent;
795
796     CTxIndex()
797     {
798         SetNull();
799     }
800
801     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
802     {
803         pos = posIn;
804         vSpent.resize(nOutputs);
805     }
806
807     IMPLEMENT_SERIALIZE
808     (
809         if (!(nType & SER_GETHASH))
810             READWRITE(nVersion);
811         READWRITE(pos);
812         READWRITE(vSpent);
813     )
814
815     void SetNull()
816     {
817         pos.SetNull();
818         vSpent.clear();
819     }
820
821     bool IsNull()
822     {
823         return pos.IsNull();
824     }
825
826     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
827     {
828         return (a.pos    == b.pos &&
829                 a.vSpent == b.vSpent);
830     }
831
832     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
833     {
834         return !(a == b);
835     }
836     int GetDepthInMainChain() const;
837  
838 };
839
840
841
842
843
844 /** Nodes collect new transactions into a block, hash them into a hash tree,
845  * and scan through nonce values to make the block's hash satisfy proof-of-work
846  * requirements.  When they solve the proof-of-work, they broadcast the block
847  * to everyone and the block is added to the block chain.  The first transaction
848  * in the block is a special one that creates a new coin owned by the creator
849  * of the block.
850  *
851  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
852  * is indexed by CBlockIndex objects in memory.
853  */
854 class CBlock
855 {
856 public:
857     // header
858     int nVersion;
859     uint256 hashPrevBlock;
860     uint256 hashMerkleRoot;
861     unsigned int nTime;
862     unsigned int nBits;
863     unsigned int nNonce;
864
865     // network and disk
866     std::vector<CTransaction> vtx;
867
868     // ppcoin: block signature - signed by coin base txout[0]'s owner
869     std::vector<unsigned char> vchBlockSig;
870
871     // memory only
872     mutable std::vector<uint256> vMerkleTree;
873
874     // Denial-of-service detection:
875     mutable int nDoS;
876     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
877
878     CBlock()
879     {
880         SetNull();
881     }
882
883     IMPLEMENT_SERIALIZE
884     (
885         READWRITE(this->nVersion);
886         nVersion = this->nVersion;
887         READWRITE(hashPrevBlock);
888         READWRITE(hashMerkleRoot);
889         READWRITE(nTime);
890         READWRITE(nBits);
891         READWRITE(nNonce);
892
893         // ConnectBlock depends on vtx following header to generate CDiskTxPos
894         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
895         {
896             READWRITE(vtx);
897             READWRITE(vchBlockSig);
898         }
899         else if (fRead)
900         {
901             const_cast<CBlock*>(this)->vtx.clear();
902             const_cast<CBlock*>(this)->vchBlockSig.clear();
903         }
904     )
905
906     void SetNull()
907     {
908         nVersion = 1;
909         hashPrevBlock = 0;
910         hashMerkleRoot = 0;
911         nTime = 0;
912         nBits = 0;
913         nNonce = 0;
914         vtx.clear();
915         vchBlockSig.clear();
916         vMerkleTree.clear();
917         nDoS = 0;
918     }
919
920     bool IsNull() const
921     {
922         return (nBits == 0);
923     }
924
925     uint256 GetHash() const
926     {
927         return Hash(BEGIN(nVersion), END(nNonce));
928     }
929
930     int64 GetBlockTime() const
931     {
932         return (int64)nTime;
933     }
934
935     void UpdateTime(const CBlockIndex* pindexPrev);
936
937     // ppcoin: two types of block: proof-of-work or proof-of-stake
938     bool IsProofOfStake() const
939     {
940         return (vtx.size() > 1 && vtx[1].IsCoinStake());
941     }
942
943     bool IsProofOfWork() const
944     {
945         return !IsProofOfStake();
946     }
947
948     std::pair<COutPoint, unsigned int> GetProofOfStake() const
949     {
950         return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
951     }
952
953     // ppcoin: get max transaction timestamp
954     int64 GetMaxTransactionTime() const
955     {
956         int64 maxTransactionTime = 0;
957         BOOST_FOREACH(const CTransaction& tx, vtx)
958             maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
959         return maxTransactionTime;
960     }
961
962     uint256 BuildMerkleTree() const
963     {
964         vMerkleTree.clear();
965         BOOST_FOREACH(const CTransaction& tx, vtx)
966             vMerkleTree.push_back(tx.GetHash());
967         int j = 0;
968         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
969         {
970             for (int i = 0; i < nSize; i += 2)
971             {
972                 int i2 = std::min(i+1, nSize-1);
973                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
974                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
975             }
976             j += nSize;
977         }
978         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
979     }
980
981     std::vector<uint256> GetMerkleBranch(int nIndex) const
982     {
983         if (vMerkleTree.empty())
984             BuildMerkleTree();
985         std::vector<uint256> vMerkleBranch;
986         int j = 0;
987         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
988         {
989             int i = std::min(nIndex^1, nSize-1);
990             vMerkleBranch.push_back(vMerkleTree[j+i]);
991             nIndex >>= 1;
992             j += nSize;
993         }
994         return vMerkleBranch;
995     }
996
997     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
998     {
999         if (nIndex == -1)
1000             return 0;
1001         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1002         {
1003             if (nIndex & 1)
1004                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1005             else
1006                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1007             nIndex >>= 1;
1008         }
1009         return hash;
1010     }
1011
1012
1013     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1014     {
1015         // Open history file to append
1016         CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1017         if (!fileout)
1018             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1019
1020         // Write index header
1021         unsigned int nSize = fileout.GetSerializeSize(*this);
1022         fileout << FLATDATA(pchMessageStart) << nSize;
1023
1024         // Write block
1025         long fileOutPos = ftell(fileout);
1026         if (fileOutPos < 0)
1027             return error("CBlock::WriteToDisk() : ftell failed");
1028         nBlockPosRet = fileOutPos;
1029         fileout << *this;
1030
1031         // Flush stdio buffers and commit to disk before returning
1032         fflush(fileout);
1033         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1034         {
1035 #ifdef WIN32
1036             _commit(_fileno(fileout));
1037 #else
1038             fsync(fileno(fileout));
1039 #endif
1040         }
1041
1042         return true;
1043     }
1044
1045     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1046     {
1047         SetNull();
1048
1049         // Open history file to read
1050         CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1051         if (!filein)
1052             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1053         if (!fReadTransactions)
1054             filein.nType |= SER_BLOCKHEADERONLY;
1055
1056         // Read block
1057         try {
1058             filein >> *this;
1059         }
1060         catch (std::exception &e) {
1061             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1062         }
1063
1064         // Check the header
1065         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1066             return error("CBlock::ReadFromDisk() : errors in block header");
1067
1068         return true;
1069     }
1070
1071
1072
1073     void print() const
1074     {
1075         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1076             GetHash().ToString().substr(0,20).c_str(),
1077             nVersion,
1078             hashPrevBlock.ToString().substr(0,20).c_str(),
1079             hashMerkleRoot.ToString().substr(0,10).c_str(),
1080             nTime, nBits, nNonce,
1081             vtx.size(),
1082             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1083         for (unsigned int i = 0; i < vtx.size(); i++)
1084         {
1085             printf("  ");
1086             vtx[i].print();
1087         }
1088         printf("  vMerkleTree: ");
1089         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1090             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1091         printf("\n");
1092     }
1093
1094
1095     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1096     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1097     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1098     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1099     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1100     bool CheckBlock() const;
1101     bool AcceptBlock();
1102     bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1103     bool SignBlock(const CKeyStore& keystore);
1104     bool CheckBlockSignature() const;
1105
1106 private:
1107     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1108 };
1109
1110
1111
1112
1113
1114
1115 /** The block chain is a tree shaped structure starting with the
1116  * genesis block at the root, with each block potentially having multiple
1117  * candidates to be the next block.  pprev and pnext link a path through the
1118  * main/longest chain.  A blockindex may have multiple pprev pointing back
1119  * to it, but pnext will only point forward to the longest branch, or will
1120  * be null if the block is not part of the longest chain.
1121  */
1122 class CBlockIndex
1123 {
1124 public:
1125     const uint256* phashBlock;
1126     CBlockIndex* pprev;
1127     CBlockIndex* pnext;
1128     unsigned int nFile;
1129     unsigned int nBlockPos;
1130     CBigNum bnChainTrust; // ppcoin: trust score of block chain
1131     int nHeight;
1132     int64 nMint;
1133     int64 nMoneySupply;
1134     bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1135     COutPoint prevoutStake;
1136     unsigned int nStakeTime;
1137
1138     // block header
1139     int nVersion;
1140     uint256 hashMerkleRoot;
1141     unsigned int nTime;
1142     unsigned int nBits;
1143     unsigned int nNonce;
1144
1145
1146     CBlockIndex()
1147     {
1148         phashBlock = NULL;
1149         pprev = NULL;
1150         pnext = NULL;
1151         nFile = 0;
1152         nBlockPos = 0;
1153         nHeight = 0;
1154         bnChainTrust = 0;
1155         nMint = 0;
1156         nMoneySupply = 0;
1157         fProofOfStake = true;
1158         prevoutStake.SetNull();
1159         nStakeTime = 0;
1160
1161         nVersion       = 0;
1162         hashMerkleRoot = 0;
1163         nTime          = 0;
1164         nBits          = 0;
1165         nNonce         = 0;
1166     }
1167
1168     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1169     {
1170         phashBlock = NULL;
1171         pprev = NULL;
1172         pnext = NULL;
1173         nFile = nFileIn;
1174         nBlockPos = nBlockPosIn;
1175         nHeight = 0;
1176         bnChainTrust = 0;
1177         nMint = 0;
1178         nMoneySupply = 0;
1179         fProofOfStake = block.IsProofOfStake();
1180         if (fProofOfStake)
1181         {
1182             prevoutStake = block.vtx[1].vin[0].prevout;
1183             nStakeTime = block.vtx[1].nTime;
1184         }
1185         else
1186         {
1187             prevoutStake.SetNull();
1188             nStakeTime = 0;
1189         }
1190
1191         nVersion       = block.nVersion;
1192         hashMerkleRoot = block.hashMerkleRoot;
1193         nTime          = block.nTime;
1194         nBits          = block.nBits;
1195         nNonce         = block.nNonce;
1196     }
1197
1198     CBlock GetBlockHeader() const
1199     {
1200         CBlock block;
1201         block.nVersion       = nVersion;
1202         if (pprev)
1203             block.hashPrevBlock = pprev->GetBlockHash();
1204         block.hashMerkleRoot = hashMerkleRoot;
1205         block.nTime          = nTime;
1206         block.nBits          = nBits;
1207         block.nNonce         = nNonce;
1208         return block;
1209     }
1210
1211     uint256 GetBlockHash() const
1212     {
1213         return *phashBlock;
1214     }
1215
1216     int64 GetBlockTime() const
1217     {
1218         return (int64)nTime;
1219     }
1220
1221     CBigNum GetBlockTrust() const
1222     {
1223         CBigNum bnTarget;
1224         bnTarget.SetCompact(nBits);
1225         if (bnTarget <= 0)
1226             return 0;
1227         return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1228     }
1229
1230     bool IsInMainChain() const
1231     {
1232         return (pnext || this == pindexBest);
1233     }
1234
1235     bool CheckIndex() const
1236     {
1237         return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1238     }
1239
1240     bool EraseBlockFromDisk()
1241     {
1242         // Open history file
1243         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1244         if (!fileout)
1245             return false;
1246
1247         // Overwrite with empty null block
1248         CBlock block;
1249         block.SetNull();
1250         fileout << block;
1251
1252         return true;
1253     }
1254
1255     enum { nMedianTimeSpan=11 };
1256
1257     int64 GetMedianTimePast() const
1258     {
1259         int64 pmedian[nMedianTimeSpan];
1260         int64* pbegin = &pmedian[nMedianTimeSpan];
1261         int64* pend = &pmedian[nMedianTimeSpan];
1262
1263         const CBlockIndex* pindex = this;
1264         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1265             *(--pbegin) = pindex->GetBlockTime();
1266
1267         std::sort(pbegin, pend);
1268         return pbegin[(pend - pbegin)/2];
1269     }
1270
1271     int64 GetMedianTime() const
1272     {
1273         const CBlockIndex* pindex = this;
1274         for (int i = 0; i < nMedianTimeSpan/2; i++)
1275         {
1276             if (!pindex->pnext)
1277                 return GetBlockTime();
1278             pindex = pindex->pnext;
1279         }
1280         return pindex->GetMedianTimePast();
1281     }
1282
1283     bool IsProofOfWork() const
1284     {
1285         return !fProofOfStake;
1286     }
1287
1288     bool IsProofOfStake() const
1289     {
1290         return fProofOfStake;
1291     }
1292
1293     std::string ToString() const
1294     {
1295         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1296             pprev, pnext, nFile, nBlockPos, nHeight,
1297             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1298             fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1299             hashMerkleRoot.ToString().substr(0,10).c_str(),
1300             GetBlockHash().ToString().substr(0,20).c_str());
1301     }
1302
1303     void print() const
1304     {
1305         printf("%s\n", ToString().c_str());
1306     }
1307 };
1308
1309
1310
1311 /** Used to marshal pointers into hashes for db storage. */
1312 class CDiskBlockIndex : public CBlockIndex
1313 {
1314 public:
1315     uint256 hashPrev;
1316     uint256 hashNext;
1317
1318     CDiskBlockIndex()
1319     {
1320         hashPrev = 0;
1321         hashNext = 0;
1322     }
1323
1324     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1325     {
1326         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1327         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1328     }
1329
1330     IMPLEMENT_SERIALIZE
1331     (
1332         if (!(nType & SER_GETHASH))
1333             READWRITE(nVersion);
1334
1335         READWRITE(hashNext);
1336         READWRITE(nFile);
1337         READWRITE(nBlockPos);
1338         READWRITE(nHeight);
1339         READWRITE(nMint);
1340         READWRITE(nMoneySupply);
1341         READWRITE(fProofOfStake);
1342         if (fProofOfStake)
1343         {
1344             READWRITE(prevoutStake);
1345             READWRITE(nStakeTime);
1346         }
1347         else if (fRead)
1348         {
1349             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1350             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1351         }
1352
1353         // block header
1354         READWRITE(this->nVersion);
1355         READWRITE(hashPrev);
1356         READWRITE(hashMerkleRoot);
1357         READWRITE(nTime);
1358         READWRITE(nBits);
1359         READWRITE(nNonce);
1360     )
1361
1362     uint256 GetBlockHash() const
1363     {
1364         CBlock block;
1365         block.nVersion        = nVersion;
1366         block.hashPrevBlock   = hashPrev;
1367         block.hashMerkleRoot  = hashMerkleRoot;
1368         block.nTime           = nTime;
1369         block.nBits           = nBits;
1370         block.nNonce          = nNonce;
1371         return block.GetHash();
1372     }
1373
1374
1375     std::string ToString() const
1376     {
1377         std::string str = "CDiskBlockIndex(";
1378         str += CBlockIndex::ToString();
1379         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1380             GetBlockHash().ToString().c_str(),
1381             hashPrev.ToString().substr(0,20).c_str(),
1382             hashNext.ToString().substr(0,20).c_str());
1383         return str;
1384     }
1385
1386     void print() const
1387     {
1388         printf("%s\n", ToString().c_str());
1389     }
1390 };
1391
1392
1393
1394
1395
1396
1397
1398
1399 /** Describes a place in the block chain to another node such that if the
1400  * other node doesn't have the same branch, it can find a recent common trunk.
1401  * The further back it is, the further before the fork it may be.
1402  */
1403 class CBlockLocator
1404 {
1405 protected:
1406     std::vector<uint256> vHave;
1407 public:
1408
1409     CBlockLocator()
1410     {
1411     }
1412
1413     explicit CBlockLocator(const CBlockIndex* pindex)
1414     {
1415         Set(pindex);
1416     }
1417
1418     explicit CBlockLocator(uint256 hashBlock)
1419     {
1420         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1421         if (mi != mapBlockIndex.end())
1422             Set((*mi).second);
1423     }
1424
1425     CBlockLocator(const std::vector<uint256>& vHaveIn)
1426     {
1427         vHave = vHaveIn;
1428     }
1429
1430     IMPLEMENT_SERIALIZE
1431     (
1432         if (!(nType & SER_GETHASH))
1433             READWRITE(nVersion);
1434         READWRITE(vHave);
1435     )
1436
1437     void SetNull()
1438     {
1439         vHave.clear();
1440     }
1441
1442     bool IsNull()
1443     {
1444         return vHave.empty();
1445     }
1446
1447     void Set(const CBlockIndex* pindex)
1448     {
1449         vHave.clear();
1450         int nStep = 1;
1451         while (pindex)
1452         {
1453             vHave.push_back(pindex->GetBlockHash());
1454
1455             // Exponentially larger steps back
1456             for (int i = 0; pindex && i < nStep; i++)
1457                 pindex = pindex->pprev;
1458             if (vHave.size() > 10)
1459                 nStep *= 2;
1460         }
1461         vHave.push_back(hashGenesisBlock);
1462     }
1463
1464     int GetDistanceBack()
1465     {
1466         // Retrace how far back it was in the sender's branch
1467         int nDistance = 0;
1468         int nStep = 1;
1469         BOOST_FOREACH(const uint256& hash, vHave)
1470         {
1471             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1472             if (mi != mapBlockIndex.end())
1473             {
1474                 CBlockIndex* pindex = (*mi).second;
1475                 if (pindex->IsInMainChain())
1476                     return nDistance;
1477             }
1478             nDistance += nStep;
1479             if (nDistance > 10)
1480                 nStep *= 2;
1481         }
1482         return nDistance;
1483     }
1484
1485     CBlockIndex* GetBlockIndex()
1486     {
1487         // Find the first block the caller has in the main chain
1488         BOOST_FOREACH(const uint256& hash, vHave)
1489         {
1490             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1491             if (mi != mapBlockIndex.end())
1492             {
1493                 CBlockIndex* pindex = (*mi).second;
1494                 if (pindex->IsInMainChain())
1495                     return pindex;
1496             }
1497         }
1498         return pindexGenesisBlock;
1499     }
1500
1501     uint256 GetBlockHash()
1502     {
1503         // Find the first block the caller has in the main chain
1504         BOOST_FOREACH(const uint256& hash, vHave)
1505         {
1506             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1507             if (mi != mapBlockIndex.end())
1508             {
1509                 CBlockIndex* pindex = (*mi).second;
1510                 if (pindex->IsInMainChain())
1511                     return hash;
1512             }
1513         }
1514         return hashGenesisBlock;
1515     }
1516
1517     int GetHeight()
1518     {
1519         CBlockIndex* pindex = GetBlockIndex();
1520         if (!pindex)
1521             return 0;
1522         return pindex->nHeight;
1523     }
1524 };
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534 /** Alerts are for notifying old versions if they become too obsolete and
1535  * need to upgrade.  The message is displayed in the status bar.
1536  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1537  * not read the entire buffer if the alert is for a newer version, but older
1538  * versions can still relay the original data.
1539  */
1540 class CUnsignedAlert
1541 {
1542 public:
1543     int nVersion;
1544     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1545     int64 nExpiration;
1546     int nID;
1547     int nCancel;
1548     std::set<int> setCancel;
1549     int nMinVer;            // lowest version inclusive
1550     int nMaxVer;            // highest version inclusive
1551     std::set<std::string> setSubVer;  // empty matches all
1552     int nPriority;
1553
1554     // Actions
1555     std::string strComment;
1556     std::string strStatusBar;
1557     std::string strReserved;
1558
1559     IMPLEMENT_SERIALIZE
1560     (
1561         READWRITE(this->nVersion);
1562         nVersion = this->nVersion;
1563         READWRITE(nRelayUntil);
1564         READWRITE(nExpiration);
1565         READWRITE(nID);
1566         READWRITE(nCancel);
1567         READWRITE(setCancel);
1568         READWRITE(nMinVer);
1569         READWRITE(nMaxVer);
1570         READWRITE(setSubVer);
1571         READWRITE(nPriority);
1572
1573         READWRITE(strComment);
1574         READWRITE(strStatusBar);
1575         READWRITE(strReserved);
1576     )
1577
1578     void SetNull()
1579     {
1580         nVersion = 1;
1581         nRelayUntil = 0;
1582         nExpiration = 0;
1583         nID = 0;
1584         nCancel = 0;
1585         setCancel.clear();
1586         nMinVer = 0;
1587         nMaxVer = 0;
1588         setSubVer.clear();
1589         nPriority = 0;
1590
1591         strComment.clear();
1592         strStatusBar.clear();
1593         strReserved.clear();
1594     }
1595
1596     std::string ToString() const
1597     {
1598         std::string strSetCancel;
1599         BOOST_FOREACH(int n, setCancel)
1600             strSetCancel += strprintf("%d ", n);
1601         std::string strSetSubVer;
1602         BOOST_FOREACH(std::string str, setSubVer)
1603             strSetSubVer += "\"" + str + "\" ";
1604         return strprintf(
1605                 "CAlert(\n"
1606                 "    nVersion     = %d\n"
1607                 "    nRelayUntil  = %"PRI64d"\n"
1608                 "    nExpiration  = %"PRI64d"\n"
1609                 "    nID          = %d\n"
1610                 "    nCancel      = %d\n"
1611                 "    setCancel    = %s\n"
1612                 "    nMinVer      = %d\n"
1613                 "    nMaxVer      = %d\n"
1614                 "    setSubVer    = %s\n"
1615                 "    nPriority    = %d\n"
1616                 "    strComment   = \"%s\"\n"
1617                 "    strStatusBar = \"%s\"\n"
1618                 ")\n",
1619             nVersion,
1620             nRelayUntil,
1621             nExpiration,
1622             nID,
1623             nCancel,
1624             strSetCancel.c_str(),
1625             nMinVer,
1626             nMaxVer,
1627             strSetSubVer.c_str(),
1628             nPriority,
1629             strComment.c_str(),
1630             strStatusBar.c_str());
1631     }
1632
1633     void print() const
1634     {
1635         printf("%s", ToString().c_str());
1636     }
1637 };
1638
1639 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1640 class CAlert : public CUnsignedAlert
1641 {
1642 public:
1643     std::vector<unsigned char> vchMsg;
1644     std::vector<unsigned char> vchSig;
1645
1646     CAlert()
1647     {
1648         SetNull();
1649     }
1650
1651     IMPLEMENT_SERIALIZE
1652     (
1653         READWRITE(vchMsg);
1654         READWRITE(vchSig);
1655     )
1656
1657     void SetNull()
1658     {
1659         CUnsignedAlert::SetNull();
1660         vchMsg.clear();
1661         vchSig.clear();
1662     }
1663
1664     bool IsNull() const
1665     {
1666         return (nExpiration == 0);
1667     }
1668
1669     uint256 GetHash() const
1670     {
1671         return SerializeHash(*this);
1672     }
1673
1674     bool IsInEffect() const
1675     {
1676         return (GetAdjustedTime() < nExpiration);
1677     }
1678
1679     bool Cancels(const CAlert& alert) const
1680     {
1681         if (!IsInEffect())
1682             return false; // this was a no-op before 31403
1683         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1684     }
1685
1686     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1687     {
1688         // TODO: rework for client-version-embedded-in-strSubVer ?
1689         return (IsInEffect() &&
1690                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1691                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1692     }
1693
1694     bool AppliesToMe() const
1695     {
1696         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1697     }
1698
1699     bool RelayTo(CNode* pnode) const
1700     {
1701         if (!IsInEffect())
1702             return false;
1703         // returns true if wasn't already contained in the set
1704         if (pnode->setKnown.insert(GetHash()).second)
1705         {
1706             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1707                 AppliesToMe() ||
1708                 GetAdjustedTime() < nRelayUntil)
1709             {
1710                 pnode->PushMessage("alert", *this);
1711                 return true;
1712             }
1713         }
1714         return false;
1715     }
1716
1717     bool CheckSignature()
1718     {
1719         CKey key;
1720         if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1721             return error("CAlert::CheckSignature() : SetPubKey failed");
1722         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1723             return error("CAlert::CheckSignature() : verify signature failed");
1724
1725         // Now unserialize the data
1726         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1727         sMsg >> *(CUnsignedAlert*)this;
1728         return true;
1729     }
1730
1731     bool ProcessAlert();
1732 };
1733
1734 class CTxMemPool
1735 {
1736 public:
1737     mutable CCriticalSection cs;
1738     std::map<uint256, CTransaction> mapTx;
1739     std::map<COutPoint, CInPoint> mapNextTx;
1740
1741     bool accept(CTxDB& txdb, CTransaction &tx,
1742                 bool fCheckInputs, bool* pfMissingInputs);
1743     bool addUnchecked(CTransaction &tx);
1744     bool remove(CTransaction &tx);
1745
1746     unsigned long size()
1747     {
1748         LOCK(cs);
1749         return mapTx.size();
1750     }
1751
1752     bool exists(uint256 hash)
1753     {
1754         return (mapTx.count(hash) != 0);
1755     }
1756
1757     CTransaction& lookup(uint256 hash)
1758     {
1759         return mapTx[hash];
1760     }
1761 };
1762
1763 extern CTxMemPool mempool;
1764
1765 #endif