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"
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;
46 static const int64_t MIN_TX_FEE = CENT/10;
47 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
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;
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 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
58 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
59 // Maximum number of script-checking threads allowed
60 static const int MAX_SCRIPTCHECK_THREADS = 16;
62 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
63 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
65 inline int64_t PastDrift(int64_t nTime) { return nTime - 2 * nOneHour; } // up to 2 hours from the past
66 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
68 extern CScript COINBASE_FLAGS;
69 extern CCriticalSection cs_main;
70 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
71 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
72 extern CBlockIndex* pindexGenesisBlock;
73 extern unsigned int nNodeLifespan;
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;
92 extern int64_t nTransactionFee;
93 extern int64_t nMinimumInputValue;
94 extern bool fUseFastIndex;
95 extern int nScriptCheckThreads;
96 extern const uint256 entropyStore[38];
98 // Minimum disk space required - used in CheckDiskSpace()
99 static const uint64_t nMinDiskSpace = 52428800;
101 void RegisterWallet(CWallet* pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn);
103 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
104 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
105 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
106 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
107 FILE* AppendBlockFile(unsigned int& nFileRet);
109 void UnloadBlockIndex();
110 bool LoadBlockIndex(bool fAllowNew=true);
111 void PrintBlockTree();
112 CBlockIndex* FindBlockByHeight(int nHeight);
113 bool ProcessMessages(CNode* pfrom);
114 bool SendMessages(CNode* pto);
115 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface);
117 // Run an instance of the script checking thread
118 void ThreadScriptCheck(void* parg);
119 // Stop the script checking threads
120 void ThreadScriptCheckQuit();
122 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
123 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
124 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees=0);
125 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
126 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
127 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
128 int GetNumBlocksOfPeers();
129 bool IsInitialBlockDownload();
130 std::string GetWarnings(std::string strFor);
131 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
132 uint256 WantedByOrphan(const CBlock* pblockOrphan);
133 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
134 void ResendWalletTransactions(bool fForceResend=false);
136 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType);
141 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
143 // Position on disk for a particular transaction.
151 CDiskTxPos() { SetNull(); }
152 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) : nFile(nFileIn), nBlockPos(nBlockPosIn), nTxPos(nTxPosIn) {}
154 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
155 void SetNull() { nFile = std::numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
156 bool IsNull() const { return (nFile == std::numeric_limits<uint32_t>::max()); }
158 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
160 return (a.nFile == b.nFile &&
161 a.nBlockPos == b.nBlockPos &&
162 a.nTxPos == b.nTxPos);
165 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
171 std::string ToString() const
176 return strprintf("(nFile=%" PRIu32 ", nBlockPos=%" PRIu32 ", nTxPos=%" PRIu32 ")", nFile, nBlockPos, nTxPos);
181 printf("%s", ToString().c_str());
187 // An inpoint - a combination of a transaction and an index n into its vin
194 CInPoint() { SetNull(); }
195 CInPoint(CTransaction* ptxIn, uint32_t nIn) : ptx(ptxIn), n(nIn) {}
196 void SetNull() { ptx = NULL; n = std::numeric_limits<uint32_t>::max(); }
197 bool IsNull() const { return (ptx == NULL && n == std::numeric_limits<uint32_t>::max()); }
202 // An outpoint - a combination of a transaction hash and an index n into its vout
209 COutPoint() { SetNull(); }
210 COutPoint(uint256 hashIn, uint32_t nIn) : hash(hashIn), n(nIn) {}
211 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212 void SetNull() { hash = 0; n = std::numeric_limits<uint32_t>::max(); }
213 bool IsNull() const { return (hash == 0 && n == std::numeric_limits<uint32_t>::max()); }
215 friend bool operator<(const COutPoint& a, const COutPoint& b)
217 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220 friend bool operator==(const COutPoint& a, const COutPoint& b)
222 return (a.hash == b.hash && a.n == b.n);
225 friend bool operator!=(const COutPoint& a, const COutPoint& b)
230 std::string ToString() const
232 return strprintf("COutPoint(%s, %" PRIu32 ")", hash.ToString().substr(0,10).c_str(), n);
237 printf("%s\n", ToString().c_str());
243 // An input of a transaction. It contains the location of the previous
244 // transaction's output that it claims and a signature that matches the
245 // output's public key.
254 CTxIn() : nSequence(std::numeric_limits<unsigned int>::max()) {}
255 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
256 : prevout(prevoutIn), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
257 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
258 : prevout(COutPoint(hashPrevTx, nOut)), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
263 READWRITE(scriptSig);
264 READWRITE(nSequence);
269 return (nSequence == std::numeric_limits<unsigned int>::max());
272 friend bool operator==(const CTxIn& a, const CTxIn& b)
274 return (a.prevout == b.prevout &&
275 a.scriptSig == b.scriptSig &&
276 a.nSequence == b.nSequence);
279 friend bool operator!=(const CTxIn& a, const CTxIn& b)
284 std::string ToStringShort() const
286 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
289 std::string ToString() const;
293 printf("%s\n", ToString().c_str());
299 // An output of a transaction. It contains the public key that the next input
300 // must be able to sign with to claim it.
306 CScript scriptPubKey;
308 CTxOut() { SetNull(); }
309 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) : nValue(nValueIn), scriptPubKey(scriptPubKeyIn) {}
314 READWRITE(scriptPubKey);
320 scriptPubKey.clear();
325 return (nValue == -1);
331 scriptPubKey.clear();
336 return (nValue == 0 && scriptPubKey.empty());
339 uint256 GetHash() const
341 return SerializeHash(*this);
344 friend bool operator==(const CTxOut& a, const CTxOut& b)
346 return (a.nValue == b.nValue &&
347 a.scriptPubKey == b.scriptPubKey);
350 friend bool operator!=(const CTxOut& a, const CTxOut& b)
355 std::string ToStringShort() const
357 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
360 std::string ToString() const
362 if (IsEmpty()) return "CTxOut(empty)";
363 if (scriptPubKey.size() < 6)
364 return "CTxOut(error)";
365 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
370 printf("%s\n", ToString().c_str());
384 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
386 /** The basic transaction that is broadcasted on the network and contained in
387 * blocks. A transaction can contain multiple inputs and outputs.
392 static const int CURRENT_VERSION=1;
395 std::vector<CTxIn> vin;
396 std::vector<CTxOut> vout;
399 // Denial-of-service detection:
401 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
410 READWRITE(this->nVersion);
411 nVersion = this->nVersion;
415 READWRITE(nLockTime);
420 nVersion = CTransaction::CURRENT_VERSION;
421 nTime = (uint32_t) GetAdjustedTime();
425 nDoS = 0; // Denial-of-service prevention
430 return (vin.empty() && vout.empty());
433 uint256 GetHash() const
435 return SerializeHash(*this);
438 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const;
439 bool IsNewerThan(const CTransaction& old) const;
441 bool IsCoinBase() const
443 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
446 bool IsCoinStake() const
448 // ppcoin: the coin stake transaction is marked with the first output empty
449 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
452 /** Check for standard transaction types
453 @return True if all outputs (scriptPubKeys) use only standard transaction forms
455 bool IsStandard(std::string& strReason) const;
456 bool IsStandard() const
458 std::string strReason;
459 return IsStandard(strReason);
462 /** Check for standard transaction types
463 @param[in] mapInputs Map of previous transactions that have outputs we're spending
464 @return True if all inputs (scriptSigs) use only standard transaction forms
465 @see CTransaction::FetchInputs
467 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
469 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
470 @return number of sigops this transaction's outputs will produce when spent
471 @see CTransaction::FetchInputs
473 unsigned int GetLegacySigOpCount() const;
475 /** Count ECDSA signature operations in pay-to-script-hash inputs.
477 @param[in] mapInputs Map of previous transactions that have outputs we're spending
478 @return maximum number of sigops required to validate this transaction's inputs
479 @see CTransaction::FetchInputs
481 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
483 /** Amount of bitcoins spent by this transaction.
484 @return sum of all outputs (note: does not include fees)
486 int64_t GetValueOut() const;
488 /** Amount of bitcoins coming in to this transaction
489 Note that lightweight clients may not know anything besides the hash of previous transactions,
490 so may not be able to calculate this.
492 @param[in] mapInputs Map of previous transactions that have outputs we're spending
493 @return Sum of value of all inputs (scriptSigs)
494 @see CTransaction::FetchInputs
496 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
498 static bool AllowFree(double dPriority)
500 // Large (in bytes) low-priority (new, small-coin) transactions
502 return dPriority > COIN * 144 / 250;
505 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
507 friend bool operator==(const CTransaction& a, const CTransaction& b)
509 return (a.nVersion == b.nVersion &&
510 a.nTime == b.nTime &&
513 a.nLockTime == b.nLockTime);
516 friend bool operator!=(const CTransaction& a, const CTransaction& b)
521 std::string ToStringShort() const;
522 std::string ToString() const;
526 printf("%s", ToString().c_str());
529 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL);
530 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
531 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
532 bool ReadFromDisk(COutPoint prevout);
533 bool DisconnectInputs(CTxDB& txdb);
535 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
537 @param[in] txdb Transaction database
538 @param[in] mapTestPool List of pending changes to the transaction index database
539 @param[in] fBlock True if being called to add a new best-block to the chain
540 @param[in] fMiner True if being called by CreateNewBlock
541 @param[out] inputsRet Pointers to this transaction's inputs
542 @param[out] fInvalid returns true if transaction is invalid
543 @return Returns true if all inputs are in txdb or mapTestPool
545 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
546 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
548 /** Sanity check previous transactions, then, if all checks succeed,
549 mark them as spent by this transaction.
551 @param[in] inputs Previous transactions (from FetchInputs)
552 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
553 @param[in] posThisTx Position of this transaction on disk
554 @param[in] pindexBlock
555 @param[in] fBlock true if called from ConnectBlock
556 @param[in] fMiner true if called from CreateNewBlock
557 @param[in] fScriptChecks enable scripts validation?
558 @param[in] flags STRICT_FLAGS script validation flags
559 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
560 @return Returns true if all checks succeed
562 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
563 bool fBlock, bool fMiner, bool fScriptChecks=true,
564 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
565 bool ClientConnectInputs();
566 bool CheckTransaction() const;
567 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
568 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
571 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
577 /** A transaction with a merkle branch linking it to the block chain. */
578 class CMerkleTx : public CTransaction
582 std::vector<uint256> vMerkleBranch;
586 mutable bool fMerkleVerified;
594 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
603 fMerkleVerified = false;
609 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
610 nVersion = this->nVersion;
611 READWRITE(hashBlock);
612 READWRITE(vMerkleBranch);
617 int SetMerkleBranch(const CBlock* pblock=NULL);
618 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
619 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
620 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
621 int GetBlocksToMaturity() const;
622 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
623 bool AcceptToMemoryPool();
629 /** A txdb record that contains the disk location of a transaction and the
630 * locations of transactions that spend its outputs. vSpent is really only
631 * used as a flag, but having the location is very helpful for debugging.
637 std::vector<CDiskTxPos> vSpent;
644 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
647 vSpent.resize(nOutputs);
652 if (!(nType & SER_GETHASH))
669 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
671 return (a.pos == b.pos &&
672 a.vSpent == b.vSpent);
675 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
679 int GetDepthInMainChain() const;
684 /** Nodes collect new transactions into a block, hash them into a hash tree,
685 * and scan through nonce values to make the block's hash satisfy proof-of-work
686 * requirements. When they solve the proof-of-work, they broadcast the block
687 * to everyone and the block is added to the block chain. The first transaction
688 * in the block is a special one that creates a new coin owned by the creator
691 * Blocks are appended to blk0001.dat files on disk. Their location on disk
692 * is indexed by CBlockIndex objects in memory.
698 static const int CURRENT_VERSION=6;
700 uint256 hashPrevBlock;
701 uint256 hashMerkleRoot;
707 std::vector<CTransaction> vtx;
709 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
710 std::vector<unsigned char> vchBlockSig;
713 mutable std::vector<uint256> vMerkleTree;
715 // Denial-of-service detection:
717 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
726 READWRITE(this->nVersion);
727 nVersion = this->nVersion;
728 READWRITE(hashPrevBlock);
729 READWRITE(hashMerkleRoot);
734 // ConnectBlock depends on vtx following header to generate CDiskTxPos
735 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
738 READWRITE(vchBlockSig);
742 const_cast<CBlock*>(this)->vtx.clear();
743 const_cast<CBlock*>(this)->vchBlockSig.clear();
749 nVersion = CBlock::CURRENT_VERSION;
766 uint256 GetHash() const
768 return scrypt_blockhash((const uint8_t*)&nVersion);
771 int64_t GetBlockTime() const
773 return (int64_t)nTime;
776 void UpdateTime(const CBlockIndex* pindexPrev);
778 // ppcoin: entropy bit for stake modifier if chosen by modifier
779 unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
781 // ppcoin: two types of block: proof-of-work or proof-of-stake
782 bool IsProofOfStake() const
784 return (vtx.size() > 1 && vtx[1].IsCoinStake());
787 bool IsProofOfWork() const
789 return !IsProofOfStake();
792 std::pair<COutPoint, unsigned int> GetProofOfStake() const
794 if (IsProofOfStake())
795 return { vtx[1].vin[0].prevout, vtx[1].nTime };
796 return { COutPoint(), (unsigned int)0 };
799 // ppcoin: get max transaction timestamp
800 int64_t GetMaxTransactionTime() const;
801 uint256 BuildMerkleTree() const;
802 std::vector<uint256> GetMerkleBranch(int nIndex) const;
803 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
804 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet);
805 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true);
807 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
808 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
809 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
810 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
811 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
812 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
814 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
815 bool CheckBlockSignature() const;
818 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
826 /** The block chain is a tree shaped structure starting with the
827 * genesis block at the root, with each block potentially having multiple
828 * candidates to be the next block. pprev and pnext link a path through the
829 * main/longest chain. A blockindex may have multiple pprev pointing back
830 * to it, but pnext will only point forward to the longest branch, or will
831 * be null if the block is not part of the longest chain.
836 const uint256* phashBlock;
841 uint256 nChainTrust; // ppcoin: trust score of block chain
845 int64_t nMoneySupply;
847 uint32_t nFlags; // ppcoin: block index flags
850 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
851 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
852 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
855 uint64_t nStakeModifier; // hash modifier for proof-of-stake
856 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
858 // proof-of-stake specific fields
859 COutPoint prevoutStake;
861 uint256 hashProofOfStake;
865 uint256 hashMerkleRoot;
883 nStakeModifierChecksum = 0;
884 hashProofOfStake = 0;
885 prevoutStake.SetNull();
895 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
901 nBlockPos = nBlockPosIn;
908 nStakeModifierChecksum = 0;
909 hashProofOfStake = 0;
910 if (block.IsProofOfStake())
913 prevoutStake = block.vtx[1].vin[0].prevout;
914 nStakeTime = block.vtx[1].nTime;
918 prevoutStake.SetNull();
922 nVersion = block.nVersion;
923 hashMerkleRoot = block.hashMerkleRoot;
926 nNonce = block.nNonce;
929 CBlock GetBlockHeader() const;
931 uint256 GetBlockHash() const
936 int64_t GetBlockTime() const
938 return (int64_t)nTime;
941 uint256 GetBlockTrust() const;
943 bool IsInMainChain() const
945 return (pnext || this == pindexBest);
948 bool CheckIndex() const
953 int64_t GetMedianTimePast() const;
954 int64_t GetMedianTime() const;
957 * Returns true if there are nRequired or more blocks of minVersion or above
958 * in the last nToCheck blocks, starting at pstart and going backwards.
960 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
961 unsigned int nRequired, unsigned int nToCheck);
964 bool IsProofOfWork() const
966 return !(nFlags & BLOCK_PROOF_OF_STAKE);
969 bool IsProofOfStake() const
971 return (nFlags & BLOCK_PROOF_OF_STAKE);
974 void SetProofOfStake()
976 nFlags |= BLOCK_PROOF_OF_STAKE;
979 unsigned int GetStakeEntropyBit() const
981 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
984 bool SetStakeEntropyBit(unsigned int nEntropyBit);
986 bool GeneratedStakeModifier() const
988 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
991 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
992 std::string ToString() const;
996 printf("%s\n", ToString().c_str());
1002 // Used to marshal pointers into hashes for db storage.
1003 class CDiskBlockIndex : public CBlockIndex
1012 CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1013 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1015 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1016 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1021 if (!(nType & SER_GETHASH))
1022 READWRITE(nVersion);
1024 READWRITE(hashNext);
1026 READWRITE(nBlockPos);
1029 READWRITE(nMoneySupply);
1031 READWRITE(nStakeModifier);
1032 if (IsProofOfStake())
1034 READWRITE(prevoutStake);
1035 READWRITE(nStakeTime);
1036 READWRITE(hashProofOfStake);
1040 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1041 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1042 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1046 READWRITE(this->nVersion);
1047 READWRITE(hashPrev);
1048 READWRITE(hashMerkleRoot);
1052 READWRITE(blockHash);
1055 uint256 GetBlockHash() const;
1056 std::string ToString() const;
1060 printf("%s\n", ToString().c_str());
1066 // Describes a place in the block chain to another node such that if the
1067 // other node doesn't have the same branch, it can find a recent common trunk.
1068 // The further back it is, the further before the fork it may be.
1073 std::vector<uint256> vHave;
1077 CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1079 explicit CBlockLocator(const CBlockIndex* pindex)
1084 explicit CBlockLocator(uint256 hashBlock)
1086 auto mi = mapBlockIndex.find(hashBlock);
1087 if (mi != mapBlockIndex.end())
1093 if (!(nType & SER_GETHASH))
1094 READWRITE(nVersion);
1105 return vHave.empty();
1108 void Set(const CBlockIndex* pindex);
1109 int GetDistanceBack();
1110 CBlockIndex* GetBlockIndex();
1111 uint256 GetBlockHash();
1120 mutable CCriticalSection cs;
1121 std::map<uint256, CTransaction> mapTx;
1122 std::map<COutPoint, CInPoint> mapNextTx;
1124 bool accept(CTxDB& txdb, CTransaction &tx,
1125 bool fCheckInputs, bool* pfMissingInputs);
1126 bool addUnchecked(const uint256& hash, CTransaction &tx);
1127 bool remove(CTransaction &tx);
1129 void queryHashes(std::vector<uint256>& vtxid);
1134 return mapTx.size();
1137 bool exists(const uint256 &hash)
1139 return (mapTx.count(hash) != 0);
1142 CTransaction& lookup(const uint256 &hash)
1148 extern CTxMemPool mempool;