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