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 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;
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;
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);
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);
122 // Run an instance of the script checking thread
123 void ThreadScriptCheck(void* parg);
124 // Stop the script checking threads
125 void ThreadScriptCheckQuit();
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);
141 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType);
146 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
148 // Position on disk for a particular transaction.
156 CDiskTxPos() { SetNull(); }
157 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) : nFile(nFileIn), nBlockPos(nBlockPosIn), nTxPos(nTxPosIn) {}
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()); }
163 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
165 return (a.nFile == b.nFile &&
166 a.nBlockPos == b.nBlockPos &&
167 a.nTxPos == b.nTxPos);
170 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
176 std::string ToString() const
181 return strprintf("(nFile=%" PRIu32 ", nBlockPos=%" PRIu32 ", nTxPos=%" PRIu32 ")", nFile, nBlockPos, nTxPos);
186 printf("%s", ToString().c_str());
192 // An inpoint - a combination of a transaction and an index n into its vin
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()); }
207 // An outpoint - a combination of a transaction hash and an index n into its vout
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()); }
220 friend bool operator<(const COutPoint& a, const COutPoint& b)
222 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
225 friend bool operator==(const COutPoint& a, const COutPoint& b)
227 return (a.hash == b.hash && a.n == b.n);
230 friend bool operator!=(const COutPoint& a, const COutPoint& b)
235 std::string ToString() const
237 return strprintf("COutPoint(%s, %" PRIu32 ")", hash.ToString().substr(0,10).c_str(), n);
242 printf("%s\n", ToString().c_str());
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.
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) {}
268 READWRITE(scriptSig);
269 READWRITE(nSequence);
274 return (nSequence == std::numeric_limits<unsigned int>::max());
277 friend bool operator==(const CTxIn& a, const CTxIn& b)
279 return (a.prevout == b.prevout &&
280 a.scriptSig == b.scriptSig &&
281 a.nSequence == b.nSequence);
284 friend bool operator!=(const CTxIn& a, const CTxIn& b)
289 std::string ToStringShort() const
291 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
294 std::string ToString() const;
298 printf("%s\n", ToString().c_str());
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.
311 CScript scriptPubKey;
313 CTxOut() { SetNull(); }
314 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) : nValue(nValueIn), scriptPubKey(scriptPubKeyIn) {}
319 READWRITE(scriptPubKey);
325 scriptPubKey.clear();
330 return (nValue == -1);
336 scriptPubKey.clear();
341 return (nValue == 0 && scriptPubKey.empty());
344 uint256 GetHash() const
346 return SerializeHash(*this);
349 friend bool operator==(const CTxOut& a, const CTxOut& b)
351 return (a.nValue == b.nValue &&
352 a.scriptPubKey == b.scriptPubKey);
355 friend bool operator!=(const CTxOut& a, const CTxOut& b)
360 std::string ToStringShort() const
362 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
365 std::string ToString() const
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());
375 printf("%s\n", ToString().c_str());
389 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
391 /** The basic transaction that is broadcasted on the network and contained in
392 * blocks. A transaction can contain multiple inputs and outputs.
397 static const int CURRENT_VERSION=1;
400 std::vector<CTxIn> vin;
401 std::vector<CTxOut> vout;
404 // Denial-of-service detection:
406 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
415 READWRITE(this->nVersion);
416 nVersion = this->nVersion;
420 READWRITE(nLockTime);
425 nVersion = CTransaction::CURRENT_VERSION;
426 nTime = (uint32_t) GetAdjustedTime();
430 nDoS = 0; // Denial-of-service prevention
435 return (vin.empty() && vout.empty());
438 uint256 GetHash() const
440 return SerializeHash(*this);
443 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const;
444 bool IsNewerThan(const CTransaction& old) const;
446 bool IsCoinBase() const
448 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
451 bool IsCoinStake() const
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());
457 /** Check for standard transaction types
458 @return True if all outputs (scriptPubKeys) use only standard transaction forms
460 bool IsStandard(std::string& strReason) const;
461 bool IsStandard() const
463 std::string strReason;
464 return IsStandard(strReason);
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
472 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
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
478 unsigned int GetLegacySigOpCount() const;
480 /** Count ECDSA signature operations in pay-to-script-hash inputs.
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
486 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
488 /** Amount of bitcoins spent by this transaction.
489 @return sum of all outputs (note: does not include fees)
491 int64_t GetValueOut() const;
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.
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
501 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
503 static bool AllowFree(double dPriority)
505 // Large (in bytes) low-priority (new, small-coin) transactions
507 return dPriority > COIN * 144 / 250;
510 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
512 friend bool operator==(const CTransaction& a, const CTransaction& b)
514 return (a.nVersion == b.nVersion &&
515 a.nTime == b.nTime &&
518 a.nLockTime == b.nLockTime);
521 friend bool operator!=(const CTransaction& a, const CTransaction& b)
526 std::string ToStringShort() const;
527 std::string ToString() const;
531 printf("%s", ToString().c_str());
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);
540 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
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
550 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
551 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
553 /** Sanity check previous transactions, then, if all checks succeed,
554 mark them as spent by this transaction.
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
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
576 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
582 /** A transaction with a merkle branch linking it to the block chain. */
583 class CMerkleTx : public CTransaction
587 std::vector<uint256> vMerkleBranch;
591 mutable bool fMerkleVerified;
599 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
608 fMerkleVerified = false;
614 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
615 nVersion = this->nVersion;
616 READWRITE(hashBlock);
617 READWRITE(vMerkleBranch);
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();
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.
642 std::vector<CDiskTxPos> vSpent;
649 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
652 vSpent.resize(nOutputs);
657 if (!(nType & SER_GETHASH))
674 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
676 return (a.pos == b.pos &&
677 a.vSpent == b.vSpent);
680 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
684 int GetDepthInMainChain() const;
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
696 * Blocks are appended to blk0001.dat files on disk. Their location on disk
697 * is indexed by CBlockIndex objects in memory.
703 static const int CURRENT_VERSION=6;
705 uint256 hashPrevBlock;
706 uint256 hashMerkleRoot;
712 std::vector<CTransaction> vtx;
714 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
715 std::vector<unsigned char> vchBlockSig;
718 mutable std::vector<uint256> vMerkleTree;
720 // Denial-of-service detection:
722 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
731 READWRITE(this->nVersion);
732 nVersion = this->nVersion;
733 READWRITE(hashPrevBlock);
734 READWRITE(hashMerkleRoot);
739 // ConnectBlock depends on vtx following header to generate CDiskTxPos
740 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
743 READWRITE(vchBlockSig);
747 const_cast<CBlock*>(this)->vtx.clear();
748 const_cast<CBlock*>(this)->vchBlockSig.clear();
754 nVersion = CBlock::CURRENT_VERSION;
771 uint256 GetHash() const
773 return scrypt_blockhash((const uint8_t*)&nVersion);
776 int64_t GetBlockTime() const
778 return (int64_t)nTime;
781 void UpdateTime(const CBlockIndex* pindexPrev);
783 // ppcoin: entropy bit for stake modifier if chosen by modifier
784 unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
786 // ppcoin: two types of block: proof-of-work or proof-of-stake
787 bool IsProofOfStake() const
789 return (vtx.size() > 1 && vtx[1].IsCoinStake());
792 bool IsProofOfWork() const
794 return !IsProofOfStake();
797 std::pair<COutPoint, unsigned int> GetProofOfStake() const
799 if (IsProofOfStake())
800 return { vtx[1].vin[0].prevout, vtx[1].nTime };
801 return { COutPoint(), (unsigned int)0 };
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);
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;
819 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
820 bool CheckBlockSignature() const;
823 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
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.
841 const uint256* phashBlock;
846 uint256 nChainTrust; // ppcoin: trust score of block chain
850 int64_t nMoneySupply;
852 uint32_t nFlags; // ppcoin: block index flags
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
860 uint64_t nStakeModifier; // hash modifier for proof-of-stake
861 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
863 // proof-of-stake specific fields
864 COutPoint prevoutStake;
866 uint256 hashProofOfStake;
870 uint256 hashMerkleRoot;
888 nStakeModifierChecksum = 0;
889 hashProofOfStake = 0;
890 prevoutStake.SetNull();
900 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
906 nBlockPos = nBlockPosIn;
913 nStakeModifierChecksum = 0;
914 hashProofOfStake = 0;
915 if (block.IsProofOfStake())
918 prevoutStake = block.vtx[1].vin[0].prevout;
919 nStakeTime = block.vtx[1].nTime;
923 prevoutStake.SetNull();
927 nVersion = block.nVersion;
928 hashMerkleRoot = block.hashMerkleRoot;
931 nNonce = block.nNonce;
934 CBlock GetBlockHeader() const;
936 uint256 GetBlockHash() const
941 int64_t GetBlockTime() const
943 return (int64_t)nTime;
946 uint256 GetBlockTrust() const;
948 bool IsInMainChain() const
950 return (pnext || this == pindexBest);
953 bool CheckIndex() const
958 int64_t GetMedianTimePast() const;
959 int64_t GetMedianTime() const;
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.
965 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
966 unsigned int nRequired, unsigned int nToCheck);
969 bool IsProofOfWork() const
971 return !(nFlags & BLOCK_PROOF_OF_STAKE);
974 bool IsProofOfStake() const
976 return (nFlags & BLOCK_PROOF_OF_STAKE);
979 void SetProofOfStake()
981 nFlags |= BLOCK_PROOF_OF_STAKE;
984 unsigned int GetStakeEntropyBit() const
986 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
989 bool SetStakeEntropyBit(unsigned int nEntropyBit);
991 bool GeneratedStakeModifier() const
993 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
996 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
997 std::string ToString() const;
1001 printf("%s\n", ToString().c_str());
1007 // Used to marshal pointers into hashes for db storage.
1008 class CDiskBlockIndex : public CBlockIndex
1017 CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1018 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1020 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1021 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1026 if (!(nType & SER_GETHASH))
1027 READWRITE(nVersion);
1029 READWRITE(hashNext);
1031 READWRITE(nBlockPos);
1034 READWRITE(nMoneySupply);
1036 READWRITE(nStakeModifier);
1037 if (IsProofOfStake())
1039 READWRITE(prevoutStake);
1040 READWRITE(nStakeTime);
1041 READWRITE(hashProofOfStake);
1045 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1046 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1047 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1051 READWRITE(this->nVersion);
1052 READWRITE(hashPrev);
1053 READWRITE(hashMerkleRoot);
1057 READWRITE(blockHash);
1060 uint256 GetBlockHash() const;
1061 std::string ToString() const;
1065 printf("%s\n", ToString().c_str());
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.
1078 std::vector<uint256> vHave;
1082 CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1084 explicit CBlockLocator(const CBlockIndex* pindex)
1089 explicit CBlockLocator(uint256 hashBlock)
1091 auto mi = mapBlockIndex.find(hashBlock);
1092 if (mi != mapBlockIndex.end())
1098 if (!(nType & SER_GETHASH))
1099 READWRITE(nVersion);
1110 return vHave.empty();
1113 void Set(const CBlockIndex* pindex);
1114 int GetDistanceBack();
1115 CBlockIndex* GetBlockIndex();
1116 uint256 GetBlockHash();
1125 mutable CCriticalSection cs;
1126 std::map<uint256, CTransaction> mapTx;
1127 std::map<COutPoint, CInPoint> mapNextTx;
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);
1134 void queryHashes(std::vector<uint256>& vtxid);
1139 return mapTx.size();
1142 bool exists(const uint256 &hash)
1144 return (mapTx.count(hash) != 0);
1147 CTransaction& lookup(const uint256 &hash)
1153 extern CTxMemPool mempool;