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