9a893b4092776a06d70e099d9c5d126d2a7ee5b0
[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 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
40 static const int COINBASE_MATURITY = 100;
41 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
42 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
43 #ifdef USE_UPNP
44 static const int fHaveUPnP = true;
45 #else
46 static const int fHaveUPnP = false;
47 #endif
48
49 static const uint256 hashGenesisBlockOfficial("0x000000007c82d1f0aa2896b01bf533a8cc26a1f44790be4ceb4ecde7bee24add");
50 static const uint256 hashGenesisBlockTestNet("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
51
52 extern CScript COINBASE_FLAGS;
53
54
55
56
57
58
59 extern CCriticalSection cs_main;
60 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
61 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
62 extern uint256 hashGenesisBlock;
63 extern CBlockIndex* pindexGenesisBlock;
64 extern int nBestHeight;
65 extern uint64 nBestChainTrust;
66 extern uint64 nBestInvalidTrust;
67 extern uint256 hashBestChain;
68 extern CBlockIndex* pindexBest;
69 extern unsigned int nTransactionsUpdated;
70 extern uint64 nLastBlockTx;
71 extern uint64 nLastBlockSize;
72 extern const std::string strMessageMagic;
73 extern double dHashesPerSec;
74 extern int64 nHPSTimerStart;
75 extern int64 nTimeBestReceived;
76 extern CCriticalSection cs_setpwalletRegistered;
77 extern std::set<CWallet*> setpwalletRegistered;
78 extern std::map<uint256, CBlock*> mapOrphanBlocks;
79
80 // Settings
81 extern int64 nTransactionFee;
82
83
84
85
86
87 class CReserveKey;
88 class CTxDB;
89 class CTxIndex;
90
91 void RegisterWallet(CWallet* pwalletIn);
92 void UnregisterWallet(CWallet* pwalletIn);
93 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
94 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
95 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
96 FILE* AppendBlockFile(unsigned int& nFileRet);
97 bool LoadBlockIndex(bool fAllowNew=true);
98 void PrintBlockTree();
99 bool ProcessMessages(CNode* pfrom);
100 bool SendMessages(CNode* pto, bool fSendTrickle);
101 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
102 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
103 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
104 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
105 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
106 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
107 int64 GetProofOfStakeReward(int64 nCoinAge);
108 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
109 int GetNumBlocksOfPeers();
110 bool IsInitialBlockDownload();
111 std::string GetWarnings(std::string strFor);
112 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
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     uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1130     int nHeight;
1131     bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1132     COutPoint prevoutStake;
1133     unsigned int nStakeTime;
1134
1135     // block header
1136     int nVersion;
1137     uint256 hashMerkleRoot;
1138     unsigned int nTime;
1139     unsigned int nBits;
1140     unsigned int nNonce;
1141
1142
1143     CBlockIndex()
1144     {
1145         phashBlock = NULL;
1146         pprev = NULL;
1147         pnext = NULL;
1148         nFile = 0;
1149         nBlockPos = 0;
1150         nHeight = 0;
1151         nChainTrust = 0;
1152         fProofOfStake = true;
1153         prevoutStake.SetNull();
1154         nStakeTime = 0;
1155
1156         nVersion       = 0;
1157         hashMerkleRoot = 0;
1158         nTime          = 0;
1159         nBits          = 0;
1160         nNonce         = 0;
1161     }
1162
1163     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1164     {
1165         phashBlock = NULL;
1166         pprev = NULL;
1167         pnext = NULL;
1168         nFile = nFileIn;
1169         nBlockPos = nBlockPosIn;
1170         nHeight = 0;
1171         nChainTrust = 0;
1172         fProofOfStake = block.IsProofOfStake();
1173         if (fProofOfStake)
1174         {
1175             prevoutStake = block.vtx[1].vin[0].prevout;
1176             nStakeTime = block.vtx[1].nTime;
1177         }
1178         else
1179         {
1180             prevoutStake.SetNull();
1181             nStakeTime = 0;
1182         }
1183
1184         nVersion       = block.nVersion;
1185         hashMerkleRoot = block.hashMerkleRoot;
1186         nTime          = block.nTime;
1187         nBits          = block.nBits;
1188         nNonce         = block.nNonce;
1189     }
1190
1191     CBlock GetBlockHeader() const
1192     {
1193         CBlock block;
1194         block.nVersion       = nVersion;
1195         if (pprev)
1196             block.hashPrevBlock = pprev->GetBlockHash();
1197         block.hashMerkleRoot = hashMerkleRoot;
1198         block.nTime          = nTime;
1199         block.nBits          = nBits;
1200         block.nNonce         = nNonce;
1201         return block;
1202     }
1203
1204     uint256 GetBlockHash() const
1205     {
1206         return *phashBlock;
1207     }
1208
1209     int64 GetBlockTime() const
1210     {
1211         return (int64)nTime;
1212     }
1213
1214     int64 GetBlockTrust() const
1215     {
1216         return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1217     }
1218
1219     bool IsInMainChain() const
1220     {
1221         return (pnext || this == pindexBest);
1222     }
1223
1224     bool CheckIndex() const
1225     {
1226         return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1227     }
1228
1229     bool EraseBlockFromDisk()
1230     {
1231         // Open history file
1232         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1233         if (!fileout)
1234             return false;
1235
1236         // Overwrite with empty null block
1237         CBlock block;
1238         block.SetNull();
1239         fileout << block;
1240
1241         return true;
1242     }
1243
1244     enum { nMedianTimeSpan=11 };
1245
1246     int64 GetMedianTimePast() const
1247     {
1248         int64 pmedian[nMedianTimeSpan];
1249         int64* pbegin = &pmedian[nMedianTimeSpan];
1250         int64* pend = &pmedian[nMedianTimeSpan];
1251
1252         const CBlockIndex* pindex = this;
1253         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1254             *(--pbegin) = pindex->GetBlockTime();
1255
1256         std::sort(pbegin, pend);
1257         return pbegin[(pend - pbegin)/2];
1258     }
1259
1260     int64 GetMedianTime() const
1261     {
1262         const CBlockIndex* pindex = this;
1263         for (int i = 0; i < nMedianTimeSpan/2; i++)
1264         {
1265             if (!pindex->pnext)
1266                 return GetBlockTime();
1267             pindex = pindex->pnext;
1268         }
1269         return pindex->GetMedianTimePast();
1270     }
1271
1272     bool IsProofOfWork() const
1273     {
1274         return !fProofOfStake;
1275     }
1276
1277     bool IsProofOfStake() const
1278     {
1279         return fProofOfStake;
1280     }
1281
1282     std::string ToString() const
1283     {
1284         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)",
1285             pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
1286             fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1287             hashMerkleRoot.ToString().substr(0,10).c_str(),
1288             GetBlockHash().ToString().substr(0,20).c_str());
1289     }
1290
1291     void print() const
1292     {
1293         printf("%s\n", ToString().c_str());
1294     }
1295 };
1296
1297
1298
1299 /** Used to marshal pointers into hashes for db storage. */
1300 class CDiskBlockIndex : public CBlockIndex
1301 {
1302 public:
1303     uint256 hashPrev;
1304     uint256 hashNext;
1305
1306     CDiskBlockIndex()
1307     {
1308         hashPrev = 0;
1309         hashNext = 0;
1310     }
1311
1312     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1313     {
1314         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1315         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1316     }
1317
1318     IMPLEMENT_SERIALIZE
1319     (
1320         if (!(nType & SER_GETHASH))
1321             READWRITE(nVersion);
1322
1323         READWRITE(hashNext);
1324         READWRITE(nFile);
1325         READWRITE(nBlockPos);
1326         READWRITE(nChainTrust);
1327         READWRITE(nHeight);
1328         READWRITE(fProofOfStake);
1329         if (fProofOfStake)
1330         {
1331             READWRITE(prevoutStake);
1332             READWRITE(nStakeTime);
1333         }
1334         else if (fRead)
1335         {
1336             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1337             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1338         }
1339
1340         // block header
1341         READWRITE(this->nVersion);
1342         READWRITE(hashPrev);
1343         READWRITE(hashMerkleRoot);
1344         READWRITE(nTime);
1345         READWRITE(nBits);
1346         READWRITE(nNonce);
1347     )
1348
1349     uint256 GetBlockHash() const
1350     {
1351         CBlock block;
1352         block.nVersion        = nVersion;
1353         block.hashPrevBlock   = hashPrev;
1354         block.hashMerkleRoot  = hashMerkleRoot;
1355         block.nTime           = nTime;
1356         block.nBits           = nBits;
1357         block.nNonce          = nNonce;
1358         return block.GetHash();
1359     }
1360
1361
1362     std::string ToString() const
1363     {
1364         std::string str = "CDiskBlockIndex(";
1365         str += CBlockIndex::ToString();
1366         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1367             GetBlockHash().ToString().c_str(),
1368             hashPrev.ToString().substr(0,20).c_str(),
1369             hashNext.ToString().substr(0,20).c_str());
1370         return str;
1371     }
1372
1373     void print() const
1374     {
1375         printf("%s\n", ToString().c_str());
1376     }
1377 };
1378
1379
1380
1381
1382
1383
1384
1385
1386 /** Describes a place in the block chain to another node such that if the
1387  * other node doesn't have the same branch, it can find a recent common trunk.
1388  * The further back it is, the further before the fork it may be.
1389  */
1390 class CBlockLocator
1391 {
1392 protected:
1393     std::vector<uint256> vHave;
1394 public:
1395
1396     CBlockLocator()
1397     {
1398     }
1399
1400     explicit CBlockLocator(const CBlockIndex* pindex)
1401     {
1402         Set(pindex);
1403     }
1404
1405     explicit CBlockLocator(uint256 hashBlock)
1406     {
1407         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1408         if (mi != mapBlockIndex.end())
1409             Set((*mi).second);
1410     }
1411
1412     CBlockLocator(const std::vector<uint256>& vHaveIn)
1413     {
1414         vHave = vHaveIn;
1415     }
1416
1417     IMPLEMENT_SERIALIZE
1418     (
1419         if (!(nType & SER_GETHASH))
1420             READWRITE(nVersion);
1421         READWRITE(vHave);
1422     )
1423
1424     void SetNull()
1425     {
1426         vHave.clear();
1427     }
1428
1429     bool IsNull()
1430     {
1431         return vHave.empty();
1432     }
1433
1434     void Set(const CBlockIndex* pindex)
1435     {
1436         vHave.clear();
1437         int nStep = 1;
1438         while (pindex)
1439         {
1440             vHave.push_back(pindex->GetBlockHash());
1441
1442             // Exponentially larger steps back
1443             for (int i = 0; pindex && i < nStep; i++)
1444                 pindex = pindex->pprev;
1445             if (vHave.size() > 10)
1446                 nStep *= 2;
1447         }
1448         vHave.push_back(hashGenesisBlock);
1449     }
1450
1451     int GetDistanceBack()
1452     {
1453         // Retrace how far back it was in the sender's branch
1454         int nDistance = 0;
1455         int nStep = 1;
1456         BOOST_FOREACH(const uint256& hash, vHave)
1457         {
1458             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1459             if (mi != mapBlockIndex.end())
1460             {
1461                 CBlockIndex* pindex = (*mi).second;
1462                 if (pindex->IsInMainChain())
1463                     return nDistance;
1464             }
1465             nDistance += nStep;
1466             if (nDistance > 10)
1467                 nStep *= 2;
1468         }
1469         return nDistance;
1470     }
1471
1472     CBlockIndex* GetBlockIndex()
1473     {
1474         // Find the first block the caller has in the main chain
1475         BOOST_FOREACH(const uint256& hash, vHave)
1476         {
1477             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1478             if (mi != mapBlockIndex.end())
1479             {
1480                 CBlockIndex* pindex = (*mi).second;
1481                 if (pindex->IsInMainChain())
1482                     return pindex;
1483             }
1484         }
1485         return pindexGenesisBlock;
1486     }
1487
1488     uint256 GetBlockHash()
1489     {
1490         // Find the first block the caller has in the main chain
1491         BOOST_FOREACH(const uint256& hash, vHave)
1492         {
1493             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1494             if (mi != mapBlockIndex.end())
1495             {
1496                 CBlockIndex* pindex = (*mi).second;
1497                 if (pindex->IsInMainChain())
1498                     return hash;
1499             }
1500         }
1501         return hashGenesisBlock;
1502     }
1503
1504     int GetHeight()
1505     {
1506         CBlockIndex* pindex = GetBlockIndex();
1507         if (!pindex)
1508             return 0;
1509         return pindex->nHeight;
1510     }
1511 };
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521 /** Alerts are for notifying old versions if they become too obsolete and
1522  * need to upgrade.  The message is displayed in the status bar.
1523  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1524  * not read the entire buffer if the alert is for a newer version, but older
1525  * versions can still relay the original data.
1526  */
1527 class CUnsignedAlert
1528 {
1529 public:
1530     int nVersion;
1531     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1532     int64 nExpiration;
1533     int nID;
1534     int nCancel;
1535     std::set<int> setCancel;
1536     int nMinVer;            // lowest version inclusive
1537     int nMaxVer;            // highest version inclusive
1538     std::set<std::string> setSubVer;  // empty matches all
1539     int nPriority;
1540
1541     // Actions
1542     std::string strComment;
1543     std::string strStatusBar;
1544     std::string strReserved;
1545
1546     IMPLEMENT_SERIALIZE
1547     (
1548         READWRITE(this->nVersion);
1549         nVersion = this->nVersion;
1550         READWRITE(nRelayUntil);
1551         READWRITE(nExpiration);
1552         READWRITE(nID);
1553         READWRITE(nCancel);
1554         READWRITE(setCancel);
1555         READWRITE(nMinVer);
1556         READWRITE(nMaxVer);
1557         READWRITE(setSubVer);
1558         READWRITE(nPriority);
1559
1560         READWRITE(strComment);
1561         READWRITE(strStatusBar);
1562         READWRITE(strReserved);
1563     )
1564
1565     void SetNull()
1566     {
1567         nVersion = 1;
1568         nRelayUntil = 0;
1569         nExpiration = 0;
1570         nID = 0;
1571         nCancel = 0;
1572         setCancel.clear();
1573         nMinVer = 0;
1574         nMaxVer = 0;
1575         setSubVer.clear();
1576         nPriority = 0;
1577
1578         strComment.clear();
1579         strStatusBar.clear();
1580         strReserved.clear();
1581     }
1582
1583     std::string ToString() const
1584     {
1585         std::string strSetCancel;
1586         BOOST_FOREACH(int n, setCancel)
1587             strSetCancel += strprintf("%d ", n);
1588         std::string strSetSubVer;
1589         BOOST_FOREACH(std::string str, setSubVer)
1590             strSetSubVer += "\"" + str + "\" ";
1591         return strprintf(
1592                 "CAlert(\n"
1593                 "    nVersion     = %d\n"
1594                 "    nRelayUntil  = %"PRI64d"\n"
1595                 "    nExpiration  = %"PRI64d"\n"
1596                 "    nID          = %d\n"
1597                 "    nCancel      = %d\n"
1598                 "    setCancel    = %s\n"
1599                 "    nMinVer      = %d\n"
1600                 "    nMaxVer      = %d\n"
1601                 "    setSubVer    = %s\n"
1602                 "    nPriority    = %d\n"
1603                 "    strComment   = \"%s\"\n"
1604                 "    strStatusBar = \"%s\"\n"
1605                 ")\n",
1606             nVersion,
1607             nRelayUntil,
1608             nExpiration,
1609             nID,
1610             nCancel,
1611             strSetCancel.c_str(),
1612             nMinVer,
1613             nMaxVer,
1614             strSetSubVer.c_str(),
1615             nPriority,
1616             strComment.c_str(),
1617             strStatusBar.c_str());
1618     }
1619
1620     void print() const
1621     {
1622         printf("%s", ToString().c_str());
1623     }
1624 };
1625
1626 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1627 class CAlert : public CUnsignedAlert
1628 {
1629 public:
1630     std::vector<unsigned char> vchMsg;
1631     std::vector<unsigned char> vchSig;
1632
1633     CAlert()
1634     {
1635         SetNull();
1636     }
1637
1638     IMPLEMENT_SERIALIZE
1639     (
1640         READWRITE(vchMsg);
1641         READWRITE(vchSig);
1642     )
1643
1644     void SetNull()
1645     {
1646         CUnsignedAlert::SetNull();
1647         vchMsg.clear();
1648         vchSig.clear();
1649     }
1650
1651     bool IsNull() const
1652     {
1653         return (nExpiration == 0);
1654     }
1655
1656     uint256 GetHash() const
1657     {
1658         return SerializeHash(*this);
1659     }
1660
1661     bool IsInEffect() const
1662     {
1663         return (GetAdjustedTime() < nExpiration);
1664     }
1665
1666     bool Cancels(const CAlert& alert) const
1667     {
1668         if (!IsInEffect())
1669             return false; // this was a no-op before 31403
1670         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1671     }
1672
1673     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1674     {
1675         // TODO: rework for client-version-embedded-in-strSubVer ?
1676         return (IsInEffect() &&
1677                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1678                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1679     }
1680
1681     bool AppliesToMe() const
1682     {
1683         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1684     }
1685
1686     bool RelayTo(CNode* pnode) const
1687     {
1688         if (!IsInEffect())
1689             return false;
1690         // returns true if wasn't already contained in the set
1691         if (pnode->setKnown.insert(GetHash()).second)
1692         {
1693             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1694                 AppliesToMe() ||
1695                 GetAdjustedTime() < nRelayUntil)
1696             {
1697                 pnode->PushMessage("alert", *this);
1698                 return true;
1699             }
1700         }
1701         return false;
1702     }
1703
1704     bool CheckSignature()
1705     {
1706         CKey key;
1707         if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1708             return error("CAlert::CheckSignature() : SetPubKey failed");
1709         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1710             return error("CAlert::CheckSignature() : verify signature failed");
1711
1712         // Now unserialize the data
1713         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1714         sMsg >> *(CUnsignedAlert*)this;
1715         return true;
1716     }
1717
1718     bool ProcessAlert();
1719 };
1720
1721 class CTxMemPool
1722 {
1723 public:
1724     mutable CCriticalSection cs;
1725     std::map<uint256, CTransaction> mapTx;
1726     std::map<COutPoint, CInPoint> mapNextTx;
1727
1728     bool accept(CTxDB& txdb, CTransaction &tx,
1729                 bool fCheckInputs, bool* pfMissingInputs);
1730     bool addUnchecked(CTransaction &tx);
1731     bool remove(CTransaction &tx);
1732
1733     unsigned long size()
1734     {
1735         LOCK(cs);
1736         return mapTx.size();
1737     }
1738
1739     bool exists(uint256 hash)
1740     {
1741         return (mapTx.count(hash) != 0);
1742     }
1743
1744     CTransaction& lookup(uint256 hash)
1745     {
1746         return mapTx[hash];
1747     }
1748 };
1749
1750 extern CTxMemPool mempool;
1751
1752 #endif