PPCoin: Switch main chain protocol to score with proof-of-stake difficulty
[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     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         bnChainTrust = 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         bnChainTrust = 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     CBigNum GetBlockTrust() const
1215     {
1216         CBigNum bnTarget;
1217         bnTarget.SetCompact(nBits);
1218         if (bnTarget <= 0)
1219             return 0;
1220         return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1221     }
1222
1223     bool IsInMainChain() const
1224     {
1225         return (pnext || this == pindexBest);
1226     }
1227
1228     bool CheckIndex() const
1229     {
1230         return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1231     }
1232
1233     bool EraseBlockFromDisk()
1234     {
1235         // Open history file
1236         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1237         if (!fileout)
1238             return false;
1239
1240         // Overwrite with empty null block
1241         CBlock block;
1242         block.SetNull();
1243         fileout << block;
1244
1245         return true;
1246     }
1247
1248     enum { nMedianTimeSpan=11 };
1249
1250     int64 GetMedianTimePast() const
1251     {
1252         int64 pmedian[nMedianTimeSpan];
1253         int64* pbegin = &pmedian[nMedianTimeSpan];
1254         int64* pend = &pmedian[nMedianTimeSpan];
1255
1256         const CBlockIndex* pindex = this;
1257         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1258             *(--pbegin) = pindex->GetBlockTime();
1259
1260         std::sort(pbegin, pend);
1261         return pbegin[(pend - pbegin)/2];
1262     }
1263
1264     int64 GetMedianTime() const
1265     {
1266         const CBlockIndex* pindex = this;
1267         for (int i = 0; i < nMedianTimeSpan/2; i++)
1268         {
1269             if (!pindex->pnext)
1270                 return GetBlockTime();
1271             pindex = pindex->pnext;
1272         }
1273         return pindex->GetMedianTimePast();
1274     }
1275
1276     bool IsProofOfWork() const
1277     {
1278         return !fProofOfStake;
1279     }
1280
1281     bool IsProofOfStake() const
1282     {
1283         return fProofOfStake;
1284     }
1285
1286     std::string ToString() const
1287     {
1288         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1289             pprev, pnext, nFile, nBlockPos, nHeight,
1290             fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1291             hashMerkleRoot.ToString().substr(0,10).c_str(),
1292             GetBlockHash().ToString().substr(0,20).c_str());
1293     }
1294
1295     void print() const
1296     {
1297         printf("%s\n", ToString().c_str());
1298     }
1299 };
1300
1301
1302
1303 /** Used to marshal pointers into hashes for db storage. */
1304 class CDiskBlockIndex : public CBlockIndex
1305 {
1306 public:
1307     uint256 hashPrev;
1308     uint256 hashNext;
1309
1310     CDiskBlockIndex()
1311     {
1312         hashPrev = 0;
1313         hashNext = 0;
1314     }
1315
1316     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1317     {
1318         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1319         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1320     }
1321
1322     IMPLEMENT_SERIALIZE
1323     (
1324         if (!(nType & SER_GETHASH))
1325             READWRITE(nVersion);
1326
1327         READWRITE(hashNext);
1328         READWRITE(nFile);
1329         READWRITE(nBlockPos);
1330         READWRITE(nHeight);
1331         READWRITE(fProofOfStake);
1332         if (fProofOfStake)
1333         {
1334             READWRITE(prevoutStake);
1335             READWRITE(nStakeTime);
1336         }
1337         else if (fRead)
1338         {
1339             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1340             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1341         }
1342
1343         // block header
1344         READWRITE(this->nVersion);
1345         READWRITE(hashPrev);
1346         READWRITE(hashMerkleRoot);
1347         READWRITE(nTime);
1348         READWRITE(nBits);
1349         READWRITE(nNonce);
1350     )
1351
1352     uint256 GetBlockHash() const
1353     {
1354         CBlock block;
1355         block.nVersion        = nVersion;
1356         block.hashPrevBlock   = hashPrev;
1357         block.hashMerkleRoot  = hashMerkleRoot;
1358         block.nTime           = nTime;
1359         block.nBits           = nBits;
1360         block.nNonce          = nNonce;
1361         return block.GetHash();
1362     }
1363
1364
1365     std::string ToString() const
1366     {
1367         std::string str = "CDiskBlockIndex(";
1368         str += CBlockIndex::ToString();
1369         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1370             GetBlockHash().ToString().c_str(),
1371             hashPrev.ToString().substr(0,20).c_str(),
1372             hashNext.ToString().substr(0,20).c_str());
1373         return str;
1374     }
1375
1376     void print() const
1377     {
1378         printf("%s\n", ToString().c_str());
1379     }
1380 };
1381
1382
1383
1384
1385
1386
1387
1388
1389 /** Describes a place in the block chain to another node such that if the
1390  * other node doesn't have the same branch, it can find a recent common trunk.
1391  * The further back it is, the further before the fork it may be.
1392  */
1393 class CBlockLocator
1394 {
1395 protected:
1396     std::vector<uint256> vHave;
1397 public:
1398
1399     CBlockLocator()
1400     {
1401     }
1402
1403     explicit CBlockLocator(const CBlockIndex* pindex)
1404     {
1405         Set(pindex);
1406     }
1407
1408     explicit CBlockLocator(uint256 hashBlock)
1409     {
1410         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1411         if (mi != mapBlockIndex.end())
1412             Set((*mi).second);
1413     }
1414
1415     CBlockLocator(const std::vector<uint256>& vHaveIn)
1416     {
1417         vHave = vHaveIn;
1418     }
1419
1420     IMPLEMENT_SERIALIZE
1421     (
1422         if (!(nType & SER_GETHASH))
1423             READWRITE(nVersion);
1424         READWRITE(vHave);
1425     )
1426
1427     void SetNull()
1428     {
1429         vHave.clear();
1430     }
1431
1432     bool IsNull()
1433     {
1434         return vHave.empty();
1435     }
1436
1437     void Set(const CBlockIndex* pindex)
1438     {
1439         vHave.clear();
1440         int nStep = 1;
1441         while (pindex)
1442         {
1443             vHave.push_back(pindex->GetBlockHash());
1444
1445             // Exponentially larger steps back
1446             for (int i = 0; pindex && i < nStep; i++)
1447                 pindex = pindex->pprev;
1448             if (vHave.size() > 10)
1449                 nStep *= 2;
1450         }
1451         vHave.push_back(hashGenesisBlock);
1452     }
1453
1454     int GetDistanceBack()
1455     {
1456         // Retrace how far back it was in the sender's branch
1457         int nDistance = 0;
1458         int nStep = 1;
1459         BOOST_FOREACH(const uint256& hash, vHave)
1460         {
1461             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1462             if (mi != mapBlockIndex.end())
1463             {
1464                 CBlockIndex* pindex = (*mi).second;
1465                 if (pindex->IsInMainChain())
1466                     return nDistance;
1467             }
1468             nDistance += nStep;
1469             if (nDistance > 10)
1470                 nStep *= 2;
1471         }
1472         return nDistance;
1473     }
1474
1475     CBlockIndex* GetBlockIndex()
1476     {
1477         // Find the first block the caller has in the main chain
1478         BOOST_FOREACH(const uint256& hash, vHave)
1479         {
1480             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1481             if (mi != mapBlockIndex.end())
1482             {
1483                 CBlockIndex* pindex = (*mi).second;
1484                 if (pindex->IsInMainChain())
1485                     return pindex;
1486             }
1487         }
1488         return pindexGenesisBlock;
1489     }
1490
1491     uint256 GetBlockHash()
1492     {
1493         // Find the first block the caller has in the main chain
1494         BOOST_FOREACH(const uint256& hash, vHave)
1495         {
1496             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1497             if (mi != mapBlockIndex.end())
1498             {
1499                 CBlockIndex* pindex = (*mi).second;
1500                 if (pindex->IsInMainChain())
1501                     return hash;
1502             }
1503         }
1504         return hashGenesisBlock;
1505     }
1506
1507     int GetHeight()
1508     {
1509         CBlockIndex* pindex = GetBlockIndex();
1510         if (!pindex)
1511             return 0;
1512         return pindex->nHeight;
1513     }
1514 };
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524 /** Alerts are for notifying old versions if they become too obsolete and
1525  * need to upgrade.  The message is displayed in the status bar.
1526  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1527  * not read the entire buffer if the alert is for a newer version, but older
1528  * versions can still relay the original data.
1529  */
1530 class CUnsignedAlert
1531 {
1532 public:
1533     int nVersion;
1534     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1535     int64 nExpiration;
1536     int nID;
1537     int nCancel;
1538     std::set<int> setCancel;
1539     int nMinVer;            // lowest version inclusive
1540     int nMaxVer;            // highest version inclusive
1541     std::set<std::string> setSubVer;  // empty matches all
1542     int nPriority;
1543
1544     // Actions
1545     std::string strComment;
1546     std::string strStatusBar;
1547     std::string strReserved;
1548
1549     IMPLEMENT_SERIALIZE
1550     (
1551         READWRITE(this->nVersion);
1552         nVersion = this->nVersion;
1553         READWRITE(nRelayUntil);
1554         READWRITE(nExpiration);
1555         READWRITE(nID);
1556         READWRITE(nCancel);
1557         READWRITE(setCancel);
1558         READWRITE(nMinVer);
1559         READWRITE(nMaxVer);
1560         READWRITE(setSubVer);
1561         READWRITE(nPriority);
1562
1563         READWRITE(strComment);
1564         READWRITE(strStatusBar);
1565         READWRITE(strReserved);
1566     )
1567
1568     void SetNull()
1569     {
1570         nVersion = 1;
1571         nRelayUntil = 0;
1572         nExpiration = 0;
1573         nID = 0;
1574         nCancel = 0;
1575         setCancel.clear();
1576         nMinVer = 0;
1577         nMaxVer = 0;
1578         setSubVer.clear();
1579         nPriority = 0;
1580
1581         strComment.clear();
1582         strStatusBar.clear();
1583         strReserved.clear();
1584     }
1585
1586     std::string ToString() const
1587     {
1588         std::string strSetCancel;
1589         BOOST_FOREACH(int n, setCancel)
1590             strSetCancel += strprintf("%d ", n);
1591         std::string strSetSubVer;
1592         BOOST_FOREACH(std::string str, setSubVer)
1593             strSetSubVer += "\"" + str + "\" ";
1594         return strprintf(
1595                 "CAlert(\n"
1596                 "    nVersion     = %d\n"
1597                 "    nRelayUntil  = %"PRI64d"\n"
1598                 "    nExpiration  = %"PRI64d"\n"
1599                 "    nID          = %d\n"
1600                 "    nCancel      = %d\n"
1601                 "    setCancel    = %s\n"
1602                 "    nMinVer      = %d\n"
1603                 "    nMaxVer      = %d\n"
1604                 "    setSubVer    = %s\n"
1605                 "    nPriority    = %d\n"
1606                 "    strComment   = \"%s\"\n"
1607                 "    strStatusBar = \"%s\"\n"
1608                 ")\n",
1609             nVersion,
1610             nRelayUntil,
1611             nExpiration,
1612             nID,
1613             nCancel,
1614             strSetCancel.c_str(),
1615             nMinVer,
1616             nMaxVer,
1617             strSetSubVer.c_str(),
1618             nPriority,
1619             strComment.c_str(),
1620             strStatusBar.c_str());
1621     }
1622
1623     void print() const
1624     {
1625         printf("%s", ToString().c_str());
1626     }
1627 };
1628
1629 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1630 class CAlert : public CUnsignedAlert
1631 {
1632 public:
1633     std::vector<unsigned char> vchMsg;
1634     std::vector<unsigned char> vchSig;
1635
1636     CAlert()
1637     {
1638         SetNull();
1639     }
1640
1641     IMPLEMENT_SERIALIZE
1642     (
1643         READWRITE(vchMsg);
1644         READWRITE(vchSig);
1645     )
1646
1647     void SetNull()
1648     {
1649         CUnsignedAlert::SetNull();
1650         vchMsg.clear();
1651         vchSig.clear();
1652     }
1653
1654     bool IsNull() const
1655     {
1656         return (nExpiration == 0);
1657     }
1658
1659     uint256 GetHash() const
1660     {
1661         return SerializeHash(*this);
1662     }
1663
1664     bool IsInEffect() const
1665     {
1666         return (GetAdjustedTime() < nExpiration);
1667     }
1668
1669     bool Cancels(const CAlert& alert) const
1670     {
1671         if (!IsInEffect())
1672             return false; // this was a no-op before 31403
1673         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1674     }
1675
1676     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1677     {
1678         // TODO: rework for client-version-embedded-in-strSubVer ?
1679         return (IsInEffect() &&
1680                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1681                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1682     }
1683
1684     bool AppliesToMe() const
1685     {
1686         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1687     }
1688
1689     bool RelayTo(CNode* pnode) const
1690     {
1691         if (!IsInEffect())
1692             return false;
1693         // returns true if wasn't already contained in the set
1694         if (pnode->setKnown.insert(GetHash()).second)
1695         {
1696             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1697                 AppliesToMe() ||
1698                 GetAdjustedTime() < nRelayUntil)
1699             {
1700                 pnode->PushMessage("alert", *this);
1701                 return true;
1702             }
1703         }
1704         return false;
1705     }
1706
1707     bool CheckSignature()
1708     {
1709         CKey key;
1710         if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1711             return error("CAlert::CheckSignature() : SetPubKey failed");
1712         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1713             return error("CAlert::CheckSignature() : verify signature failed");
1714
1715         // Now unserialize the data
1716         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1717         sMsg >> *(CUnsignedAlert*)this;
1718         return true;
1719     }
1720
1721     bool ProcessAlert();
1722 };
1723
1724 class CTxMemPool
1725 {
1726 public:
1727     mutable CCriticalSection cs;
1728     std::map<uint256, CTransaction> mapTx;
1729     std::map<COutPoint, CInPoint> mapNextTx;
1730
1731     bool accept(CTxDB& txdb, CTransaction &tx,
1732                 bool fCheckInputs, bool* pfMissingInputs);
1733     bool addUnchecked(CTransaction &tx);
1734     bool remove(CTransaction &tx);
1735
1736     unsigned long size()
1737     {
1738         LOCK(cs);
1739         return mapTx.size();
1740     }
1741
1742     bool exists(uint256 hash)
1743     {
1744         return (mapTx.count(hash) != 0);
1745     }
1746
1747     CTransaction& lookup(uint256 hash)
1748     {
1749         return mapTx[hash];
1750     }
1751 };
1752
1753 extern CTxMemPool mempool;
1754
1755 #endif