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