a9f72ad508a561b20dcf18501b8c1e0b16768997
[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
438     bool IsCoinBase() const
439     {
440         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
441     }
442
443     bool IsCoinStake() const
444     {
445         // ppcoin: the coin stake transaction is marked with the first output empty
446         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
447     }
448
449     /** Check for standard transaction types
450         @return True if all outputs (scriptPubKeys) use only standard transaction forms
451     */
452     bool IsStandard(std::string& strReason) const;
453     bool IsStandard() const
454     {
455         std::string strReason;
456         return IsStandard(strReason);
457     }
458
459     /** Check for standard transaction types
460         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
461         @return True if all inputs (scriptSigs) use only standard transaction forms
462         @see CTransaction::FetchInputs
463     */
464     bool AreInputsStandard(const MapPrevTx& mapInputs) const;
465
466     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
467         @return number of sigops this transaction's outputs will produce when spent
468         @see CTransaction::FetchInputs
469     */
470     unsigned int GetLegacySigOpCount() const;
471
472     /** Count ECDSA signature operations in pay-to-script-hash inputs.
473
474         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
475         @return maximum number of sigops required to validate this transaction's inputs
476         @see CTransaction::FetchInputs
477      */
478     unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
479
480     /** Amount of bitcoins spent by this transaction.
481         @return sum of all outputs (note: does not include fees)
482      */
483     int64_t GetValueOut() const;
484
485     /** Amount of bitcoins coming in to this transaction
486         Note that lightweight clients may not know anything besides the hash of previous transactions,
487         so may not be able to calculate this.
488
489         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
490         @return Sum of value of all inputs (scriptSigs)
491         @see CTransaction::FetchInputs
492      */
493     int64_t GetValueIn(const MapPrevTx& mapInputs) const;
494
495     static bool AllowFree(double dPriority)
496     {
497         // Large (in bytes) low-priority (new, small-coin) transactions
498         // need a fee.
499         return dPriority > COIN * 144 / 250;
500     }
501
502     int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
503
504     friend bool operator==(const CTransaction& a, const CTransaction& b)
505     {
506         return (a.nVersion  == b.nVersion &&
507                 a.nTime     == b.nTime &&
508                 a.vin       == b.vin &&
509                 a.vout      == b.vout &&
510                 a.nLockTime == b.nLockTime);
511     }
512
513     friend bool operator!=(const CTransaction& a, const CTransaction& b)
514     {
515         return !(a == b);
516     }
517
518     std::string ToStringShort() const;
519     std::string ToString() const;
520
521     void print() const
522     {
523         printf("%s", ToString().c_str());
524     }
525
526     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL);
527     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
528     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
529     bool ReadFromDisk(COutPoint prevout);
530     bool DisconnectInputs(CTxDB& txdb);
531
532     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
533
534      @param[in] txdb    Transaction database
535      @param[in] mapTestPool     List of pending changes to the transaction index database
536      @param[in] fBlock  True if being called to add a new best-block to the chain
537      @param[in] fMiner  True if being called by CreateNewBlock
538      @param[out] inputsRet      Pointers to this transaction's inputs
539      @param[out] fInvalid       returns true if transaction is invalid
540      @return    Returns true if all inputs are in txdb or mapTestPool
541      */
542     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
543                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
544
545     /** Sanity check previous transactions, then, if all checks succeed,
546         mark them as spent by this transaction.
547
548         @param[in] inputs       Previous transactions (from FetchInputs)
549         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
550         @param[in] posThisTx    Position of this transaction on disk
551         @param[in] pindexBlock
552         @param[in] fBlock       true if called from ConnectBlock
553         @param[in] fMiner       true if called from CreateNewBlock
554         @param[in] fScriptChecks        enable scripts validation?
555         @param[in] flags        STRICT_FLAGS script validation flags
556         @param[in] pvChecks     NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
557         @return Returns true if all checks succeed
558      */
559     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, 
560                      bool fBlock, bool fMiner, bool fScriptChecks=true, 
561                      unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
562     bool ClientConnectInputs();
563     bool CheckTransaction() const;
564     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
565     bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const;  // ppcoin: get transaction coin age
566
567 protected:
568     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
569 };
570
571
572
573
574 /** A transaction with a merkle branch linking it to the block chain. */
575 class CMerkleTx : public CTransaction
576 {
577 public:
578     uint256 hashBlock;
579     std::vector<uint256> vMerkleBranch;
580     int32_t nIndex;
581
582     // memory only
583     mutable bool fMerkleVerified;
584
585
586     CMerkleTx()
587     {
588         Init();
589     }
590
591     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
592     {
593         Init();
594     }
595
596     void Init()
597     {
598         hashBlock = 0;
599         nIndex = -1;
600         fMerkleVerified = false;
601     }
602
603
604     IMPLEMENT_SERIALIZE
605     (
606         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
607         nVersion = this->nVersion;
608         READWRITE(hashBlock);
609         READWRITE(vMerkleBranch);
610         READWRITE(nIndex);
611     )
612
613
614     int SetMerkleBranch(const CBlock* pblock=NULL);
615     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
616     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
617     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
618     int GetBlocksToMaturity() const;
619     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
620     bool AcceptToMemoryPool();
621 };
622
623
624
625
626 /**  A txdb record that contains the disk location of a transaction and the
627  * locations of transactions that spend its outputs.  vSpent is really only
628  * used as a flag, but having the location is very helpful for debugging.
629  */
630 class CTxIndex
631 {
632 public:
633     CDiskTxPos pos;
634     std::vector<CDiskTxPos> vSpent;
635
636     CTxIndex()
637     {
638         SetNull();
639     }
640
641     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
642     {
643         pos = posIn;
644         vSpent.resize(nOutputs);
645     }
646
647     IMPLEMENT_SERIALIZE
648     (
649         if (!(nType & SER_GETHASH))
650             READWRITE(nVersion);
651         READWRITE(pos);
652         READWRITE(vSpent);
653     )
654
655     void SetNull()
656     {
657         pos.SetNull();
658         vSpent.clear();
659     }
660
661     bool IsNull()
662     {
663         return pos.IsNull();
664     }
665
666     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
667     {
668         return (a.pos    == b.pos &&
669                 a.vSpent == b.vSpent);
670     }
671
672     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
673     {
674         return !(a == b);
675     }
676     int GetDepthInMainChain() const;
677
678 };
679
680
681 /** Nodes collect new transactions into a block, hash them into a hash tree,
682  * and scan through nonce values to make the block's hash satisfy proof-of-work
683  * requirements.  When they solve the proof-of-work, they broadcast the block
684  * to everyone and the block is added to the block chain.  The first transaction
685  * in the block is a special one that creates a new coin owned by the creator
686  * of the block.
687  *
688  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
689  * is indexed by CBlockIndex objects in memory.
690  */
691 class CBlock
692 {
693 public:
694     // header
695     static const int CURRENT_VERSION=6;
696     int32_t nVersion;
697     uint256 hashPrevBlock;
698     uint256 hashMerkleRoot;
699     uint32_t nTime;
700     uint32_t nBits;
701     uint32_t nNonce;
702
703     // network and disk
704     std::vector<CTransaction> vtx;
705
706     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
707     std::vector<unsigned char> vchBlockSig;
708
709     // memory only
710     mutable std::vector<uint256> vMerkleTree;
711
712     // Denial-of-service detection:
713     mutable int nDoS;
714     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
715
716     CBlock()
717     {
718         SetNull();
719     }
720
721     IMPLEMENT_SERIALIZE
722     (
723         READWRITE(this->nVersion);
724         nVersion = this->nVersion;
725         READWRITE(hashPrevBlock);
726         READWRITE(hashMerkleRoot);
727         READWRITE(nTime);
728         READWRITE(nBits);
729         READWRITE(nNonce);
730
731         // ConnectBlock depends on vtx following header to generate CDiskTxPos
732         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
733         {
734             READWRITE(vtx);
735             READWRITE(vchBlockSig);
736         }
737         else if (fRead)
738         {
739             const_cast<CBlock*>(this)->vtx.clear();
740             const_cast<CBlock*>(this)->vchBlockSig.clear();
741         }
742     )
743
744     void SetNull()
745     {
746         nVersion = CBlock::CURRENT_VERSION;
747         hashPrevBlock = 0;
748         hashMerkleRoot = 0;
749         nTime = 0;
750         nBits = 0;
751         nNonce = 0;
752         vtx.clear();
753         vchBlockSig.clear();
754         vMerkleTree.clear();
755         nDoS = 0;
756     }
757
758     bool IsNull() const
759     {
760         return (nBits == 0);
761     }
762
763     uint256 GetHash() const
764     {
765         return scrypt_blockhash((const uint8_t*)&nVersion);
766     }
767
768     int64_t GetBlockTime() const
769     {
770         return (int64_t)nTime;
771     }
772
773     void UpdateTime(const CBlockIndex* pindexPrev);
774
775     // ppcoin: entropy bit for stake modifier if chosen by modifier
776     unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
777
778     // ppcoin: two types of block: proof-of-work or proof-of-stake
779     bool IsProofOfStake() const
780     {
781         return (vtx.size() > 1 && vtx[1].IsCoinStake());
782     }
783
784     bool IsProofOfWork() const
785     {
786         return !IsProofOfStake();
787     }
788
789     std::pair<COutPoint, unsigned int> GetProofOfStake() const
790     {
791         if (IsProofOfStake())
792             return { vtx[1].vin[0].prevout, vtx[1].nTime };
793         return { COutPoint(), (unsigned int)0 };
794     }
795
796     // ppcoin: get max transaction timestamp
797     int64_t GetMaxTransactionTime() const;
798     uint256 BuildMerkleTree() const;
799     std::vector<uint256> GetMerkleBranch(int nIndex) const;
800     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
801     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet);
802     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true);
803     void print() const;
804     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
805     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
806     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
807     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
808     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
809     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
810     bool AcceptBlock();
811     bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
812     bool CheckBlockSignature() const;
813
814 private:
815     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
816 };
817
818
819
820
821
822
823 /** The block chain is a tree shaped structure starting with the
824  * genesis block at the root, with each block potentially having multiple
825  * candidates to be the next block.  pprev and pnext link a path through the
826  * main/longest chain.  A blockindex may have multiple pprev pointing back
827  * to it, but pnext will only point forward to the longest branch, or will
828  * be null if the block is not part of the longest chain.
829  */
830 class CBlockIndex
831 {
832 public:
833     const uint256* phashBlock;
834     CBlockIndex* pprev;
835     CBlockIndex* pnext;
836     uint32_t nFile;
837     uint32_t nBlockPos;
838     uint256 nChainTrust; // ppcoin: trust score of block chain
839     int32_t nHeight;
840
841     int64_t nMint;
842     int64_t nMoneySupply;
843
844     uint32_t nFlags;  // ppcoin: block index flags
845     enum  
846     {
847         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
848         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
849         BLOCK_STAKE_MODIFIER = (1 << 2)  // regenerated stake modifier
850     };
851
852     uint64_t nStakeModifier; // hash modifier for proof-of-stake
853     uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
854
855     // proof-of-stake specific fields
856     COutPoint prevoutStake;
857     uint32_t nStakeTime;
858     uint256 hashProofOfStake;
859
860     // block header
861     int32_t  nVersion;
862     uint256  hashMerkleRoot;
863     uint32_t nTime;
864     uint32_t nBits;
865     uint32_t nNonce;
866
867     CBlockIndex()
868     {
869         phashBlock = NULL;
870         pprev = NULL;
871         pnext = NULL;
872         nFile = 0;
873         nBlockPos = 0;
874         nHeight = 0;
875         nChainTrust = 0;
876         nMint = 0;
877         nMoneySupply = 0;
878         nFlags = 0;
879         nStakeModifier = 0;
880         nStakeModifierChecksum = 0;
881         hashProofOfStake = 0;
882         prevoutStake.SetNull();
883         nStakeTime = 0;
884
885         nVersion       = 0;
886         hashMerkleRoot = 0;
887         nTime          = 0;
888         nBits          = 0;
889         nNonce         = 0;
890     }
891
892     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
893     {
894         phashBlock = NULL;
895         pprev = NULL;
896         pnext = NULL;
897         nFile = nFileIn;
898         nBlockPos = nBlockPosIn;
899         nHeight = 0;
900         nChainTrust = 0;
901         nMint = 0;
902         nMoneySupply = 0;
903         nFlags = 0;
904         nStakeModifier = 0;
905         nStakeModifierChecksum = 0;
906         hashProofOfStake = 0;
907         if (block.IsProofOfStake())
908         {
909             SetProofOfStake();
910             prevoutStake = block.vtx[1].vin[0].prevout;
911             nStakeTime = block.vtx[1].nTime;
912         }
913         else
914         {
915             prevoutStake.SetNull();
916             nStakeTime = 0;
917         }
918
919         nVersion       = block.nVersion;
920         hashMerkleRoot = block.hashMerkleRoot;
921         nTime          = block.nTime;
922         nBits          = block.nBits;
923         nNonce         = block.nNonce;
924     }
925
926     CBlock GetBlockHeader() const;
927
928     uint256 GetBlockHash() const
929     {
930         return *phashBlock;
931     }
932
933     int64_t GetBlockTime() const
934     {
935         return (int64_t)nTime;
936     }
937
938     uint256 GetBlockTrust() const;
939
940     bool IsInMainChain() const
941     {
942         return (pnext || this == pindexBest);
943     }
944
945     bool CheckIndex() const
946     {
947         return true;
948     }
949
950     int64_t GetMedianTimePast() const;
951     int64_t GetMedianTime() const;
952
953     /**
954      * Returns true if there are nRequired or more blocks of minVersion or above
955      * in the last nToCheck blocks, starting at pstart and going backwards.
956      */
957     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
958                                 unsigned int nRequired, unsigned int nToCheck);
959
960
961     bool IsProofOfWork() const
962     {
963         return !(nFlags & BLOCK_PROOF_OF_STAKE);
964     }
965
966     bool IsProofOfStake() const
967     {
968         return (nFlags & BLOCK_PROOF_OF_STAKE);
969     }
970
971     void SetProofOfStake()
972     {
973         nFlags |= BLOCK_PROOF_OF_STAKE;
974     }
975
976     unsigned int GetStakeEntropyBit() const
977     {
978         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
979     }
980
981     bool SetStakeEntropyBit(unsigned int nEntropyBit);
982
983     bool GeneratedStakeModifier() const
984     {
985         return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
986     }
987
988     void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
989     std::string ToString() const;
990
991     void print() const
992     {
993         printf("%s\n", ToString().c_str());
994     }
995 };
996
997
998
999 // Used to marshal pointers into hashes for db storage.
1000 class CDiskBlockIndex : public CBlockIndex
1001 {
1002 private:
1003     uint256 blockHash;
1004
1005 public:
1006     uint256 hashPrev;
1007     uint256 hashNext;
1008
1009     CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1010     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1011     {
1012         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1013         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1014     }
1015
1016     IMPLEMENT_SERIALIZE
1017     (
1018         if (!(nType & SER_GETHASH))
1019             READWRITE(nVersion);
1020
1021         READWRITE(hashNext);
1022         READWRITE(nFile);
1023         READWRITE(nBlockPos);
1024         READWRITE(nHeight);
1025         READWRITE(nMint);
1026         READWRITE(nMoneySupply);
1027         READWRITE(nFlags);
1028         READWRITE(nStakeModifier);
1029         if (IsProofOfStake())
1030         {
1031             READWRITE(prevoutStake);
1032             READWRITE(nStakeTime);
1033             READWRITE(hashProofOfStake);
1034         }
1035         else if (fRead)
1036         {
1037             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1038             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1039             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1040         }
1041
1042         // block header
1043         READWRITE(this->nVersion);
1044         READWRITE(hashPrev);
1045         READWRITE(hashMerkleRoot);
1046         READWRITE(nTime);
1047         READWRITE(nBits);
1048         READWRITE(nNonce);
1049         READWRITE(blockHash);
1050     )
1051
1052     uint256 GetBlockHash() const;
1053     std::string ToString() const;
1054
1055     void print() const
1056     {
1057         printf("%s\n", ToString().c_str());
1058     }
1059 };
1060
1061
1062
1063 // Describes a place in the block chain to another node such that if the
1064 // other node doesn't have the same branch, it can find a recent common trunk.
1065 // The further back it is, the further before the fork it may be.
1066 //
1067 class CBlockLocator
1068 {
1069 protected:
1070     std::vector<uint256> vHave;
1071 public:
1072
1073     CBlockLocator() { }
1074     CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1075
1076     explicit CBlockLocator(const CBlockIndex* pindex)
1077     {
1078         Set(pindex);
1079     }
1080
1081     explicit CBlockLocator(uint256 hashBlock)
1082     {
1083         auto mi = mapBlockIndex.find(hashBlock);
1084         if (mi != mapBlockIndex.end())
1085             Set((*mi).second);
1086     }
1087
1088     IMPLEMENT_SERIALIZE
1089     (
1090         if (!(nType & SER_GETHASH))
1091             READWRITE(nVersion);
1092         READWRITE(vHave);
1093     )
1094
1095     void SetNull()
1096     {
1097         vHave.clear();
1098     }
1099
1100     bool IsNull()
1101     {
1102         return vHave.empty();
1103     }
1104
1105     void Set(const CBlockIndex* pindex);
1106     int GetDistanceBack();
1107     CBlockIndex* GetBlockIndex();
1108     uint256 GetBlockHash();
1109     int GetHeight();
1110 };
1111
1112
1113
1114 class CTxMemPool
1115 {
1116 public:
1117     mutable CCriticalSection cs;
1118     std::map<uint256, CTransaction> mapTx;
1119     std::map<COutPoint, CInPoint> mapNextTx;
1120
1121     bool accept(CTxDB& txdb, CTransaction &tx,
1122                 bool fCheckInputs, bool* pfMissingInputs);
1123     bool addUnchecked(const uint256& hash, CTransaction &tx);
1124     bool remove(CTransaction &tx);
1125     void clear();
1126     void queryHashes(std::vector<uint256>& vtxid);
1127
1128     size_t size()
1129     {
1130         LOCK(cs);
1131         return mapTx.size();
1132     }
1133
1134     bool exists(const uint256 &hash)
1135     {
1136         return (mapTx.count(hash) != 0);
1137     }
1138
1139     CTransaction& lookup(const uint256 &hash)
1140     {
1141         return mapTx[hash];
1142     }
1143 };
1144
1145 extern CTxMemPool mempool;
1146
1147 #endif