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