594bdbdbd6fa34a9a97b3be68fef887061541220
[novacoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_MAIN_H
6 #define BITCOIN_MAIN_H
7
8 #include <algorithm>
9
10 #include "timestamps.h"
11 #include "bignum.h"
12 #include "sync.h"
13 #include "net.h"
14 #include "script.h"
15 #include "scrypt.h"
16 #include "ui_interface.h"
17
18 #include <limits>
19 #include <list>
20 #include <map>
21
22 using namespace std;
23
24 class CWallet;
25 class CBlock;
26 class CBlockIndex;
27 class CKeyItem;
28 class CReserveKey;
29 class COutPoint;
30
31 class CAddress;
32 class CInv;
33 class CRequestTracker;
34 class CNode;
35
36 //
37 // Global state
38 //
39
40 static const unsigned int MAX_BLOCK_SIZE = 1000000;
41 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
42 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
43 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
44 static const unsigned int MAX_INV_SZ = 50000;
45
46 static const int64_t MIN_TX_FEE = CENT/10;
47 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
48
49 static const int64_t MAX_MONEY = numeric_limits<int64_t>::max();
50 static const int64_t MAX_MINT_PROOF_OF_WORK = 100 * COIN;
51 static const int64_t MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
52 static const int64_t MIN_TXOUT_AMOUNT = CENT/100;
53
54
55 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
56 inline bool MoneyRange(CBigNum nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
57 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
58 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
59 // Maximum number of script-checking threads allowed
60 static const int MAX_SCRIPTCHECK_THREADS = 16;
61
62 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
63 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
64
65 inline int64_t PastDrift(int64_t nTime)   { return nTime - 2 * nOneHour; } // up to 2 hours from the past
66 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
67
68 extern CScript COINBASE_FLAGS;
69 extern CCriticalSection cs_main;
70 extern map<uint256, CBlockIndex*> mapBlockIndex;
71 extern set<pair<COutPoint, unsigned int> > setStakeSeen;
72 extern CBlockIndex* pindexGenesisBlock;
73 extern unsigned int nNodeLifespan;
74 extern unsigned int nStakeMinAge;
75 extern int nCoinbaseMaturity;
76 extern int nBestHeight;
77 extern uint256 nBestChainTrust;
78 extern uint256 nBestInvalidTrust;
79 extern uint256 hashBestChain;
80 extern CBlockIndex* pindexBest;
81 extern unsigned int nTransactionsUpdated;
82 extern uint64_t nLastBlockTx;
83 extern uint64_t nLastBlockSize;
84 extern uint32_t nLastCoinStakeSearchInterval;
85 extern const string strMessageMagic;
86 extern int64_t nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern set<CWallet*> setpwalletRegistered;
89 extern uint32_t nNetworkID;
90 extern map<uint256, CBlock*> mapOrphanBlocks;
91
92 // Settings
93 extern int64_t nTransactionFee;
94 extern int64_t nMinimumInputValue;
95 extern bool fUseFastIndex;
96 extern int nScriptCheckThreads;
97 extern const uint256 entropyStore[38];
98
99 // Minimum disk space required - used in CheckDiskSpace()
100 static const uint64_t nMinDiskSpace = 52428800;
101
102 class CReserveKey;
103 class CTxDB;
104 class CTxIndex;
105 class CScriptCheck;
106
107 void RegisterWallet(CWallet* pwalletIn);
108 void UnregisterWallet(CWallet* pwalletIn);
109 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
110 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
111 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
112 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
113 FILE* AppendBlockFile(unsigned int& nFileRet);
114
115 void UnloadBlockIndex();
116 bool LoadBlockIndex(bool fAllowNew=true);
117 void PrintBlockTree();
118 CBlockIndex* FindBlockByHeight(int nHeight);
119 bool ProcessMessages(CNode* pfrom);
120 bool SendMessages(CNode* pto);
121 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface);
122
123 // Run an instance of the script checking thread
124 void ThreadScriptCheck(void* parg);
125 // Stop the script checking threads
126 void ThreadScriptCheckQuit();
127
128 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
129 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
130 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees=0);
131 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
132 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
133 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
134 int GetNumBlocksOfPeers();
135 bool IsInitialBlockDownload();
136 string GetWarnings(string strFor);
137 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
138 uint256 WantedByOrphan(const CBlock* pblockOrphan);
139 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
140 void ResendWalletTransactions(bool fForceResend=false);
141
142 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType);
143
144
145
146
147 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut);
148
149 // Position on disk for a particular transaction.
150 class CDiskTxPos
151 {
152 public:
153     uint32_t nFile;
154     uint32_t nBlockPos;
155     uint32_t nTxPos;
156
157     CDiskTxPos() { SetNull(); }
158     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) : nFile(nFileIn), nBlockPos(nBlockPosIn), nTxPos(nTxPosIn) {}
159
160     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
161     void SetNull() { nFile = numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
162     bool IsNull() const { return (nFile == numeric_limits<uint32_t>::max()); }
163
164     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
165     {
166         return (a.nFile     == b.nFile &&
167                 a.nBlockPos == b.nBlockPos &&
168                 a.nTxPos    == b.nTxPos);
169     }
170
171     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
172     {
173         return !(a == b);
174     }
175
176
177     string ToString() const
178     {
179         if (IsNull())
180             return "null";
181         else
182             return strprintf("(nFile=%" PRIu32 ", nBlockPos=%" PRIu32 ", nTxPos=%" PRIu32 ")", nFile, nBlockPos, nTxPos);
183     }
184
185     void print() const
186     {
187         printf("%s", ToString().c_str());
188     }
189 };
190
191
192
193 // An inpoint - a combination of a transaction and an index n into its vin
194 class CInPoint
195 {
196 public:
197     CTransaction* ptx;
198     uint32_t n;
199
200     CInPoint() { SetNull(); }
201     CInPoint(CTransaction* ptxIn, uint32_t nIn) : ptx(ptxIn), n(nIn) {}
202     void SetNull() { ptx = NULL; n = numeric_limits<uint32_t>::max(); }
203     bool IsNull() const { return (ptx == NULL && n == numeric_limits<uint32_t>::max()); }
204 };
205
206
207
208 // An outpoint - a combination of a transaction hash and an index n into its vout
209 class COutPoint
210 {
211 public:
212     uint256 hash;
213     uint32_t n;
214
215     COutPoint() { SetNull(); }
216     COutPoint(uint256 hashIn, uint32_t nIn) : hash(hashIn), n(nIn) {}
217     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
218     void SetNull() { hash = 0; n = numeric_limits<uint32_t>::max(); }
219     bool IsNull() const { return (hash == 0 && n == numeric_limits<uint32_t>::max()); }
220
221     friend bool operator<(const COutPoint& a, const COutPoint& b)
222     {
223         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
224     }
225
226     friend bool operator==(const COutPoint& a, const COutPoint& b)
227     {
228         return (a.hash == b.hash && a.n == b.n);
229     }
230
231     friend bool operator!=(const COutPoint& a, const COutPoint& b)
232     {
233         return !(a == b);
234     }
235
236     string ToString() const
237     {
238         return strprintf("COutPoint(%s, %" PRIu32 ")", hash.ToString().substr(0,10).c_str(), n);
239     }
240
241     void print() const
242     {
243         printf("%s\n", ToString().c_str());
244     }
245 };
246
247
248
249 // An input of a transaction.  It contains the location of the previous
250 // transaction's output that it claims and a signature that matches the
251 // output's public key.
252 //
253 class CTxIn
254 {
255 public:
256     COutPoint prevout;
257     CScript scriptSig;
258     uint32_t nSequence;
259
260     CTxIn() : nSequence(numeric_limits<unsigned int>::max()) {}
261     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=numeric_limits<unsigned int>::max())
262             : prevout(prevoutIn), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
263     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=numeric_limits<unsigned int>::max())
264             : prevout(COutPoint(hashPrevTx, nOut)), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
265
266     IMPLEMENT_SERIALIZE
267     (
268         READWRITE(prevout);
269         READWRITE(scriptSig);
270         READWRITE(nSequence);
271     )
272
273     bool IsFinal() const
274     {
275         return (nSequence == numeric_limits<unsigned int>::max());
276     }
277
278     friend bool operator==(const CTxIn& a, const CTxIn& b)
279     {
280         return (a.prevout   == b.prevout &&
281                 a.scriptSig == b.scriptSig &&
282                 a.nSequence == b.nSequence);
283     }
284
285     friend bool operator!=(const CTxIn& a, const CTxIn& b)
286     {
287         return !(a == b);
288     }
289
290     string ToStringShort() const
291     {
292         return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
293     }
294
295     string ToString() const;
296
297     void print() const
298     {
299         printf("%s\n", ToString().c_str());
300     }
301 };
302
303
304
305 // An output of a transaction.  It contains the public key that the next input
306 // must be able to sign with to claim it.
307 //
308 class CTxOut
309 {
310 public:
311     int64_t nValue;
312     CScript scriptPubKey;
313
314     CTxOut() { SetNull(); }
315     CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) : nValue(nValueIn), scriptPubKey(scriptPubKeyIn) {}
316
317     IMPLEMENT_SERIALIZE
318     (
319         READWRITE(nValue);
320         READWRITE(scriptPubKey);
321     )
322
323     void SetNull()
324     {
325         nValue = -1;
326         scriptPubKey.clear();
327     }
328
329     bool IsNull()
330     {
331         return (nValue == -1);
332     }
333
334     void SetEmpty()
335     {
336         nValue = 0;
337         scriptPubKey.clear();
338     }
339
340     bool IsEmpty() const
341     {
342         return (nValue == 0 && scriptPubKey.empty());
343     }
344
345     uint256 GetHash() const
346     {
347         return SerializeHash(*this);
348     }
349
350     friend bool operator==(const CTxOut& a, const CTxOut& b)
351     {
352         return (a.nValue       == b.nValue &&
353                 a.scriptPubKey == b.scriptPubKey);
354     }
355
356     friend bool operator!=(const CTxOut& a, const CTxOut& b)
357     {
358         return !(a == b);
359     }
360
361     string ToStringShort() const
362     {
363         return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
364     }
365
366     string ToString() const
367     {
368         if (IsEmpty()) return "CTxOut(empty)";
369         if (scriptPubKey.size() < 6)
370             return "CTxOut(error)";
371         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
372     }
373
374     void print() const
375     {
376         printf("%s\n", ToString().c_str());
377     }
378 };
379
380
381
382
383 enum GetMinFee_mode
384 {
385     GMF_BLOCK,
386     GMF_RELAY,
387     GMF_SEND
388 };
389
390 typedef map<uint256, pair<CTxIndex, CTransaction> > MapPrevTx;
391
392 /** The basic transaction that is broadcasted on the network and contained in
393  * blocks.  A transaction can contain multiple inputs and outputs.
394  */
395 class CTransaction
396 {
397 public:
398     static const int CURRENT_VERSION=1;
399     int nVersion;
400     uint32_t nTime;
401     vector<CTxIn> vin;
402     vector<CTxOut> vout;
403     uint32_t nLockTime;
404
405     // Denial-of-service detection:
406     mutable int nDoS;
407     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
408
409     CTransaction()
410     {
411         SetNull();
412     }
413
414     IMPLEMENT_SERIALIZE
415     (
416         READWRITE(this->nVersion);
417         nVersion = this->nVersion;
418         READWRITE(nTime);
419         READWRITE(vin);
420         READWRITE(vout);
421         READWRITE(nLockTime);
422     )
423
424     void SetNull()
425     {
426         nVersion = CTransaction::CURRENT_VERSION;
427         nTime = (uint32_t) GetAdjustedTime();
428         vin.clear();
429         vout.clear();
430         nLockTime = 0;
431         nDoS = 0;  // Denial-of-service prevention
432     }
433
434     bool IsNull() const
435     {
436         return (vin.empty() && vout.empty());
437     }
438
439     uint256 GetHash() const
440     {
441         return SerializeHash(*this);
442     }
443
444     bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const;
445     bool IsNewerThan(const CTransaction& old) const;
446
447     bool IsCoinBase() const
448     {
449         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
450     }
451
452     bool IsCoinStake() const
453     {
454         // ppcoin: the coin stake transaction is marked with the first output empty
455         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
456     }
457
458     /** Check for standard transaction types
459         @return True if all outputs (scriptPubKeys) use only standard transaction forms
460     */
461     bool IsStandard(string& strReason) const;
462     bool IsStandard() const
463     {
464         string strReason;
465         return IsStandard(strReason);
466     }
467
468     /** Check for standard transaction types
469         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
470         @return True if all inputs (scriptSigs) use only standard transaction forms
471         @see CTransaction::FetchInputs
472     */
473     bool AreInputsStandard(const MapPrevTx& mapInputs) const;
474
475     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
476         @return number of sigops this transaction's outputs will produce when spent
477         @see CTransaction::FetchInputs
478     */
479     unsigned int GetLegacySigOpCount() const;
480
481     /** Count ECDSA signature operations in pay-to-script-hash inputs.
482
483         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
484         @return maximum number of sigops required to validate this transaction's inputs
485         @see CTransaction::FetchInputs
486      */
487     unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
488
489     /** Amount of bitcoins spent by this transaction.
490         @return sum of all outputs (note: does not include fees)
491      */
492     int64_t GetValueOut() const;
493
494     /** Amount of bitcoins coming in to this transaction
495         Note that lightweight clients may not know anything besides the hash of previous transactions,
496         so may not be able to calculate this.
497
498         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
499         @return Sum of value of all inputs (scriptSigs)
500         @see CTransaction::FetchInputs
501      */
502     int64_t GetValueIn(const MapPrevTx& mapInputs) const;
503
504     static bool AllowFree(double dPriority)
505     {
506         // Large (in bytes) low-priority (new, small-coin) transactions
507         // need a fee.
508         return dPriority > COIN * 144 / 250;
509     }
510
511     int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
512
513     friend bool operator==(const CTransaction& a, const CTransaction& b)
514     {
515         return (a.nVersion  == b.nVersion &&
516                 a.nTime     == b.nTime &&
517                 a.vin       == b.vin &&
518                 a.vout      == b.vout &&
519                 a.nLockTime == b.nLockTime);
520     }
521
522     friend bool operator!=(const CTransaction& a, const CTransaction& b)
523     {
524         return !(a == b);
525     }
526
527     string ToStringShort() const;
528     string ToString() const;
529
530     void print() const
531     {
532         printf("%s", ToString().c_str());
533     }
534
535     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL);
536     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
537     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
538     bool ReadFromDisk(COutPoint prevout);
539     bool DisconnectInputs(CTxDB& txdb);
540
541     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
542
543      @param[in] txdb    Transaction database
544      @param[in] mapTestPool     List of pending changes to the transaction index database
545      @param[in] fBlock  True if being called to add a new best-block to the chain
546      @param[in] fMiner  True if being called by CreateNewBlock
547      @param[out] inputsRet      Pointers to this transaction's inputs
548      @param[out] fInvalid       returns true if transaction is invalid
549      @return    Returns true if all inputs are in txdb or mapTestPool
550      */
551     bool FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
552                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
553
554     /** Sanity check previous transactions, then, if all checks succeed,
555         mark them as spent by this transaction.
556
557         @param[in] inputs       Previous transactions (from FetchInputs)
558         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
559         @param[in] posThisTx    Position of this transaction on disk
560         @param[in] pindexBlock
561         @param[in] fBlock       true if called from ConnectBlock
562         @param[in] fMiner       true if called from CreateNewBlock
563         @param[in] fScriptChecks        enable scripts validation?
564         @param[in] flags        STRICT_FLAGS script validation flags
565         @param[in] pvChecks     NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
566         @return Returns true if all checks succeed
567      */
568     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, 
569                      bool fBlock, bool fMiner, bool fScriptChecks=true, 
570                      unsigned int flags=STRICT_FLAGS, vector<CScriptCheck> *pvChecks = NULL);
571     bool ClientConnectInputs();
572     bool CheckTransaction() const;
573     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
574     bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const;  // ppcoin: get transaction coin age
575
576 protected:
577     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
578 };
579
580
581
582
583 /** A transaction with a merkle branch linking it to the block chain. */
584 class CMerkleTx : public CTransaction
585 {
586 public:
587     uint256 hashBlock;
588     vector<uint256> vMerkleBranch;
589     int32_t nIndex;
590
591     // memory only
592     mutable bool fMerkleVerified;
593
594
595     CMerkleTx()
596     {
597         Init();
598     }
599
600     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
601     {
602         Init();
603     }
604
605     void Init()
606     {
607         hashBlock = 0;
608         nIndex = -1;
609         fMerkleVerified = false;
610     }
611
612
613     IMPLEMENT_SERIALIZE
614     (
615         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
616         nVersion = this->nVersion;
617         READWRITE(hashBlock);
618         READWRITE(vMerkleBranch);
619         READWRITE(nIndex);
620     )
621
622
623     int SetMerkleBranch(const CBlock* pblock=NULL);
624     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
625     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
626     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
627     int GetBlocksToMaturity() const;
628     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
629     bool AcceptToMemoryPool();
630 };
631
632
633
634
635 /**  A txdb record that contains the disk location of a transaction and the
636  * locations of transactions that spend its outputs.  vSpent is really only
637  * used as a flag, but having the location is very helpful for debugging.
638  */
639 class CTxIndex
640 {
641 public:
642     CDiskTxPos pos;
643     vector<CDiskTxPos> vSpent;
644
645     CTxIndex()
646     {
647         SetNull();
648     }
649
650     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
651     {
652         pos = posIn;
653         vSpent.resize(nOutputs);
654     }
655
656     IMPLEMENT_SERIALIZE
657     (
658         if (!(nType & SER_GETHASH))
659             READWRITE(nVersion);
660         READWRITE(pos);
661         READWRITE(vSpent);
662     )
663
664     void SetNull()
665     {
666         pos.SetNull();
667         vSpent.clear();
668     }
669
670     bool IsNull()
671     {
672         return pos.IsNull();
673     }
674
675     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
676     {
677         return (a.pos    == b.pos &&
678                 a.vSpent == b.vSpent);
679     }
680
681     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
682     {
683         return !(a == b);
684     }
685     int GetDepthInMainChain() const;
686
687 };
688
689
690 /** Nodes collect new transactions into a block, hash them into a hash tree,
691  * and scan through nonce values to make the block's hash satisfy proof-of-work
692  * requirements.  When they solve the proof-of-work, they broadcast the block
693  * to everyone and the block is added to the block chain.  The first transaction
694  * in the block is a special one that creates a new coin owned by the creator
695  * of the block.
696  *
697  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
698  * is indexed by CBlockIndex objects in memory.
699  */
700 class CBlock
701 {
702 public:
703     // header
704     static const int CURRENT_VERSION=6;
705     int32_t nVersion;
706     uint256 hashPrevBlock;
707     uint256 hashMerkleRoot;
708     uint32_t nTime;
709     uint32_t nBits;
710     uint32_t nNonce;
711
712     // network and disk
713     vector<CTransaction> vtx;
714
715     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
716     vector<unsigned char> vchBlockSig;
717
718     // memory only
719     mutable vector<uint256> vMerkleTree;
720
721     // Denial-of-service detection:
722     mutable int nDoS;
723     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
724
725     CBlock()
726     {
727         SetNull();
728     }
729
730     IMPLEMENT_SERIALIZE
731     (
732         READWRITE(this->nVersion);
733         nVersion = this->nVersion;
734         READWRITE(hashPrevBlock);
735         READWRITE(hashMerkleRoot);
736         READWRITE(nTime);
737         READWRITE(nBits);
738         READWRITE(nNonce);
739
740         // ConnectBlock depends on vtx following header to generate CDiskTxPos
741         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
742         {
743             READWRITE(vtx);
744             READWRITE(vchBlockSig);
745         }
746         else if (fRead)
747         {
748             const_cast<CBlock*>(this)->vtx.clear();
749             const_cast<CBlock*>(this)->vchBlockSig.clear();
750         }
751     )
752
753     void SetNull()
754     {
755         nVersion = CBlock::CURRENT_VERSION;
756         hashPrevBlock = 0;
757         hashMerkleRoot = 0;
758         nTime = 0;
759         nBits = 0;
760         nNonce = 0;
761         vtx.clear();
762         vchBlockSig.clear();
763         vMerkleTree.clear();
764         nDoS = 0;
765     }
766
767     bool IsNull() const
768     {
769         return (nBits == 0);
770     }
771
772     uint256 GetHash() const
773     {
774         return scrypt_blockhash((const uint8_t*)&nVersion);
775     }
776
777     int64_t GetBlockTime() const
778     {
779         return (int64_t)nTime;
780     }
781
782     void UpdateTime(const CBlockIndex* pindexPrev);
783
784     // ppcoin: entropy bit for stake modifier if chosen by modifier
785     unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
786
787     // ppcoin: two types of block: proof-of-work or proof-of-stake
788     bool IsProofOfStake() const
789     {
790         return (vtx.size() > 1 && vtx[1].IsCoinStake());
791     }
792
793     bool IsProofOfWork() const
794     {
795         return !IsProofOfStake();
796     }
797
798     pair<COutPoint, unsigned int> GetProofOfStake() const
799     {
800         if (IsProofOfStake())
801             return { vtx[1].vin[0].prevout, vtx[1].nTime };
802         return { COutPoint(), (unsigned int)0 };
803     }
804
805     // ppcoin: get max transaction timestamp
806     int64_t GetMaxTransactionTime() const;
807     uint256 BuildMerkleTree() const;
808     vector<uint256> GetMerkleBranch(int nIndex) const;
809     static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex);
810     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet);
811     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true);
812     void print() const;
813     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
814     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
815     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
816     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
817     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
818     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
819     bool AcceptBlock();
820     bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
821     bool CheckBlockSignature() const;
822
823 private:
824     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
825 };
826
827
828
829
830
831
832 /** The block chain is a tree shaped structure starting with the
833  * genesis block at the root, with each block potentially having multiple
834  * candidates to be the next block.  pprev and pnext link a path through the
835  * main/longest chain.  A blockindex may have multiple pprev pointing back
836  * to it, but pnext will only point forward to the longest branch, or will
837  * be null if the block is not part of the longest chain.
838  */
839 class CBlockIndex
840 {
841 public:
842     const uint256* phashBlock;
843     CBlockIndex* pprev;
844     CBlockIndex* pnext;
845     uint32_t nFile;
846     uint32_t nBlockPos;
847     uint256 nChainTrust; // ppcoin: trust score of block chain
848     int32_t nHeight;
849
850     int64_t nMint;
851     int64_t nMoneySupply;
852
853     uint32_t nFlags;  // ppcoin: block index flags
854     enum  
855     {
856         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
857         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
858         BLOCK_STAKE_MODIFIER = (1 << 2)  // regenerated stake modifier
859     };
860
861     uint64_t nStakeModifier; // hash modifier for proof-of-stake
862     uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
863
864     // proof-of-stake specific fields
865     COutPoint prevoutStake;
866     uint32_t nStakeTime;
867     uint256 hashProofOfStake;
868
869     // block header
870     int32_t  nVersion;
871     uint256  hashMerkleRoot;
872     uint32_t nTime;
873     uint32_t nBits;
874     uint32_t nNonce;
875
876     CBlockIndex()
877     {
878         phashBlock = NULL;
879         pprev = NULL;
880         pnext = NULL;
881         nFile = 0;
882         nBlockPos = 0;
883         nHeight = 0;
884         nChainTrust = 0;
885         nMint = 0;
886         nMoneySupply = 0;
887         nFlags = 0;
888         nStakeModifier = 0;
889         nStakeModifierChecksum = 0;
890         hashProofOfStake = 0;
891         prevoutStake.SetNull();
892         nStakeTime = 0;
893
894         nVersion       = 0;
895         hashMerkleRoot = 0;
896         nTime          = 0;
897         nBits          = 0;
898         nNonce         = 0;
899     }
900
901     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
902     {
903         phashBlock = NULL;
904         pprev = NULL;
905         pnext = NULL;
906         nFile = nFileIn;
907         nBlockPos = nBlockPosIn;
908         nHeight = 0;
909         nChainTrust = 0;
910         nMint = 0;
911         nMoneySupply = 0;
912         nFlags = 0;
913         nStakeModifier = 0;
914         nStakeModifierChecksum = 0;
915         hashProofOfStake = 0;
916         if (block.IsProofOfStake())
917         {
918             SetProofOfStake();
919             prevoutStake = block.vtx[1].vin[0].prevout;
920             nStakeTime = block.vtx[1].nTime;
921         }
922         else
923         {
924             prevoutStake.SetNull();
925             nStakeTime = 0;
926         }
927
928         nVersion       = block.nVersion;
929         hashMerkleRoot = block.hashMerkleRoot;
930         nTime          = block.nTime;
931         nBits          = block.nBits;
932         nNonce         = block.nNonce;
933     }
934
935     CBlock GetBlockHeader() const;
936
937     uint256 GetBlockHash() const
938     {
939         return *phashBlock;
940     }
941
942     int64_t GetBlockTime() const
943     {
944         return (int64_t)nTime;
945     }
946
947     uint256 GetBlockTrust() const;
948
949     bool IsInMainChain() const
950     {
951         return (pnext || this == pindexBest);
952     }
953
954     bool CheckIndex() const
955     {
956         return true;
957     }
958
959     int64_t GetMedianTimePast() const;
960     int64_t GetMedianTime() const;
961
962     /**
963      * Returns true if there are nRequired or more blocks of minVersion or above
964      * in the last nToCheck blocks, starting at pstart and going backwards.
965      */
966     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
967                                 unsigned int nRequired, unsigned int nToCheck);
968
969
970     bool IsProofOfWork() const
971     {
972         return !(nFlags & BLOCK_PROOF_OF_STAKE);
973     }
974
975     bool IsProofOfStake() const
976     {
977         return (nFlags & BLOCK_PROOF_OF_STAKE);
978     }
979
980     void SetProofOfStake()
981     {
982         nFlags |= BLOCK_PROOF_OF_STAKE;
983     }
984
985     unsigned int GetStakeEntropyBit() const
986     {
987         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
988     }
989
990     bool SetStakeEntropyBit(unsigned int nEntropyBit);
991
992     bool GeneratedStakeModifier() const
993     {
994         return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
995     }
996
997     void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
998     string ToString() const;
999
1000     void print() const
1001     {
1002         printf("%s\n", ToString().c_str());
1003     }
1004 };
1005
1006
1007
1008 // Used to marshal pointers into hashes for db storage.
1009 class CDiskBlockIndex : public CBlockIndex
1010 {
1011 private:
1012     uint256 blockHash;
1013
1014 public:
1015     uint256 hashPrev;
1016     uint256 hashNext;
1017
1018     CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1019     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1020     {
1021         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1022         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1023     }
1024
1025     IMPLEMENT_SERIALIZE
1026     (
1027         if (!(nType & SER_GETHASH))
1028             READWRITE(nVersion);
1029
1030         READWRITE(hashNext);
1031         READWRITE(nFile);
1032         READWRITE(nBlockPos);
1033         READWRITE(nHeight);
1034         READWRITE(nMint);
1035         READWRITE(nMoneySupply);
1036         READWRITE(nFlags);
1037         READWRITE(nStakeModifier);
1038         if (IsProofOfStake())
1039         {
1040             READWRITE(prevoutStake);
1041             READWRITE(nStakeTime);
1042             READWRITE(hashProofOfStake);
1043         }
1044         else if (fRead)
1045         {
1046             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1047             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1048             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1049         }
1050
1051         // block header
1052         READWRITE(this->nVersion);
1053         READWRITE(hashPrev);
1054         READWRITE(hashMerkleRoot);
1055         READWRITE(nTime);
1056         READWRITE(nBits);
1057         READWRITE(nNonce);
1058         READWRITE(blockHash);
1059     )
1060
1061     uint256 GetBlockHash() const;
1062     string ToString() const;
1063
1064     void print() const
1065     {
1066         printf("%s\n", ToString().c_str());
1067     }
1068 };
1069
1070
1071
1072 // Describes a place in the block chain to another node such that if the
1073 // other node doesn't have the same branch, it can find a recent common trunk.
1074 // The further back it is, the further before the fork it may be.
1075 //
1076 class CBlockLocator
1077 {
1078 protected:
1079     vector<uint256> vHave;
1080 public:
1081
1082     CBlockLocator() { }
1083     CBlockLocator(const vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1084
1085     explicit CBlockLocator(const CBlockIndex* pindex)
1086     {
1087         Set(pindex);
1088     }
1089
1090     explicit CBlockLocator(uint256 hashBlock)
1091     {
1092         auto mi = mapBlockIndex.find(hashBlock);
1093         if (mi != mapBlockIndex.end())
1094             Set((*mi).second);
1095     }
1096
1097     IMPLEMENT_SERIALIZE
1098     (
1099         if (!(nType & SER_GETHASH))
1100             READWRITE(nVersion);
1101         READWRITE(vHave);
1102     )
1103
1104     void SetNull()
1105     {
1106         vHave.clear();
1107     }
1108
1109     bool IsNull()
1110     {
1111         return vHave.empty();
1112     }
1113
1114     void Set(const CBlockIndex* pindex);
1115     int GetDistanceBack();
1116     CBlockIndex* GetBlockIndex();
1117     uint256 GetBlockHash();
1118     int GetHeight();
1119 };
1120
1121
1122
1123 class CTxMemPool
1124 {
1125 public:
1126     mutable CCriticalSection cs;
1127     map<uint256, CTransaction> mapTx;
1128     map<COutPoint, CInPoint> mapNextTx;
1129
1130     bool accept(CTxDB& txdb, CTransaction &tx,
1131                 bool fCheckInputs, bool* pfMissingInputs);
1132     bool addUnchecked(const uint256& hash, CTransaction &tx);
1133     bool remove(CTransaction &tx);
1134     void clear();
1135     void queryHashes(vector<uint256>& vtxid);
1136
1137     size_t size()
1138     {
1139         LOCK(cs);
1140         return mapTx.size();
1141     }
1142
1143     bool exists(const uint256 &hash)
1144     {
1145         return (mapTx.count(hash) != 0);
1146     }
1147
1148     CTransaction& lookup(const uint256 &hash)
1149     {
1150         return mapTx[hash];
1151     }
1152 };
1153
1154 extern CTxMemPool mempool;
1155
1156 #endif