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"
30 class CRequestTracker;
37 static const unsigned int MAX_BLOCK_SIZE = 1000000;
38 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
39 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
40 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
41 static const unsigned int MAX_INV_SZ = 50000;
43 static const int64_t MIN_TX_FEE = CENT/10;
44 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
46 static const int64_t MAX_MONEY = std::numeric_limits<int64_t>::max();
47 static const int64_t MAX_MINT_PROOF_OF_WORK = 100 * COIN;
48 static const int64_t MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
49 static const int64_t MIN_TXOUT_AMOUNT = CENT/100;
52 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
53 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
54 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
55 // Maximum number of script-checking threads allowed
56 static const int MAX_SCRIPTCHECK_THREADS = 16;
58 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
59 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
61 inline int64_t PastDrift(int64_t nTime) { return nTime - 2 * nOneHour; } // up to 2 hours from the past
62 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
64 extern CScript COINBASE_FLAGS;
65 extern CCriticalSection cs_main;
66 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
67 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
68 extern CBlockIndex* pindexGenesisBlock;
69 extern unsigned int nNodeLifespan;
70 extern unsigned int nStakeMinAge;
71 extern int nCoinbaseMaturity;
72 extern int nBestHeight;
73 extern uint256 nBestChainTrust;
74 extern uint256 nBestInvalidTrust;
75 extern uint256 hashBestChain;
76 extern CBlockIndex* pindexBest;
77 extern unsigned int nTransactionsUpdated;
78 extern uint64_t nLastBlockTx;
79 extern uint64_t nLastBlockSize;
80 extern uint32_t nLastCoinStakeSearchInterval;
81 extern const std::string strMessageMagic;
82 extern int64_t nTimeBestReceived;
83 extern CCriticalSection cs_setpwalletRegistered;
84 extern std::set<CWallet*> setpwalletRegistered;
85 extern unsigned char pchMessageStart[4];
86 extern std::map<uint256, CBlock*> mapOrphanBlocks;
89 extern int64_t nTransactionFee;
90 extern int64_t nMinimumInputValue;
91 extern bool fUseFastIndex;
92 extern int nScriptCheckThreads;
93 extern const uint256 entropyStore[38];
95 // Minimum disk space required - used in CheckDiskSpace()
96 static const uint64_t nMinDiskSpace = 52428800;
103 void RegisterWallet(CWallet* pwalletIn);
104 void UnregisterWallet(CWallet* pwalletIn);
105 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
106 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
107 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
108 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
109 FILE* AppendBlockFile(unsigned int& nFileRet);
111 void UnloadBlockIndex();
112 bool LoadBlockIndex(bool fAllowNew=true);
113 void PrintBlockTree();
114 CBlockIndex* FindBlockByHeight(int nHeight);
115 bool ProcessMessages(CNode* pfrom);
116 bool SendMessages(CNode* pto);
117 bool LoadExternalBlockFile(FILE* fileIn);
119 // Run an instance of the script checking thread
120 void ThreadScriptCheck(void* parg);
121 // Stop the script checking threads
122 void ThreadScriptCheckQuit();
124 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
125 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
126 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees=0);
127 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
128 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
129 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
130 int GetNumBlocksOfPeers();
131 bool IsInitialBlockDownload();
132 std::string GetWarnings(std::string strFor);
133 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
134 uint256 WantedByOrphan(const CBlock* pblockOrphan);
135 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
136 void ResendWalletTransactions(bool fForceResend=false);
138 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
143 /** Position on disk for a particular transaction. */
156 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
159 nBlockPos = nBlockPosIn;
163 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
164 void SetNull() { nFile = std::numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
165 bool IsNull() const { return (nFile == std::numeric_limits<uint32_t>::max()); }
167 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
169 return (a.nFile == b.nFile &&
170 a.nBlockPos == b.nBlockPos &&
171 a.nTxPos == b.nTxPos);
174 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
180 std::string ToString() const
185 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
190 printf("%s", ToString().c_str());
196 /** An inpoint - a combination of a transaction and an index n into its vin */
203 CInPoint() { SetNull(); }
204 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
205 void SetNull() { ptx = NULL; n = std::numeric_limits<uint32_t>::max(); }
206 bool IsNull() const { return (ptx == NULL && n == std::numeric_limits<uint32_t>::max()); }
211 /** An outpoint - a combination of a transaction hash and an index n into its vout */
218 COutPoint() { SetNull(); }
219 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
220 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
221 void SetNull() { hash = 0; n = std::numeric_limits<uint32_t>::max(); }
222 bool IsNull() const { return (hash == 0 && n == std::numeric_limits<uint32_t>::max()); }
224 friend bool operator<(const COutPoint& a, const COutPoint& b)
226 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
229 friend bool operator==(const COutPoint& a, const COutPoint& b)
231 return (a.hash == b.hash && a.n == b.n);
234 friend bool operator!=(const COutPoint& a, const COutPoint& b)
239 std::string ToString() const
241 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
246 printf("%s\n", ToString().c_str());
253 /** An input of a transaction. It contains the location of the previous
254 * transaction's output that it claims and a signature that matches the
255 * output's public key.
266 nSequence = std::numeric_limits<unsigned int>::max();
269 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
272 scriptSig = scriptSigIn;
273 nSequence = nSequenceIn;
276 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
278 prevout = COutPoint(hashPrevTx, nOut);
279 scriptSig = scriptSigIn;
280 nSequence = nSequenceIn;
286 READWRITE(scriptSig);
287 READWRITE(nSequence);
292 return (nSequence == std::numeric_limits<unsigned int>::max());
295 friend bool operator==(const CTxIn& a, const CTxIn& b)
297 return (a.prevout == b.prevout &&
298 a.scriptSig == b.scriptSig &&
299 a.nSequence == b.nSequence);
302 friend bool operator!=(const CTxIn& a, const CTxIn& b)
307 std::string ToStringShort() const
309 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
312 std::string ToString() const
316 str += prevout.ToString();
317 if (prevout.IsNull())
318 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
320 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
321 if (nSequence != std::numeric_limits<unsigned int>::max())
322 str += strprintf(", nSequence=%u", nSequence);
329 printf("%s\n", ToString().c_str());
336 /** An output of a transaction. It contains the public key that the next input
337 * must be able to sign with to claim it.
343 CScript scriptPubKey;
350 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
353 scriptPubKey = scriptPubKeyIn;
359 READWRITE(scriptPubKey);
365 scriptPubKey.clear();
370 return (nValue == -1);
376 scriptPubKey.clear();
381 return (nValue == 0 && scriptPubKey.empty());
384 uint256 GetHash() const
386 return SerializeHash(*this);
389 friend bool operator==(const CTxOut& a, const CTxOut& b)
391 return (a.nValue == b.nValue &&
392 a.scriptPubKey == b.scriptPubKey);
395 friend bool operator!=(const CTxOut& a, const CTxOut& b)
400 std::string ToStringShort() const
402 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
405 std::string ToString() const
407 if (IsEmpty()) return "CTxOut(empty)";
408 if (scriptPubKey.size() < 6)
409 return "CTxOut(error)";
410 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
415 printf("%s\n", ToString().c_str());
429 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
431 /** The basic transaction that is broadcasted on the network and contained in
432 * blocks. A transaction can contain multiple inputs and outputs.
437 static const int CURRENT_VERSION=1;
440 std::vector<CTxIn> vin;
441 std::vector<CTxOut> vout;
444 // Denial-of-service detection:
446 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
455 READWRITE(this->nVersion);
456 nVersion = this->nVersion;
460 READWRITE(nLockTime);
465 nVersion = CTransaction::CURRENT_VERSION;
466 nTime = (uint32_t) GetAdjustedTime();
470 nDoS = 0; // Denial-of-service prevention
475 return (vin.empty() && vout.empty());
478 uint256 GetHash() const
480 return SerializeHash(*this);
483 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const
485 // Time based nLockTime implemented in 0.1.6
488 if (nBlockHeight == 0)
489 nBlockHeight = nBestHeight;
491 nBlockTime = GetAdjustedTime();
492 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
494 for (const CTxIn& txin : vin)
500 bool IsNewerThan(const CTransaction& old) const
502 if (vin.size() != old.vin.size())
504 for (unsigned int i = 0; i < vin.size(); i++)
505 if (vin[i].prevout != old.vin[i].prevout)
509 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
510 for (unsigned int i = 0; i < vin.size(); i++)
512 if (vin[i].nSequence != old.vin[i].nSequence)
514 if (vin[i].nSequence <= nLowest)
517 nLowest = vin[i].nSequence;
519 if (old.vin[i].nSequence < nLowest)
522 nLowest = old.vin[i].nSequence;
529 bool IsCoinBase() const
531 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
534 bool IsCoinStake() const
536 // ppcoin: the coin stake transaction is marked with the first output empty
537 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
540 /** Check for standard transaction types
541 @return True if all outputs (scriptPubKeys) use only standard transaction forms
543 bool IsStandard(std::string& strReason) const;
544 bool IsStandard() const
546 std::string strReason;
547 return IsStandard(strReason);
550 /** Check for standard transaction types
551 @param[in] mapInputs Map of previous transactions that have outputs we're spending
552 @return True if all inputs (scriptSigs) use only standard transaction forms
553 @see CTransaction::FetchInputs
555 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
557 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
558 @return number of sigops this transaction's outputs will produce when spent
559 @see CTransaction::FetchInputs
561 unsigned int GetLegacySigOpCount() const;
563 /** Count ECDSA signature operations in pay-to-script-hash inputs.
565 @param[in] mapInputs Map of previous transactions that have outputs we're spending
566 @return maximum number of sigops required to validate this transaction's inputs
567 @see CTransaction::FetchInputs
569 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
571 /** Amount of bitcoins spent by this transaction.
572 @return sum of all outputs (note: does not include fees)
574 int64_t GetValueOut() const
576 int64_t nValueOut = 0;
577 for (const CTxOut& txout : vout)
579 nValueOut += txout.nValue;
580 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
581 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
586 /** Amount of bitcoins coming in to this transaction
587 Note that lightweight clients may not know anything besides the hash of previous transactions,
588 so may not be able to calculate this.
590 @param[in] mapInputs Map of previous transactions that have outputs we're spending
591 @return Sum of value of all inputs (scriptSigs)
592 @see CTransaction::FetchInputs
594 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
596 static bool AllowFree(double dPriority)
598 // Large (in bytes) low-priority (new, small-coin) transactions
600 return dPriority > COIN * 144 / 250;
603 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
605 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
607 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
609 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
612 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
613 return error("CTransaction::ReadFromDisk() : fseek failed");
618 catch (const std::exception&) {
619 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
622 // Return file pointer
625 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
626 return error("CTransaction::ReadFromDisk() : second fseek failed");
627 *pfileRet = filein.release();
632 friend bool operator==(const CTransaction& a, const CTransaction& b)
634 return (a.nVersion == b.nVersion &&
635 a.nTime == b.nTime &&
638 a.nLockTime == b.nLockTime);
641 friend bool operator!=(const CTransaction& a, const CTransaction& b)
646 std::string ToStringShort() const
649 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
653 std::string ToString() const
656 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
657 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
658 GetHash().ToString().substr(0,10).c_str(),
664 for (unsigned int i = 0; i < vin.size(); i++)
665 str += " " + vin[i].ToString() + "\n";
666 for (unsigned int i = 0; i < vout.size(); i++)
667 str += " " + vout[i].ToString() + "\n";
673 printf("%s", ToString().c_str());
677 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
678 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
679 bool ReadFromDisk(COutPoint prevout);
680 bool DisconnectInputs(CTxDB& txdb);
682 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
684 @param[in] txdb Transaction database
685 @param[in] mapTestPool List of pending changes to the transaction index database
686 @param[in] fBlock True if being called to add a new best-block to the chain
687 @param[in] fMiner True if being called by CreateNewBlock
688 @param[out] inputsRet Pointers to this transaction's inputs
689 @param[out] fInvalid returns true if transaction is invalid
690 @return Returns true if all inputs are in txdb or mapTestPool
692 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
693 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
695 /** Sanity check previous transactions, then, if all checks succeed,
696 mark them as spent by this transaction.
698 @param[in] inputs Previous transactions (from FetchInputs)
699 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
700 @param[in] posThisTx Position of this transaction on disk
701 @param[in] pindexBlock
702 @param[in] fBlock true if called from ConnectBlock
703 @param[in] fMiner true if called from CreateNewBlock
704 @param[in] fScriptChecks enable scripts validation?
705 @param[in] flags STRICT_FLAGS script validation flags
706 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
707 @return Returns true if all checks succeed
709 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
710 bool fBlock, bool fMiner, bool fScriptChecks=true,
711 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
712 bool ClientConnectInputs();
713 bool CheckTransaction() const;
714 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
715 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
718 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
721 /** Closure representing one script verification
722 * Note that this stores references to the spending transaction */
726 CScript scriptPubKey;
727 const CTransaction *ptxTo;
734 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
735 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
736 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
738 bool operator()() const;
740 void swap(CScriptCheck &check) {
741 scriptPubKey.swap(check.scriptPubKey);
742 std::swap(ptxTo, check.ptxTo);
743 std::swap(nIn, check.nIn);
744 std::swap(nFlags, check.nFlags);
745 std::swap(nHashType, check.nHashType);
752 /** A transaction with a merkle branch linking it to the block chain. */
753 class CMerkleTx : public CTransaction
757 std::vector<uint256> vMerkleBranch;
761 mutable bool fMerkleVerified;
769 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
778 fMerkleVerified = false;
784 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
785 nVersion = this->nVersion;
786 READWRITE(hashBlock);
787 READWRITE(vMerkleBranch);
792 int SetMerkleBranch(const CBlock* pblock=NULL);
793 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
794 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
795 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
796 int GetBlocksToMaturity() const;
797 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
798 bool AcceptToMemoryPool();
804 /** A txdb record that contains the disk location of a transaction and the
805 * locations of transactions that spend its outputs. vSpent is really only
806 * used as a flag, but having the location is very helpful for debugging.
812 std::vector<CDiskTxPos> vSpent;
819 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
822 vSpent.resize(nOutputs);
827 if (!(nType & SER_GETHASH))
844 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
846 return (a.pos == b.pos &&
847 a.vSpent == b.vSpent);
850 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
854 int GetDepthInMainChain() const;
859 /** Nodes collect new transactions into a block, hash them into a hash tree,
860 * and scan through nonce values to make the block's hash satisfy proof-of-work
861 * requirements. When they solve the proof-of-work, they broadcast the block
862 * to everyone and the block is added to the block chain. The first transaction
863 * in the block is a special one that creates a new coin owned by the creator
866 * Blocks are appended to blk0001.dat files on disk. Their location on disk
867 * is indexed by CBlockIndex objects in memory.
873 static const int CURRENT_VERSION=6;
875 uint256 hashPrevBlock;
876 uint256 hashMerkleRoot;
882 std::vector<CTransaction> vtx;
884 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
885 std::vector<unsigned char> vchBlockSig;
888 mutable std::vector<uint256> vMerkleTree;
890 // Denial-of-service detection:
892 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
901 READWRITE(this->nVersion);
902 nVersion = this->nVersion;
903 READWRITE(hashPrevBlock);
904 READWRITE(hashMerkleRoot);
909 // ConnectBlock depends on vtx following header to generate CDiskTxPos
910 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
913 READWRITE(vchBlockSig);
917 const_cast<CBlock*>(this)->vtx.clear();
918 const_cast<CBlock*>(this)->vchBlockSig.clear();
924 nVersion = CBlock::CURRENT_VERSION;
941 uint256 GetHash() const
943 return scrypt_blockhash((const uint8_t*)&nVersion);
946 int64_t GetBlockTime() const
948 return (int64_t)nTime;
951 void UpdateTime(const CBlockIndex* pindexPrev);
953 // ppcoin: entropy bit for stake modifier if chosen by modifier
954 unsigned int GetStakeEntropyBit(unsigned int nHeight) const
956 // Protocol switch to support p2pool at novacoin block #9689
957 if (nHeight >= 9689 || fTestNet)
959 // Take last bit of block hash as entropy bit
960 unsigned int nEntropyBit = (GetHash().Get64()) & (uint64_t)1;
961 if (fDebug && GetBoolArg("-printstakemodifier"))
962 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
966 // Before novacoin block #9689 - get from pregenerated table
967 int nBitNum = nHeight & 0xFF;
968 int nItemNum = nHeight / 0xFF;
970 unsigned int nEntropyBit = (unsigned int) ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get64();
971 if (fDebug && GetBoolArg("-printstakemodifier"))
972 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%d nEntropyBit=%u\n", nHeight, nEntropyBit);
976 // ppcoin: two types of block: proof-of-work or proof-of-stake
977 bool IsProofOfStake() const
979 return (vtx.size() > 1 && vtx[1].IsCoinStake());
982 bool IsProofOfWork() const
984 return !IsProofOfStake();
987 std::pair<COutPoint, unsigned int> GetProofOfStake() const
989 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
992 // ppcoin: get max transaction timestamp
993 int64_t GetMaxTransactionTime() const
995 int64_t maxTransactionTime = 0;
996 for (const CTransaction& tx : vtx)
997 maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
998 return maxTransactionTime;
1001 uint256 BuildMerkleTree() const
1003 vMerkleTree.clear();
1004 for (const CTransaction& tx : vtx)
1005 vMerkleTree.push_back(tx.GetHash());
1007 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1009 for (int i = 0; i < nSize; i += 2)
1011 int i2 = std::min(i+1, nSize-1);
1012 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1013 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1017 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1020 std::vector<uint256> GetMerkleBranch(int nIndex) const
1022 if (vMerkleTree.empty())
1024 std::vector<uint256> vMerkleBranch;
1026 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1028 int i = std::min(nIndex^1, nSize-1);
1029 vMerkleBranch.push_back(vMerkleTree[j+i]);
1033 return vMerkleBranch;
1036 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1040 for (const uint256& otherside : vMerkleBranch)
1043 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1045 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1052 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1054 // Open history file to append
1055 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1057 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1059 // Write index header
1060 unsigned int nSize = fileout.GetSerializeSize(*this);
1061 fileout << FLATDATA(pchMessageStart) << nSize;
1064 long fileOutPos = ftell(fileout);
1066 return error("CBlock::WriteToDisk() : ftell failed");
1067 nBlockPosRet = fileOutPos;
1070 // Flush stdio buffers and commit to disk before returning
1072 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1073 FileCommit(fileout);
1078 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1082 // Open history file to read
1083 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1085 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1086 if (!fReadTransactions)
1087 filein.nType |= SER_BLOCKHEADERONLY;
1093 catch (const std::exception&) {
1094 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1098 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1099 return error("CBlock::ReadFromDisk() : errors in block header");
1108 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
1109 GetHash().ToString().c_str(),
1111 hashPrevBlock.ToString().c_str(),
1112 hashMerkleRoot.ToString().c_str(),
1113 nTime, nBits, nNonce,
1115 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1116 for (unsigned int i = 0; i < vtx.size(); i++)
1121 printf(" vMerkleTree: ");
1122 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1123 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1128 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1129 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1130 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1131 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1132 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1133 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1135 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1136 bool CheckBlockSignature() const;
1139 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1147 /** The block chain is a tree shaped structure starting with the
1148 * genesis block at the root, with each block potentially having multiple
1149 * candidates to be the next block. pprev and pnext link a path through the
1150 * main/longest chain. A blockindex may have multiple pprev pointing back
1151 * to it, but pnext will only point forward to the longest branch, or will
1152 * be null if the block is not part of the longest chain.
1157 const uint256* phashBlock;
1162 uint256 nChainTrust; // ppcoin: trust score of block chain
1166 int64_t nMoneySupply;
1168 uint32_t nFlags; // ppcoin: block index flags
1171 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1172 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1173 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
1176 uint64_t nStakeModifier; // hash modifier for proof-of-stake
1177 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
1179 // proof-of-stake specific fields
1180 COutPoint prevoutStake;
1181 uint32_t nStakeTime;
1182 uint256 hashProofOfStake;
1186 uint256 hashMerkleRoot;
1204 nStakeModifierChecksum = 0;
1205 hashProofOfStake = 0;
1206 prevoutStake.SetNull();
1216 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1222 nBlockPos = nBlockPosIn;
1229 nStakeModifierChecksum = 0;
1230 hashProofOfStake = 0;
1231 if (block.IsProofOfStake())
1234 prevoutStake = block.vtx[1].vin[0].prevout;
1235 nStakeTime = block.vtx[1].nTime;
1239 prevoutStake.SetNull();
1243 nVersion = block.nVersion;
1244 hashMerkleRoot = block.hashMerkleRoot;
1245 nTime = block.nTime;
1246 nBits = block.nBits;
1247 nNonce = block.nNonce;
1250 CBlock GetBlockHeader() const
1253 block.nVersion = nVersion;
1255 block.hashPrevBlock = pprev->GetBlockHash();
1256 block.hashMerkleRoot = hashMerkleRoot;
1257 block.nTime = nTime;
1258 block.nBits = nBits;
1259 block.nNonce = nNonce;
1263 uint256 GetBlockHash() const
1268 int64_t GetBlockTime() const
1270 return (int64_t)nTime;
1273 uint256 GetBlockTrust() const;
1275 bool IsInMainChain() const
1277 return (pnext || this == pindexBest);
1280 bool CheckIndex() const
1285 enum { nMedianTimeSpan=11 };
1287 int64_t GetMedianTimePast() const
1289 int64_t pmedian[nMedianTimeSpan];
1290 int64_t* pbegin = &pmedian[nMedianTimeSpan];
1291 int64_t* pend = &pmedian[nMedianTimeSpan];
1293 const CBlockIndex* pindex = this;
1294 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1295 *(--pbegin) = pindex->GetBlockTime();
1297 std::sort(pbegin, pend);
1298 return pbegin[(pend - pbegin)/2];
1301 int64_t GetMedianTime() const
1303 const CBlockIndex* pindex = this;
1304 for (int i = 0; i < nMedianTimeSpan/2; i++)
1307 return GetBlockTime();
1308 pindex = pindex->pnext;
1310 return pindex->GetMedianTimePast();
1314 * Returns true if there are nRequired or more blocks of minVersion or above
1315 * in the last nToCheck blocks, starting at pstart and going backwards.
1317 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1318 unsigned int nRequired, unsigned int nToCheck);
1321 bool IsProofOfWork() const
1323 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1326 bool IsProofOfStake() const
1328 return (nFlags & BLOCK_PROOF_OF_STAKE);
1331 void SetProofOfStake()
1333 nFlags |= BLOCK_PROOF_OF_STAKE;
1336 unsigned int GetStakeEntropyBit() const
1338 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1341 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1343 if (nEntropyBit > 1)
1345 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1349 bool GeneratedStakeModifier() const
1351 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
1354 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
1356 nStakeModifier = nModifier;
1357 if (fGeneratedStakeModifier)
1358 nFlags |= BLOCK_STAKE_MODIFIER;
1361 std::string ToString() const
1363 return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRIx64 ", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1364 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
1365 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1366 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1367 nStakeModifier, nStakeModifierChecksum,
1368 hashProofOfStake.ToString().c_str(),
1369 prevoutStake.ToString().c_str(), nStakeTime,
1370 hashMerkleRoot.ToString().c_str(),
1371 GetBlockHash().ToString().c_str());
1376 printf("%s\n", ToString().c_str());
1382 /** Used to marshal pointers into hashes for db storage. */
1383 class CDiskBlockIndex : public CBlockIndex
1399 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1401 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1402 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1407 if (!(nType & SER_GETHASH))
1408 READWRITE(nVersion);
1410 READWRITE(hashNext);
1412 READWRITE(nBlockPos);
1415 READWRITE(nMoneySupply);
1417 READWRITE(nStakeModifier);
1418 if (IsProofOfStake())
1420 READWRITE(prevoutStake);
1421 READWRITE(nStakeTime);
1422 READWRITE(hashProofOfStake);
1426 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1427 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1428 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1432 READWRITE(this->nVersion);
1433 READWRITE(hashPrev);
1434 READWRITE(hashMerkleRoot);
1438 READWRITE(blockHash);
1441 uint256 GetBlockHash() const
1443 if (fUseFastIndex && (nTime < GetAdjustedTime() - nOneDay) && blockHash != 0)
1447 block.nVersion = nVersion;
1448 block.hashPrevBlock = hashPrev;
1449 block.hashMerkleRoot = hashMerkleRoot;
1450 block.nTime = nTime;
1451 block.nBits = nBits;
1452 block.nNonce = nNonce;
1454 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1459 std::string ToString() const
1461 std::string str = "CDiskBlockIndex(";
1462 str += CBlockIndex::ToString();
1463 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1464 GetBlockHash().ToString().c_str(),
1465 hashPrev.ToString().c_str(),
1466 hashNext.ToString().c_str());
1472 printf("%s\n", ToString().c_str());
1483 /** Describes a place in the block chain to another node such that if the
1484 * other node doesn't have the same branch, it can find a recent common trunk.
1485 * The further back it is, the further before the fork it may be.
1490 std::vector<uint256> vHave;
1497 explicit CBlockLocator(const CBlockIndex* pindex)
1502 explicit CBlockLocator(uint256 hashBlock)
1504 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1505 if (mi != mapBlockIndex.end())
1509 CBlockLocator(const std::vector<uint256>& vHaveIn)
1516 if (!(nType & SER_GETHASH))
1517 READWRITE(nVersion);
1528 return vHave.empty();
1531 void Set(const CBlockIndex* pindex)
1537 vHave.push_back(pindex->GetBlockHash());
1539 // Exponentially larger steps back
1540 for (int i = 0; pindex && i < nStep; i++)
1541 pindex = pindex->pprev;
1542 if (vHave.size() > 10)
1545 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1548 int GetDistanceBack()
1550 // Retrace how far back it was in the sender's branch
1553 for (const uint256& hash : vHave)
1555 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1556 if (mi != mapBlockIndex.end())
1558 CBlockIndex* pindex = (*mi).second;
1559 if (pindex->IsInMainChain())
1569 CBlockIndex* GetBlockIndex()
1571 // Find the first block the caller has in the main chain
1572 for (const uint256& hash : vHave)
1574 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1575 if (mi != mapBlockIndex.end())
1577 CBlockIndex* pindex = (*mi).second;
1578 if (pindex->IsInMainChain())
1582 return pindexGenesisBlock;
1585 uint256 GetBlockHash()
1587 // Find the first block the caller has in the main chain
1588 for (const uint256& hash : vHave)
1590 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1591 if (mi != mapBlockIndex.end())
1593 CBlockIndex* pindex = (*mi).second;
1594 if (pindex->IsInMainChain())
1598 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1603 CBlockIndex* pindex = GetBlockIndex();
1606 return pindex->nHeight;
1620 mutable CCriticalSection cs;
1621 std::map<uint256, CTransaction> mapTx;
1622 std::map<COutPoint, CInPoint> mapNextTx;
1624 bool accept(CTxDB& txdb, CTransaction &tx,
1625 bool fCheckInputs, bool* pfMissingInputs);
1626 bool addUnchecked(const uint256& hash, CTransaction &tx);
1627 bool remove(CTransaction &tx);
1629 void queryHashes(std::vector<uint256>& vtxid);
1634 return mapTx.size();
1637 bool exists(uint256 hash)
1639 return (mapTx.count(hash) != 0);
1642 CTransaction& lookup(uint256 hash)
1648 extern CTxMemPool mempool;