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