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