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"
33 class CRequestTracker;
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 = 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 map<uint256, CBlockIndex*> mapBlockIndex;
71 extern set<pair<COutPoint, unsigned int> > setStakeSeen;
72 extern CBlockIndex* pindexGenesisBlock;
73 extern unsigned int nNodeLifespan;
74 extern unsigned int nStakeMinAge;
75 extern int nCoinbaseMaturity;
76 extern int nBestHeight;
77 extern uint256 nBestChainTrust;
78 extern uint256 nBestInvalidTrust;
79 extern uint256 hashBestChain;
80 extern CBlockIndex* pindexBest;
81 extern unsigned int nTransactionsUpdated;
82 extern uint64_t nLastBlockTx;
83 extern uint64_t nLastBlockSize;
84 extern uint32_t nLastCoinStakeSearchInterval;
85 extern const string strMessageMagic;
86 extern int64_t nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern set<CWallet*> setpwalletRegistered;
89 extern uint32_t nNetworkID;
90 extern map<uint256, CBlock*> mapOrphanBlocks;
93 extern int64_t nTransactionFee;
94 extern int64_t nMinimumInputValue;
95 extern bool fUseFastIndex;
96 extern int nScriptCheckThreads;
97 extern const uint256 entropyStore[38];
99 // Minimum disk space required - used in CheckDiskSpace()
100 static const uint64_t nMinDiskSpace = 52428800;
107 void RegisterWallet(CWallet* pwalletIn);
108 void UnregisterWallet(CWallet* pwalletIn);
109 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
110 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
111 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
112 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
113 FILE* AppendBlockFile(unsigned int& nFileRet);
115 void UnloadBlockIndex();
116 bool LoadBlockIndex(bool fAllowNew=true);
117 void PrintBlockTree();
118 CBlockIndex* FindBlockByHeight(int nHeight);
119 bool ProcessMessages(CNode* pfrom);
120 bool SendMessages(CNode* pto);
121 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface);
123 // Run an instance of the script checking thread
124 void ThreadScriptCheck(void* parg);
125 // Stop the script checking threads
126 void ThreadScriptCheckQuit();
128 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
129 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
130 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees=0);
131 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
132 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
133 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
134 int GetNumBlocksOfPeers();
135 bool IsInitialBlockDownload();
136 string GetWarnings(string strFor);
137 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
138 uint256 WantedByOrphan(const CBlock* pblockOrphan);
139 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
140 void ResendWalletTransactions(bool fForceResend=false);
142 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType);
147 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut);
149 // Position on disk for a particular transaction.
157 CDiskTxPos() { SetNull(); }
158 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) : nFile(nFileIn), nBlockPos(nBlockPosIn), nTxPos(nTxPosIn) {}
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
161 void SetNull() { nFile = numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
162 bool IsNull() const { return (nFile == numeric_limits<uint32_t>::max()); }
164 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
166 return (a.nFile == b.nFile &&
167 a.nBlockPos == b.nBlockPos &&
168 a.nTxPos == b.nTxPos);
171 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
177 string ToString() const
182 return strprintf("(nFile=%" PRIu32 ", nBlockPos=%" PRIu32 ", nTxPos=%" PRIu32 ")", nFile, nBlockPos, nTxPos);
187 printf("%s", ToString().c_str());
193 // An inpoint - a combination of a transaction and an index n into its vin
200 CInPoint() { SetNull(); }
201 CInPoint(CTransaction* ptxIn, uint32_t nIn) : ptx(ptxIn), n(nIn) {}
202 void SetNull() { ptx = NULL; n = numeric_limits<uint32_t>::max(); }
203 bool IsNull() const { return (ptx == NULL && n == numeric_limits<uint32_t>::max()); }
208 // An outpoint - a combination of a transaction hash and an index n into its vout
215 COutPoint() { SetNull(); }
216 COutPoint(uint256 hashIn, uint32_t nIn) : hash(hashIn), n(nIn) {}
217 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
218 void SetNull() { hash = 0; n = numeric_limits<uint32_t>::max(); }
219 bool IsNull() const { return (hash == 0 && n == numeric_limits<uint32_t>::max()); }
221 friend bool operator<(const COutPoint& a, const COutPoint& b)
223 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
226 friend bool operator==(const COutPoint& a, const COutPoint& b)
228 return (a.hash == b.hash && a.n == b.n);
231 friend bool operator!=(const COutPoint& a, const COutPoint& b)
236 string ToString() const
238 return strprintf("COutPoint(%s, %" PRIu32 ")", hash.ToString().substr(0,10).c_str(), n);
243 printf("%s\n", ToString().c_str());
249 // An input of a transaction. It contains the location of the previous
250 // transaction's output that it claims and a signature that matches the
251 // output's public key.
260 CTxIn() : nSequence(numeric_limits<unsigned int>::max()) {}
261 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=numeric_limits<unsigned int>::max())
262 : prevout(prevoutIn), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
263 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=numeric_limits<unsigned int>::max())
264 : prevout(COutPoint(hashPrevTx, nOut)), scriptSig(scriptSigIn), nSequence(nSequenceIn) {}
269 READWRITE(scriptSig);
270 READWRITE(nSequence);
275 return (nSequence == numeric_limits<unsigned int>::max());
278 friend bool operator==(const CTxIn& a, const CTxIn& b)
280 return (a.prevout == b.prevout &&
281 a.scriptSig == b.scriptSig &&
282 a.nSequence == b.nSequence);
285 friend bool operator!=(const CTxIn& a, const CTxIn& b)
290 string ToStringShort() const
292 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
295 string ToString() const;
299 printf("%s\n", ToString().c_str());
305 // An output of a transaction. It contains the public key that the next input
306 // must be able to sign with to claim it.
312 CScript scriptPubKey;
314 CTxOut() { SetNull(); }
315 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn) : nValue(nValueIn), scriptPubKey(scriptPubKeyIn) {}
320 READWRITE(scriptPubKey);
326 scriptPubKey.clear();
331 return (nValue == -1);
337 scriptPubKey.clear();
342 return (nValue == 0 && scriptPubKey.empty());
345 uint256 GetHash() const
347 return SerializeHash(*this);
350 friend bool operator==(const CTxOut& a, const CTxOut& b)
352 return (a.nValue == b.nValue &&
353 a.scriptPubKey == b.scriptPubKey);
356 friend bool operator!=(const CTxOut& a, const CTxOut& b)
361 string ToStringShort() const
363 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
366 string ToString() const
368 if (IsEmpty()) return "CTxOut(empty)";
369 if (scriptPubKey.size() < 6)
370 return "CTxOut(error)";
371 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
376 printf("%s\n", ToString().c_str());
390 typedef map<uint256, pair<CTxIndex, CTransaction> > MapPrevTx;
392 /** The basic transaction that is broadcasted on the network and contained in
393 * blocks. A transaction can contain multiple inputs and outputs.
398 static const int CURRENT_VERSION=1;
405 // Denial-of-service detection:
407 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
416 READWRITE(this->nVersion);
417 nVersion = this->nVersion;
421 READWRITE(nLockTime);
426 nVersion = CTransaction::CURRENT_VERSION;
427 nTime = (uint32_t) GetAdjustedTime();
431 nDoS = 0; // Denial-of-service prevention
436 return (vin.empty() && vout.empty());
439 uint256 GetHash() const
441 return SerializeHash(*this);
444 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const;
445 bool IsNewerThan(const CTransaction& old) const;
447 bool IsCoinBase() const
449 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
452 bool IsCoinStake() const
454 // ppcoin: the coin stake transaction is marked with the first output empty
455 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
458 /** Check for standard transaction types
459 @return True if all outputs (scriptPubKeys) use only standard transaction forms
461 bool IsStandard(string& strReason) const;
462 bool IsStandard() const
465 return IsStandard(strReason);
468 /** Check for standard transaction types
469 @param[in] mapInputs Map of previous transactions that have outputs we're spending
470 @return True if all inputs (scriptSigs) use only standard transaction forms
471 @see CTransaction::FetchInputs
473 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
475 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
476 @return number of sigops this transaction's outputs will produce when spent
477 @see CTransaction::FetchInputs
479 unsigned int GetLegacySigOpCount() const;
481 /** Count ECDSA signature operations in pay-to-script-hash inputs.
483 @param[in] mapInputs Map of previous transactions that have outputs we're spending
484 @return maximum number of sigops required to validate this transaction's inputs
485 @see CTransaction::FetchInputs
487 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
489 /** Amount of bitcoins spent by this transaction.
490 @return sum of all outputs (note: does not include fees)
492 int64_t GetValueOut() const;
494 /** Amount of bitcoins coming in to this transaction
495 Note that lightweight clients may not know anything besides the hash of previous transactions,
496 so may not be able to calculate this.
498 @param[in] mapInputs Map of previous transactions that have outputs we're spending
499 @return Sum of value of all inputs (scriptSigs)
500 @see CTransaction::FetchInputs
502 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
504 static bool AllowFree(double dPriority)
506 // Large (in bytes) low-priority (new, small-coin) transactions
508 return dPriority > COIN * 144 / 250;
511 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
513 friend bool operator==(const CTransaction& a, const CTransaction& b)
515 return (a.nVersion == b.nVersion &&
516 a.nTime == b.nTime &&
519 a.nLockTime == b.nLockTime);
522 friend bool operator!=(const CTransaction& a, const CTransaction& b)
527 string ToStringShort() const;
528 string ToString() const;
532 printf("%s", ToString().c_str());
535 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL);
536 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
537 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
538 bool ReadFromDisk(COutPoint prevout);
539 bool DisconnectInputs(CTxDB& txdb);
541 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
543 @param[in] txdb Transaction database
544 @param[in] mapTestPool List of pending changes to the transaction index database
545 @param[in] fBlock True if being called to add a new best-block to the chain
546 @param[in] fMiner True if being called by CreateNewBlock
547 @param[out] inputsRet Pointers to this transaction's inputs
548 @param[out] fInvalid returns true if transaction is invalid
549 @return Returns true if all inputs are in txdb or mapTestPool
551 bool FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
552 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
554 /** Sanity check previous transactions, then, if all checks succeed,
555 mark them as spent by this transaction.
557 @param[in] inputs Previous transactions (from FetchInputs)
558 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
559 @param[in] posThisTx Position of this transaction on disk
560 @param[in] pindexBlock
561 @param[in] fBlock true if called from ConnectBlock
562 @param[in] fMiner true if called from CreateNewBlock
563 @param[in] fScriptChecks enable scripts validation?
564 @param[in] flags STRICT_FLAGS script validation flags
565 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
566 @return Returns true if all checks succeed
568 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
569 bool fBlock, bool fMiner, bool fScriptChecks=true,
570 unsigned int flags=STRICT_FLAGS, vector<CScriptCheck> *pvChecks = NULL);
571 bool ClientConnectInputs();
572 bool CheckTransaction() const;
573 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
574 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
577 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
583 /** A transaction with a merkle branch linking it to the block chain. */
584 class CMerkleTx : public CTransaction
588 vector<uint256> vMerkleBranch;
592 mutable bool fMerkleVerified;
600 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
609 fMerkleVerified = false;
615 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
616 nVersion = this->nVersion;
617 READWRITE(hashBlock);
618 READWRITE(vMerkleBranch);
623 int SetMerkleBranch(const CBlock* pblock=NULL);
624 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
625 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
626 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
627 int GetBlocksToMaturity() const;
628 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
629 bool AcceptToMemoryPool();
635 /** A txdb record that contains the disk location of a transaction and the
636 * locations of transactions that spend its outputs. vSpent is really only
637 * used as a flag, but having the location is very helpful for debugging.
643 vector<CDiskTxPos> vSpent;
650 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
653 vSpent.resize(nOutputs);
658 if (!(nType & SER_GETHASH))
675 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
677 return (a.pos == b.pos &&
678 a.vSpent == b.vSpent);
681 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
685 int GetDepthInMainChain() const;
690 /** Nodes collect new transactions into a block, hash them into a hash tree,
691 * and scan through nonce values to make the block's hash satisfy proof-of-work
692 * requirements. When they solve the proof-of-work, they broadcast the block
693 * to everyone and the block is added to the block chain. The first transaction
694 * in the block is a special one that creates a new coin owned by the creator
697 * Blocks are appended to blk0001.dat files on disk. Their location on disk
698 * is indexed by CBlockIndex objects in memory.
704 static const int CURRENT_VERSION=6;
706 uint256 hashPrevBlock;
707 uint256 hashMerkleRoot;
713 vector<CTransaction> vtx;
715 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
716 vector<unsigned char> vchBlockSig;
719 mutable vector<uint256> vMerkleTree;
721 // Denial-of-service detection:
723 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
732 READWRITE(this->nVersion);
733 nVersion = this->nVersion;
734 READWRITE(hashPrevBlock);
735 READWRITE(hashMerkleRoot);
740 // ConnectBlock depends on vtx following header to generate CDiskTxPos
741 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
744 READWRITE(vchBlockSig);
748 const_cast<CBlock*>(this)->vtx.clear();
749 const_cast<CBlock*>(this)->vchBlockSig.clear();
755 nVersion = CBlock::CURRENT_VERSION;
772 uint256 GetHash() const
774 return scrypt_blockhash((const uint8_t*)&nVersion);
777 int64_t GetBlockTime() const
779 return (int64_t)nTime;
782 void UpdateTime(const CBlockIndex* pindexPrev);
784 // ppcoin: entropy bit for stake modifier if chosen by modifier
785 unsigned int GetStakeEntropyBit(unsigned int nHeight) const;
787 // ppcoin: two types of block: proof-of-work or proof-of-stake
788 bool IsProofOfStake() const
790 return (vtx.size() > 1 && vtx[1].IsCoinStake());
793 bool IsProofOfWork() const
795 return !IsProofOfStake();
798 pair<COutPoint, unsigned int> GetProofOfStake() const
800 if (IsProofOfStake())
801 return { vtx[1].vin[0].prevout, vtx[1].nTime };
802 return { COutPoint(), (unsigned int)0 };
805 // ppcoin: get max transaction timestamp
806 int64_t GetMaxTransactionTime() const;
807 uint256 BuildMerkleTree() const;
808 vector<uint256> GetMerkleBranch(int nIndex) const;
809 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex);
810 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet);
811 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true);
813 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
814 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
815 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
816 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
817 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
818 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
820 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
821 bool CheckBlockSignature() const;
824 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
832 /** The block chain is a tree shaped structure starting with the
833 * genesis block at the root, with each block potentially having multiple
834 * candidates to be the next block. pprev and pnext link a path through the
835 * main/longest chain. A blockindex may have multiple pprev pointing back
836 * to it, but pnext will only point forward to the longest branch, or will
837 * be null if the block is not part of the longest chain.
842 const uint256* phashBlock;
847 uint256 nChainTrust; // ppcoin: trust score of block chain
851 int64_t nMoneySupply;
853 uint32_t nFlags; // ppcoin: block index flags
856 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
857 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
858 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
861 uint64_t nStakeModifier; // hash modifier for proof-of-stake
862 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
864 // proof-of-stake specific fields
865 COutPoint prevoutStake;
867 uint256 hashProofOfStake;
871 uint256 hashMerkleRoot;
889 nStakeModifierChecksum = 0;
890 hashProofOfStake = 0;
891 prevoutStake.SetNull();
901 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
907 nBlockPos = nBlockPosIn;
914 nStakeModifierChecksum = 0;
915 hashProofOfStake = 0;
916 if (block.IsProofOfStake())
919 prevoutStake = block.vtx[1].vin[0].prevout;
920 nStakeTime = block.vtx[1].nTime;
924 prevoutStake.SetNull();
928 nVersion = block.nVersion;
929 hashMerkleRoot = block.hashMerkleRoot;
932 nNonce = block.nNonce;
935 CBlock GetBlockHeader() const;
937 uint256 GetBlockHash() const
942 int64_t GetBlockTime() const
944 return (int64_t)nTime;
947 uint256 GetBlockTrust() const;
949 bool IsInMainChain() const
951 return (pnext || this == pindexBest);
954 bool CheckIndex() const
959 int64_t GetMedianTimePast() const;
960 int64_t GetMedianTime() const;
963 * Returns true if there are nRequired or more blocks of minVersion or above
964 * in the last nToCheck blocks, starting at pstart and going backwards.
966 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
967 unsigned int nRequired, unsigned int nToCheck);
970 bool IsProofOfWork() const
972 return !(nFlags & BLOCK_PROOF_OF_STAKE);
975 bool IsProofOfStake() const
977 return (nFlags & BLOCK_PROOF_OF_STAKE);
980 void SetProofOfStake()
982 nFlags |= BLOCK_PROOF_OF_STAKE;
985 unsigned int GetStakeEntropyBit() const
987 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
990 bool SetStakeEntropyBit(unsigned int nEntropyBit);
992 bool GeneratedStakeModifier() const
994 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
997 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier);
998 string ToString() const;
1002 printf("%s\n", ToString().c_str());
1008 // Used to marshal pointers into hashes for db storage.
1009 class CDiskBlockIndex : public CBlockIndex
1018 CDiskBlockIndex() : blockHash(0), hashPrev(0), hashNext(0) {}
1019 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1021 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1022 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1027 if (!(nType & SER_GETHASH))
1028 READWRITE(nVersion);
1030 READWRITE(hashNext);
1032 READWRITE(nBlockPos);
1035 READWRITE(nMoneySupply);
1037 READWRITE(nStakeModifier);
1038 if (IsProofOfStake())
1040 READWRITE(prevoutStake);
1041 READWRITE(nStakeTime);
1042 READWRITE(hashProofOfStake);
1046 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1047 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1048 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1052 READWRITE(this->nVersion);
1053 READWRITE(hashPrev);
1054 READWRITE(hashMerkleRoot);
1058 READWRITE(blockHash);
1061 uint256 GetBlockHash() const;
1062 string ToString() const;
1066 printf("%s\n", ToString().c_str());
1072 // Describes a place in the block chain to another node such that if the
1073 // other node doesn't have the same branch, it can find a recent common trunk.
1074 // The further back it is, the further before the fork it may be.
1079 vector<uint256> vHave;
1083 CBlockLocator(const vector<uint256>& vHaveIn) : vHave(vHaveIn) { }
1085 explicit CBlockLocator(const CBlockIndex* pindex)
1090 explicit CBlockLocator(uint256 hashBlock)
1092 auto mi = mapBlockIndex.find(hashBlock);
1093 if (mi != mapBlockIndex.end())
1099 if (!(nType & SER_GETHASH))
1100 READWRITE(nVersion);
1111 return vHave.empty();
1114 void Set(const CBlockIndex* pindex);
1115 int GetDistanceBack();
1116 CBlockIndex* GetBlockIndex();
1117 uint256 GetBlockHash();
1126 mutable CCriticalSection cs;
1127 map<uint256, CTransaction> mapTx;
1128 map<COutPoint, CInPoint> mapNextTx;
1130 bool accept(CTxDB& txdb, CTransaction &tx,
1131 bool fCheckInputs, bool* pfMissingInputs);
1132 bool addUnchecked(const uint256& hash, CTransaction &tx);
1133 bool remove(CTransaction &tx);
1135 void queryHashes(vector<uint256>& vtxid);
1140 return mapTx.size();
1143 bool exists(const uint256 &hash)
1145 return (mapTx.count(hash) != 0);
1148 CTransaction& lookup(const uint256 &hash)
1154 extern CTxMemPool mempool;