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.
10 #include "timestamps.h"
16 #include "ui_interface.h"
32 class CRequestTracker;
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;
45 static const int64_t MIN_TX_FEE = CENT/10;
46 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
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;
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;
61 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
62 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
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
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;
91 extern int64_t nTransactionFee;
92 extern int64_t nMinimumInputValue;
93 extern bool fUseFastIndex;
94 extern int nScriptCheckThreads;
95 extern const uint256 entropyStore[38];
97 // Minimum disk space required - used in CheckDiskSpace()
98 static const uint64_t nMinDiskSpace = 52428800;
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);
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);
121 // Run an instance of the script checking thread
122 void ThreadScriptCheck(void* parg);
123 // Stop the script checking threads
124 void ThreadScriptCheckQuit();
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);
140 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType);
145 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
147 // Position on disk for a particular transaction.
155 CDiskTxPos() { SetNull(); }
156 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) : nFile(nFileIn), nBlockPos(nBlockPosIn), nTxPos(nTxPosIn) {}
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()); }
162 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
164 return (a.nFile == b.nFile &&
165 a.nBlockPos == b.nBlockPos &&
166 a.nTxPos == b.nTxPos);
169 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
175 std::string ToString() const
180 return strprintf("(nFile=%" PRIu32 ", nBlockPos=%" PRIu32 ", nTxPos=%" PRIu32 ")", nFile, nBlockPos, nTxPos);
185 printf("%s", ToString().c_str());
191 // An inpoint - a combination of a transaction and an index n into its vin
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()); }
206 // An outpoint - a combination of a transaction hash and an index n into its vout
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()); }
219 friend bool operator<(const COutPoint& a, const COutPoint& b)
221 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
224 friend bool operator==(const COutPoint& a, const COutPoint& b)
226 return (a.hash == b.hash && a.n == b.n);
229 friend bool operator!=(const COutPoint& a, const COutPoint& b)
234 std::string ToString() const
236 return strprintf("COutPoint(%s, %" PRIu32 ")", hash.ToString().substr(0,10).c_str(), n);
241 printf("%s\n", ToString().c_str());
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.
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) {}
267 READWRITE(scriptSig);
268 READWRITE(nSequence);
273 return (nSequence == std::numeric_limits<unsigned int>::max());
276 friend bool operator==(const CTxIn& a, const CTxIn& b)
278 return (a.prevout == b.prevout &&
279 a.scriptSig == b.scriptSig &&
280 a.nSequence == b.nSequence);
283 friend bool operator!=(const CTxIn& a, const CTxIn& b)
288 std::string ToStringShort() const
290 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
293 std::string ToString() const;
297 printf("%s\n", ToString().c_str());
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.
310 CScript scriptPubKey;
312 CTxOut() { SetNull(); }
313 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) : nValue(nValueIn), scriptPubKey(scriptPubKeyIn) {}
318 READWRITE(scriptPubKey);
324 scriptPubKey.clear();
329 return (nValue == -1);
335 scriptPubKey.clear();
340 return (nValue == 0 && scriptPubKey.empty());
343 uint256 GetHash() const
345 return SerializeHash(*this);
348 friend bool operator==(const CTxOut& a, const CTxOut& b)
350 return (a.nValue == b.nValue &&
351 a.scriptPubKey == b.scriptPubKey);
354 friend bool operator!=(const CTxOut& a, const CTxOut& b)
359 std::string ToStringShort() const
361 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
364 std::string ToString() const
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());
374 printf("%s\n", ToString().c_str());
388 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
390 /** The basic transaction that is broadcasted on the network and contained in
391 * blocks. A transaction can contain multiple inputs and outputs.
396 static const int CURRENT_VERSION=1;
399 std::vector<CTxIn> vin;
400 std::vector<CTxOut> vout;
403 // Denial-of-service detection:
405 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
414 READWRITE(this->nVersion);
415 nVersion = this->nVersion;
419 READWRITE(nLockTime);
424 nVersion = CTransaction::CURRENT_VERSION;
425 nTime = (uint32_t) GetAdjustedTime();
429 nDoS = 0; // Denial-of-service prevention
434 return (vin.empty() && vout.empty());
437 uint256 GetHash() const
439 return SerializeHash(*this);
442 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const;
443 bool IsNewerThan(const CTransaction& old) const;
445 bool IsCoinBase() const
447 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
450 bool IsCoinStake() const
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());
456 /** Check for standard transaction types
457 @return True if all outputs (scriptPubKeys) use only standard transaction forms
459 bool IsStandard(std::string& strReason) const;
460 bool IsStandard() const
462 std::string strReason;
463 return IsStandard(strReason);
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
471 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
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
477 unsigned int GetLegacySigOpCount() const;
479 /** Count ECDSA signature operations in pay-to-script-hash inputs.
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
485 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
487 /** Amount of bitcoins spent by this transaction.
488 @return sum of all outputs (note: does not include fees)
490 int64_t GetValueOut() const;
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.
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
500 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
502 static bool AllowFree(double dPriority)
504 // Large (in bytes) low-priority (new, small-coin) transactions
506 return dPriority > COIN * 144 / 250;
509 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
511 friend bool operator==(const CTransaction& a, const CTransaction& b)
513 return (a.nVersion == b.nVersion &&
514 a.nTime == b.nTime &&
517 a.nLockTime == b.nLockTime);
520 friend bool operator!=(const CTransaction& a, const CTransaction& b)
525 std::string ToStringShort() const;
526 std::string ToString() const;
530 printf("%s", ToString().c_str());
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);
539 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
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
549 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
550 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
552 /** Sanity check previous transactions, then, if all checks succeed,
553 mark them as spent by this transaction.
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
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
575 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
581 /** A transaction with a merkle branch linking it to the block chain. */
582 class CMerkleTx : public CTransaction
586 std::vector<uint256> vMerkleBranch;
590 mutable bool fMerkleVerified;
598 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
607 fMerkleVerified = false;
613 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
614 nVersion = this->nVersion;
615 READWRITE(hashBlock);
616 READWRITE(vMerkleBranch);
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();
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.
641 std::vector<CDiskTxPos> vSpent;
648 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
651 vSpent.resize(nOutputs);
656 if (!(nType & SER_GETHASH))
673 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
675 return (a.pos == b.pos &&
676 a.vSpent == b.vSpent);
679 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
683 int GetDepthInMainChain() const;
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
695 * Blocks are appended to blk0001.dat files on disk. Their location on disk
696 * is indexed by CBlockIndex objects in memory.
702 static const int CURRENT_VERSION=6;
704 uint256 hashPrevBlock;
705 uint256 hashMerkleRoot;
711 std::vector<CTransaction> vtx;
713 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
714 std::vector<unsigned char> vchBlockSig;
717 mutable std::vector<uint256> vMerkleTree;
719 // Denial-of-service detection:
721 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
730 READWRITE(this->nVersion);
731 nVersion = this->nVersion;
732 READWRITE(hashPrevBlock);
733 READWRITE(hashMerkleRoot);
738 // ConnectBlock depends on vtx following header to generate CDiskTxPos
739 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
742 READWRITE(vchBlockSig);
746 const_cast<CBlock*>(this)->vtx.clear();
747 const_cast<CBlock*>(this)->vchBlockSig.clear();
753 nVersion = CBlock::CURRENT_VERSION;
770 uint256 GetHash() const
772 return scrypt_blockhash((const uint8_t*)&nVersion);
775 int64_t GetBlockTime() const
777 return (int64_t)nTime;
780 void UpdateTime(const CBlockIndex* pindexPrev);
782 // ppcoin: entropy bit for stake modifier if chosen by modifier
783 unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
785 // ppcoin: two types of block: proof-of-work or proof-of-stake
786 bool IsProofOfStake() const
788 return (vtx.size() > 1 && vtx[1].IsCoinStake());
791 bool IsProofOfWork() const
793 return !IsProofOfStake();
796 std::pair<COutPoint, unsigned int> GetProofOfStake() const
798 if (IsProofOfStake())
799 return { vtx[1].vin[0].prevout, vtx[1].nTime };
800 return { COutPoint(), (unsigned int)0 };
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);
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;
818 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
819 bool CheckBlockSignature() const;
822 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
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.
840 const uint256* phashBlock;
845 uint256 nChainTrust; // ppcoin: trust score of block chain
849 int64_t nMoneySupply;
851 uint32_t nFlags; // ppcoin: block index flags
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
859 uint64_t nStakeModifier; // hash modifier for proof-of-stake
860 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
862 // proof-of-stake specific fields
863 COutPoint prevoutStake;
865 uint256 hashProofOfStake;
869 uint256 hashMerkleRoot;
887 nStakeModifierChecksum = 0;
888 hashProofOfStake = 0;
889 prevoutStake.SetNull();
899 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
905 nBlockPos = nBlockPosIn;
912 nStakeModifierChecksum = 0;
913 hashProofOfStake = 0;
914 if (block.IsProofOfStake())
917 prevoutStake = block.vtx[1].vin[0].prevout;
918 nStakeTime = block.vtx[1].nTime;
922 prevoutStake.SetNull();
926 nVersion = block.nVersion;
927 hashMerkleRoot = block.hashMerkleRoot;
930 nNonce = block.nNonce;
933 CBlock GetBlockHeader() const;
935 uint256 GetBlockHash() const
940 int64_t GetBlockTime() const
942 return (int64_t)nTime;
945 uint256 GetBlockTrust() const;
947 bool IsInMainChain() const
949 return (pnext || this == pindexBest);
952 bool CheckIndex() const
957 int64_t GetMedianTimePast() const;
958 int64_t GetMedianTime() const;
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.
964 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
965 unsigned int nRequired, unsigned int nToCheck);
968 bool IsProofOfWork() const
970 return !(nFlags & BLOCK_PROOF_OF_STAKE);
973 bool IsProofOfStake() const
975 return (nFlags & BLOCK_PROOF_OF_STAKE);
978 void SetProofOfStake()
980 nFlags |= BLOCK_PROOF_OF_STAKE;
983 unsigned int GetStakeEntropyBit() const
985 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
988 bool SetStakeEntropyBit(unsigned int nEntropyBit);
990 bool GeneratedStakeModifier() const
992 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
995 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
996 std::string ToString() const;
1000 printf("%s\n", ToString().c_str());
1006 // Used to marshal pointers into hashes for db storage.
1007 class CDiskBlockIndex : public CBlockIndex
1016 CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1017 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1019 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1020 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1025 if (!(nType & SER_GETHASH))
1026 READWRITE(nVersion);
1028 READWRITE(hashNext);
1030 READWRITE(nBlockPos);
1033 READWRITE(nMoneySupply);
1035 READWRITE(nStakeModifier);
1036 if (IsProofOfStake())
1038 READWRITE(prevoutStake);
1039 READWRITE(nStakeTime);
1040 READWRITE(hashProofOfStake);
1044 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1045 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1046 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1050 READWRITE(this->nVersion);
1051 READWRITE(hashPrev);
1052 READWRITE(hashMerkleRoot);
1056 READWRITE(blockHash);
1059 uint256 GetBlockHash() const;
1060 std::string ToString() const;
1064 printf("%s\n", ToString().c_str());
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.
1077 std::vector<uint256> vHave;
1081 CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1083 explicit CBlockLocator(const CBlockIndex* pindex)
1088 explicit CBlockLocator(uint256 hashBlock)
1090 auto mi = mapBlockIndex.find(hashBlock);
1091 if (mi != mapBlockIndex.end())
1097 if (!(nType & SER_GETHASH))
1098 READWRITE(nVersion);
1109 return vHave.empty();
1112 void Set(const CBlockIndex* pindex);
1113 int GetDistanceBack();
1114 CBlockIndex* GetBlockIndex();
1115 uint256 GetBlockHash();
1124 mutable CCriticalSection cs;
1125 std::map<uint256, CTransaction> mapTx;
1126 std::map<COutPoint, CInPoint> mapNextTx;
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);
1133 void queryHashes(std::vector<uint256>& vtxid);
1138 return mapTx.size();
1141 bool exists(const uint256 &hash)
1143 return (mapTx.count(hash) != 0);
1146 CTransaction& lookup(const uint256 &hash)
1152 extern CTxMemPool mempool;