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