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