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