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