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