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