ab4026ade6f21403a7a8a5313eeadb0a2598ce0a
[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 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 %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).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().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 char pchMessageStart[4];
1041         GetMessageStart(pchMessageStart, true);
1042         unsigned int nSize = fileout.GetSerializeSize(*this);
1043         fileout << FLATDATA(pchMessageStart) << nSize;
1044
1045         // Write block
1046         long fileOutPos = ftell(fileout);
1047         if (fileOutPos < 0)
1048             return error("CBlock::WriteToDisk() : ftell failed");
1049         nBlockPosRet = fileOutPos;
1050         fileout << *this;
1051
1052         // Flush stdio buffers and commit to disk before returning
1053         fflush(fileout);
1054         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1055         {
1056 #ifdef WIN32
1057             _commit(_fileno(fileout));
1058 #else
1059             fsync(fileno(fileout));
1060 #endif
1061         }
1062
1063         return true;
1064     }
1065
1066     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1067     {
1068         SetNull();
1069
1070         // Open history file to read
1071         CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1072         if (!filein)
1073             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1074         if (!fReadTransactions)
1075             filein.nType |= SER_BLOCKHEADERONLY;
1076
1077         // Read block
1078         try {
1079             filein >> *this;
1080         }
1081         catch (std::exception &e) {
1082             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1083         }
1084
1085         // Check the header
1086         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1087             return error("CBlock::ReadFromDisk() : errors in block header");
1088
1089         return true;
1090     }
1091
1092
1093
1094     void print() const
1095     {
1096         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1097             GetHash().ToString().substr(0,20).c_str(),
1098             nVersion,
1099             hashPrevBlock.ToString().substr(0,20).c_str(),
1100             hashMerkleRoot.ToString().substr(0,10).c_str(),
1101             nTime, nBits, nNonce,
1102             vtx.size(),
1103             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1104         for (unsigned int i = 0; i < vtx.size(); i++)
1105         {
1106             printf("  ");
1107             vtx[i].print();
1108         }
1109         printf("  vMerkleTree: ");
1110         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1111             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1112         printf("\n");
1113     }
1114
1115
1116     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1117     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1119     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1120     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1121     bool CheckBlock() const;
1122     bool AcceptBlock();
1123     bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1124     bool SignBlock(const CKeyStore& keystore);
1125     bool CheckBlockSignature() const;
1126
1127 private:
1128     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1129 };
1130
1131
1132
1133
1134
1135
1136 /** The block chain is a tree shaped structure starting with the
1137  * genesis block at the root, with each block potentially having multiple
1138  * candidates to be the next block.  pprev and pnext link a path through the
1139  * main/longest chain.  A blockindex may have multiple pprev pointing back
1140  * to it, but pnext will only point forward to the longest branch, or will
1141  * be null if the block is not part of the longest chain.
1142  */
1143 class CBlockIndex
1144 {
1145 public:
1146     const uint256* phashBlock;
1147     CBlockIndex* pprev;
1148     CBlockIndex* pnext;
1149     unsigned int nFile;
1150     unsigned int nBlockPos;
1151     CBigNum bnChainTrust; // ppcoin: trust score of block chain
1152     int nHeight;
1153     int64 nMint;
1154     int64 nMoneySupply;
1155     bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1156     COutPoint prevoutStake;
1157     unsigned int nStakeTime;
1158
1159     // block header
1160     int nVersion;
1161     uint256 hashMerkleRoot;
1162     unsigned int nTime;
1163     unsigned int nBits;
1164     unsigned int nNonce;
1165
1166
1167     CBlockIndex()
1168     {
1169         phashBlock = NULL;
1170         pprev = NULL;
1171         pnext = NULL;
1172         nFile = 0;
1173         nBlockPos = 0;
1174         nHeight = 0;
1175         bnChainTrust = 0;
1176         nMint = 0;
1177         nMoneySupply = 0;
1178         fProofOfStake = true;
1179         prevoutStake.SetNull();
1180         nStakeTime = 0;
1181
1182         nVersion       = 0;
1183         hashMerkleRoot = 0;
1184         nTime          = 0;
1185         nBits          = 0;
1186         nNonce         = 0;
1187     }
1188
1189     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1190     {
1191         phashBlock = NULL;
1192         pprev = NULL;
1193         pnext = NULL;
1194         nFile = nFileIn;
1195         nBlockPos = nBlockPosIn;
1196         nHeight = 0;
1197         bnChainTrust = 0;
1198         nMint = 0;
1199         nMoneySupply = 0;
1200         fProofOfStake = block.IsProofOfStake();
1201         if (fProofOfStake)
1202         {
1203             prevoutStake = block.vtx[1].vin[0].prevout;
1204             nStakeTime = block.vtx[1].nTime;
1205         }
1206         else
1207         {
1208             prevoutStake.SetNull();
1209             nStakeTime = 0;
1210         }
1211
1212         nVersion       = block.nVersion;
1213         hashMerkleRoot = block.hashMerkleRoot;
1214         nTime          = block.nTime;
1215         nBits          = block.nBits;
1216         nNonce         = block.nNonce;
1217     }
1218
1219     CBlock GetBlockHeader() const
1220     {
1221         CBlock block;
1222         block.nVersion       = nVersion;
1223         if (pprev)
1224             block.hashPrevBlock = pprev->GetBlockHash();
1225         block.hashMerkleRoot = hashMerkleRoot;
1226         block.nTime          = nTime;
1227         block.nBits          = nBits;
1228         block.nNonce         = nNonce;
1229         return block;
1230     }
1231
1232     uint256 GetBlockHash() const
1233     {
1234         return *phashBlock;
1235     }
1236
1237     int64 GetBlockTime() const
1238     {
1239         return (int64)nTime;
1240     }
1241
1242     CBigNum GetBlockTrust() const
1243     {
1244         CBigNum bnTarget;
1245         bnTarget.SetCompact(nBits);
1246         if (bnTarget <= 0)
1247             return 0;
1248         return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1249     }
1250
1251     bool IsInMainChain() const
1252     {
1253         return (pnext || this == pindexBest);
1254     }
1255
1256     bool CheckIndex() const
1257     {
1258         return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1259     }
1260
1261     bool EraseBlockFromDisk()
1262     {
1263         // Open history file
1264         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1265         if (!fileout)
1266             return false;
1267
1268         // Overwrite with empty null block
1269         CBlock block;
1270         block.SetNull();
1271         fileout << block;
1272
1273         return true;
1274     }
1275
1276     enum { nMedianTimeSpan=11 };
1277
1278     int64 GetMedianTimePast() const
1279     {
1280         int64 pmedian[nMedianTimeSpan];
1281         int64* pbegin = &pmedian[nMedianTimeSpan];
1282         int64* pend = &pmedian[nMedianTimeSpan];
1283
1284         const CBlockIndex* pindex = this;
1285         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1286             *(--pbegin) = pindex->GetBlockTime();
1287
1288         std::sort(pbegin, pend);
1289         return pbegin[(pend - pbegin)/2];
1290     }
1291
1292     int64 GetMedianTime() const
1293     {
1294         const CBlockIndex* pindex = this;
1295         for (int i = 0; i < nMedianTimeSpan/2; i++)
1296         {
1297             if (!pindex->pnext)
1298                 return GetBlockTime();
1299             pindex = pindex->pnext;
1300         }
1301         return pindex->GetMedianTimePast();
1302     }
1303
1304     bool IsProofOfWork() const
1305     {
1306         return !fProofOfStake;
1307     }
1308
1309     bool IsProofOfStake() const
1310     {
1311         return fProofOfStake;
1312     }
1313
1314     std::string ToString() const
1315     {
1316         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)",
1317             pprev, pnext, nFile, nBlockPos, nHeight,
1318             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1319             fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1320             hashMerkleRoot.ToString().substr(0,10).c_str(),
1321             GetBlockHash().ToString().substr(0,20).c_str());
1322     }
1323
1324     void print() const
1325     {
1326         printf("%s\n", ToString().c_str());
1327     }
1328 };
1329
1330
1331
1332 /** Used to marshal pointers into hashes for db storage. */
1333 class CDiskBlockIndex : public CBlockIndex
1334 {
1335 public:
1336     uint256 hashPrev;
1337     uint256 hashNext;
1338
1339     CDiskBlockIndex()
1340     {
1341         hashPrev = 0;
1342         hashNext = 0;
1343     }
1344
1345     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1346     {
1347         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1348         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1349     }
1350
1351     IMPLEMENT_SERIALIZE
1352     (
1353         if (!(nType & SER_GETHASH))
1354             READWRITE(nVersion);
1355
1356         READWRITE(hashNext);
1357         READWRITE(nFile);
1358         READWRITE(nBlockPos);
1359         READWRITE(nHeight);
1360         READWRITE(nMint);
1361         READWRITE(nMoneySupply);
1362         READWRITE(fProofOfStake);
1363         if (fProofOfStake)
1364         {
1365             READWRITE(prevoutStake);
1366             READWRITE(nStakeTime);
1367         }
1368         else if (fRead)
1369         {
1370             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1371             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1372         }
1373
1374         // block header
1375         READWRITE(this->nVersion);
1376         READWRITE(hashPrev);
1377         READWRITE(hashMerkleRoot);
1378         READWRITE(nTime);
1379         READWRITE(nBits);
1380         READWRITE(nNonce);
1381     )
1382
1383     uint256 GetBlockHash() const
1384     {
1385         CBlock block;
1386         block.nVersion        = nVersion;
1387         block.hashPrevBlock   = hashPrev;
1388         block.hashMerkleRoot  = hashMerkleRoot;
1389         block.nTime           = nTime;
1390         block.nBits           = nBits;
1391         block.nNonce          = nNonce;
1392         return block.GetHash();
1393     }
1394
1395
1396     std::string ToString() const
1397     {
1398         std::string str = "CDiskBlockIndex(";
1399         str += CBlockIndex::ToString();
1400         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1401             GetBlockHash().ToString().c_str(),
1402             hashPrev.ToString().substr(0,20).c_str(),
1403             hashNext.ToString().substr(0,20).c_str());
1404         return str;
1405     }
1406
1407     void print() const
1408     {
1409         printf("%s\n", ToString().c_str());
1410     }
1411 };
1412
1413
1414
1415
1416
1417
1418
1419
1420 /** Describes a place in the block chain to another node such that if the
1421  * other node doesn't have the same branch, it can find a recent common trunk.
1422  * The further back it is, the further before the fork it may be.
1423  */
1424 class CBlockLocator
1425 {
1426 protected:
1427     std::vector<uint256> vHave;
1428 public:
1429
1430     CBlockLocator()
1431     {
1432     }
1433
1434     explicit CBlockLocator(const CBlockIndex* pindex)
1435     {
1436         Set(pindex);
1437     }
1438
1439     explicit CBlockLocator(uint256 hashBlock)
1440     {
1441         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1442         if (mi != mapBlockIndex.end())
1443             Set((*mi).second);
1444     }
1445
1446     CBlockLocator(const std::vector<uint256>& vHaveIn)
1447     {
1448         vHave = vHaveIn;
1449     }
1450
1451     IMPLEMENT_SERIALIZE
1452     (
1453         if (!(nType & SER_GETHASH))
1454             READWRITE(nVersion);
1455         READWRITE(vHave);
1456     )
1457
1458     void SetNull()
1459     {
1460         vHave.clear();
1461     }
1462
1463     bool IsNull()
1464     {
1465         return vHave.empty();
1466     }
1467
1468     void Set(const CBlockIndex* pindex)
1469     {
1470         vHave.clear();
1471         int nStep = 1;
1472         while (pindex)
1473         {
1474             vHave.push_back(pindex->GetBlockHash());
1475
1476             // Exponentially larger steps back
1477             for (int i = 0; pindex && i < nStep; i++)
1478                 pindex = pindex->pprev;
1479             if (vHave.size() > 10)
1480                 nStep *= 2;
1481         }
1482         vHave.push_back(hashGenesisBlock);
1483     }
1484
1485     int GetDistanceBack()
1486     {
1487         // Retrace how far back it was in the sender's branch
1488         int nDistance = 0;
1489         int nStep = 1;
1490         BOOST_FOREACH(const uint256& hash, vHave)
1491         {
1492             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1493             if (mi != mapBlockIndex.end())
1494             {
1495                 CBlockIndex* pindex = (*mi).second;
1496                 if (pindex->IsInMainChain())
1497                     return nDistance;
1498             }
1499             nDistance += nStep;
1500             if (nDistance > 10)
1501                 nStep *= 2;
1502         }
1503         return nDistance;
1504     }
1505
1506     CBlockIndex* GetBlockIndex()
1507     {
1508         // Find the first block the caller has in the main chain
1509         BOOST_FOREACH(const uint256& hash, vHave)
1510         {
1511             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1512             if (mi != mapBlockIndex.end())
1513             {
1514                 CBlockIndex* pindex = (*mi).second;
1515                 if (pindex->IsInMainChain())
1516                     return pindex;
1517             }
1518         }
1519         return pindexGenesisBlock;
1520     }
1521
1522     uint256 GetBlockHash()
1523     {
1524         // Find the first block the caller has in the main chain
1525         BOOST_FOREACH(const uint256& hash, vHave)
1526         {
1527             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1528             if (mi != mapBlockIndex.end())
1529             {
1530                 CBlockIndex* pindex = (*mi).second;
1531                 if (pindex->IsInMainChain())
1532                     return hash;
1533             }
1534         }
1535         return hashGenesisBlock;
1536     }
1537
1538     int GetHeight()
1539     {
1540         CBlockIndex* pindex = GetBlockIndex();
1541         if (!pindex)
1542             return 0;
1543         return pindex->nHeight;
1544     }
1545 };
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555 /** Alerts are for notifying old versions if they become too obsolete and
1556  * need to upgrade.  The message is displayed in the status bar.
1557  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1558  * not read the entire buffer if the alert is for a newer version, but older
1559  * versions can still relay the original data.
1560  */
1561 class CUnsignedAlert
1562 {
1563 public:
1564     int nVersion;
1565     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1566     int64 nExpiration;
1567     int nID;
1568     int nCancel;
1569     std::set<int> setCancel;
1570     int nMinVer;            // lowest version inclusive
1571     int nMaxVer;            // highest version inclusive
1572     std::set<std::string> setSubVer;  // empty matches all
1573     int nPriority;
1574
1575     // Actions
1576     std::string strComment;
1577     std::string strStatusBar;
1578     std::string strReserved;
1579
1580     IMPLEMENT_SERIALIZE
1581     (
1582         READWRITE(this->nVersion);
1583         nVersion = this->nVersion;
1584         READWRITE(nRelayUntil);
1585         READWRITE(nExpiration);
1586         READWRITE(nID);
1587         READWRITE(nCancel);
1588         READWRITE(setCancel);
1589         READWRITE(nMinVer);
1590         READWRITE(nMaxVer);
1591         READWRITE(setSubVer);
1592         READWRITE(nPriority);
1593
1594         READWRITE(strComment);
1595         READWRITE(strStatusBar);
1596         READWRITE(strReserved);
1597     )
1598
1599     void SetNull()
1600     {
1601         nVersion = 1;
1602         nRelayUntil = 0;
1603         nExpiration = 0;
1604         nID = 0;
1605         nCancel = 0;
1606         setCancel.clear();
1607         nMinVer = 0;
1608         nMaxVer = 0;
1609         setSubVer.clear();
1610         nPriority = 0;
1611
1612         strComment.clear();
1613         strStatusBar.clear();
1614         strReserved.clear();
1615     }
1616
1617     std::string ToString() const
1618     {
1619         std::string strSetCancel;
1620         BOOST_FOREACH(int n, setCancel)
1621             strSetCancel += strprintf("%d ", n);
1622         std::string strSetSubVer;
1623         BOOST_FOREACH(std::string str, setSubVer)
1624             strSetSubVer += "\"" + str + "\" ";
1625         return strprintf(
1626                 "CAlert(\n"
1627                 "    nVersion     = %d\n"
1628                 "    nRelayUntil  = %"PRI64d"\n"
1629                 "    nExpiration  = %"PRI64d"\n"
1630                 "    nID          = %d\n"
1631                 "    nCancel      = %d\n"
1632                 "    setCancel    = %s\n"
1633                 "    nMinVer      = %d\n"
1634                 "    nMaxVer      = %d\n"
1635                 "    setSubVer    = %s\n"
1636                 "    nPriority    = %d\n"
1637                 "    strComment   = \"%s\"\n"
1638                 "    strStatusBar = \"%s\"\n"
1639                 ")\n",
1640             nVersion,
1641             nRelayUntil,
1642             nExpiration,
1643             nID,
1644             nCancel,
1645             strSetCancel.c_str(),
1646             nMinVer,
1647             nMaxVer,
1648             strSetSubVer.c_str(),
1649             nPriority,
1650             strComment.c_str(),
1651             strStatusBar.c_str());
1652     }
1653
1654     void print() const
1655     {
1656         printf("%s", ToString().c_str());
1657     }
1658 };
1659
1660 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1661 class CAlert : public CUnsignedAlert
1662 {
1663 public:
1664     std::vector<unsigned char> vchMsg;
1665     std::vector<unsigned char> vchSig;
1666
1667     CAlert()
1668     {
1669         SetNull();
1670     }
1671
1672     IMPLEMENT_SERIALIZE
1673     (
1674         READWRITE(vchMsg);
1675         READWRITE(vchSig);
1676     )
1677
1678     void SetNull()
1679     {
1680         CUnsignedAlert::SetNull();
1681         vchMsg.clear();
1682         vchSig.clear();
1683     }
1684
1685     bool IsNull() const
1686     {
1687         return (nExpiration == 0);
1688     }
1689
1690     uint256 GetHash() const
1691     {
1692         return SerializeHash(*this);
1693     }
1694
1695     bool IsInEffect() const
1696     {
1697         return (GetAdjustedTime() < nExpiration);
1698     }
1699
1700     bool Cancels(const CAlert& alert) const
1701     {
1702         if (!IsInEffect())
1703             return false; // this was a no-op before 31403
1704         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1705     }
1706
1707     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1708     {
1709         // TODO: rework for client-version-embedded-in-strSubVer ?
1710         return (IsInEffect() &&
1711                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1712                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1713     }
1714
1715     bool AppliesToMe() const
1716     {
1717         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1718     }
1719
1720     bool RelayTo(CNode* pnode) const
1721     {
1722         if (!IsInEffect())
1723             return false;
1724         // returns true if wasn't already contained in the set
1725         if (pnode->setKnown.insert(GetHash()).second)
1726         {
1727             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1728                 AppliesToMe() ||
1729                 GetAdjustedTime() < nRelayUntil)
1730             {
1731                 pnode->PushMessage("alert", *this);
1732                 return true;
1733             }
1734         }
1735         return false;
1736     }
1737
1738     bool CheckSignature()
1739     {
1740         CKey key;
1741         if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1742             return error("CAlert::CheckSignature() : SetPubKey failed");
1743         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1744             return error("CAlert::CheckSignature() : verify signature failed");
1745
1746         // Now unserialize the data
1747         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1748         sMsg >> *(CUnsignedAlert*)this;
1749         return true;
1750     }
1751
1752     bool ProcessAlert();
1753 };
1754
1755 class CTxMemPool
1756 {
1757 public:
1758     mutable CCriticalSection cs;
1759     std::map<uint256, CTransaction> mapTx;
1760     std::map<COutPoint, CInPoint> mapNextTx;
1761
1762     bool accept(CTxDB& txdb, CTransaction &tx,
1763                 bool fCheckInputs, bool* pfMissingInputs);
1764     bool addUnchecked(CTransaction &tx);
1765     bool remove(CTransaction &tx);
1766
1767     unsigned long size()
1768     {
1769         LOCK(cs);
1770         return mapTx.size();
1771     }
1772
1773     bool exists(uint256 hash)
1774     {
1775         return (mapTx.count(hash) != 0);
1776     }
1777
1778     CTransaction& lookup(uint256 hash)
1779     {
1780         return mapTx[hash];
1781     }
1782 };
1783
1784 extern CTxMemPool mempool;
1785
1786 #endif