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