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.
8 #include "timestamps.h"
34 static const unsigned int MAX_BLOCK_SIZE = 1000000;
35 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
36 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
37 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
38 static const unsigned int MAX_INV_SZ = 50000;
40 static const int64_t MIN_TX_FEE = CENT/10;
41 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
43 static const int64_t MAX_MONEY = std::numeric_limits<int64_t>::max();
44 static const int64_t MAX_MINT_PROOF_OF_WORK = 100 * COIN;
45 static const int64_t MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
46 static const int64_t MIN_TXOUT_AMOUNT = CENT/100;
49 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
50 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
51 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
52 // Maximum number of script-checking threads allowed
53 static const int MAX_SCRIPTCHECK_THREADS = 16;
55 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
56 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
58 inline int64_t PastDrift(int64_t nTime) { return nTime - 2 * nOneHour; } // up to 2 hours from the past
59 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
61 extern CScript COINBASE_FLAGS;
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern unsigned int nNodeLifespan;
67 extern unsigned int nStakeMinAge;
68 extern int nCoinbaseMaturity;
69 extern int nBestHeight;
70 extern uint256 nBestChainTrust;
71 extern uint256 nBestInvalidTrust;
72 extern uint256 hashBestChain;
73 extern CBlockIndex* pindexBest;
74 extern unsigned int nTransactionsUpdated;
75 extern uint64_t nLastBlockTx;
76 extern uint64_t nLastBlockSize;
77 extern uint32_t nLastCoinStakeSearchInterval;
78 extern const std::string strMessageMagic;
79 extern int64_t nTimeBestReceived;
80 extern CCriticalSection cs_setpwalletRegistered;
81 extern std::set<CWallet*> setpwalletRegistered;
82 extern unsigned char pchMessageStart[4];
83 extern std::map<uint256, CBlock*> mapOrphanBlocks;
86 extern int64_t nTransactionFee;
87 extern int64_t nMinimumInputValue;
88 extern bool fUseFastIndex;
89 extern int nScriptCheckThreads;
90 extern const uint256 entropyStore[38];
92 // Minimum disk space required - used in CheckDiskSpace()
93 static const uint64_t nMinDiskSpace = 52428800;
100 void RegisterWallet(CWallet* pwalletIn);
101 void UnregisterWallet(CWallet* pwalletIn);
102 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
103 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
104 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
105 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
106 FILE* AppendBlockFile(unsigned int& nFileRet);
108 void UnloadBlockIndex();
109 bool LoadBlockIndex(bool fAllowNew=true);
110 void PrintBlockTree();
111 CBlockIndex* FindBlockByHeight(int nHeight);
112 bool ProcessMessages(CNode* pfrom);
113 bool SendMessages(CNode* pto);
114 bool LoadExternalBlockFile(FILE* fileIn);
116 // Run an instance of the script checking thread
117 void ThreadScriptCheck(void* parg);
118 // Stop the script checking threads
119 void ThreadScriptCheckQuit();
121 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
122 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
123 int64_t GetProofOfWorkReward(unsigned int nBits);
124 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
125 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
126 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
127 int GetNumBlocksOfPeers();
128 bool IsInitialBlockDownload();
129 std::string GetWarnings(std::string strFor);
130 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
131 uint256 WantedByOrphan(const CBlock* pblockOrphan);
132 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
133 void ResendWalletTransactions(bool fForceResend=false);
135 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
140 /** Position on disk for a particular transaction. */
153 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
156 nBlockPos = nBlockPosIn;
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
161 void SetNull() { nFile = std::numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
162 bool IsNull() const { return (nFile == std::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 std::string ToString() const
182 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", 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, unsigned int nIn) { ptx = ptxIn; n = nIn; }
202 void SetNull() { ptx = NULL; n = std::numeric_limits<uint32_t>::max(); }
203 bool IsNull() const { return (ptx == NULL && n == std::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, unsigned int nIn) { hash = hashIn; n = nIn; }
217 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
218 void SetNull() { hash = 0; n = std::numeric_limits<uint32_t>::max(); }
219 bool IsNull() const { return (hash == 0 && n == std::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 std::string ToString() const
238 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
243 printf("%s\n", ToString().c_str());
250 /** An input of a transaction. It contains the location of the previous
251 * transaction's output that it claims and a signature that matches the
252 * output's public key.
263 nSequence = std::numeric_limits<unsigned int>::max();
266 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
269 scriptSig = scriptSigIn;
270 nSequence = nSequenceIn;
273 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
275 prevout = COutPoint(hashPrevTx, nOut);
276 scriptSig = scriptSigIn;
277 nSequence = nSequenceIn;
283 READWRITE(scriptSig);
284 READWRITE(nSequence);
289 return (nSequence == std::numeric_limits<unsigned int>::max());
292 friend bool operator==(const CTxIn& a, const CTxIn& b)
294 return (a.prevout == b.prevout &&
295 a.scriptSig == b.scriptSig &&
296 a.nSequence == b.nSequence);
299 friend bool operator!=(const CTxIn& a, const CTxIn& b)
304 std::string ToStringShort() const
306 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
309 std::string ToString() const
313 str += prevout.ToString();
314 if (prevout.IsNull())
315 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
317 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
318 if (nSequence != std::numeric_limits<unsigned int>::max())
319 str += strprintf(", nSequence=%u", nSequence);
326 printf("%s\n", ToString().c_str());
333 /** An output of a transaction. It contains the public key that the next input
334 * must be able to sign with to claim it.
340 CScript scriptPubKey;
347 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
350 scriptPubKey = scriptPubKeyIn;
356 READWRITE(scriptPubKey);
362 scriptPubKey.clear();
367 return (nValue == -1);
373 scriptPubKey.clear();
378 return (nValue == 0 && scriptPubKey.empty());
381 uint256 GetHash() const
383 return SerializeHash(*this);
386 friend bool operator==(const CTxOut& a, const CTxOut& b)
388 return (a.nValue == b.nValue &&
389 a.scriptPubKey == b.scriptPubKey);
392 friend bool operator!=(const CTxOut& a, const CTxOut& b)
397 std::string ToStringShort() const
399 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
402 std::string ToString() const
404 if (IsEmpty()) return "CTxOut(empty)";
405 if (scriptPubKey.size() < 6)
406 return "CTxOut(error)";
407 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
412 printf("%s\n", ToString().c_str());
426 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
428 /** The basic transaction that is broadcasted on the network and contained in
429 * blocks. A transaction can contain multiple inputs and outputs.
434 static const int CURRENT_VERSION=1;
437 std::vector<CTxIn> vin;
438 std::vector<CTxOut> vout;
441 // Denial-of-service detection:
443 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
452 READWRITE(this->nVersion);
453 nVersion = this->nVersion;
457 READWRITE(nLockTime);
462 nVersion = CTransaction::CURRENT_VERSION;
463 nTime = (uint32_t) GetAdjustedTime();
467 nDoS = 0; // Denial-of-service prevention
472 return (vin.empty() && vout.empty());
475 uint256 GetHash() const
477 return SerializeHash(*this);
480 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const
482 // Time based nLockTime implemented in 0.1.6
485 if (nBlockHeight == 0)
486 nBlockHeight = nBestHeight;
488 nBlockTime = GetAdjustedTime();
489 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
491 for (const CTxIn& txin : vin)
497 bool IsNewerThan(const CTransaction& old) const
499 if (vin.size() != old.vin.size())
501 for (unsigned int i = 0; i < vin.size(); i++)
502 if (vin[i].prevout != old.vin[i].prevout)
506 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
507 for (unsigned int i = 0; i < vin.size(); i++)
509 if (vin[i].nSequence != old.vin[i].nSequence)
511 if (vin[i].nSequence <= nLowest)
514 nLowest = vin[i].nSequence;
516 if (old.vin[i].nSequence < nLowest)
519 nLowest = old.vin[i].nSequence;
526 bool IsCoinBase() const
528 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
531 bool IsCoinStake() const
533 // ppcoin: the coin stake transaction is marked with the first output empty
534 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
537 /** Check for standard transaction types
538 @return True if all outputs (scriptPubKeys) use only standard transaction forms
540 bool IsStandard(std::string& strReason) const;
541 bool IsStandard() const
543 std::string strReason;
544 return IsStandard(strReason);
547 /** Check for standard transaction types
548 @param[in] mapInputs Map of previous transactions that have outputs we're spending
549 @return True if all inputs (scriptSigs) use only standard transaction forms
550 @see CTransaction::FetchInputs
552 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
554 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
555 @return number of sigops this transaction's outputs will produce when spent
556 @see CTransaction::FetchInputs
558 unsigned int GetLegacySigOpCount() const;
560 /** Count ECDSA signature operations in pay-to-script-hash inputs.
562 @param[in] mapInputs Map of previous transactions that have outputs we're spending
563 @return maximum number of sigops required to validate this transaction's inputs
564 @see CTransaction::FetchInputs
566 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
568 /** Amount of bitcoins spent by this transaction.
569 @return sum of all outputs (note: does not include fees)
571 int64_t GetValueOut() const
573 int64_t nValueOut = 0;
574 for (const CTxOut& txout : vout)
576 nValueOut += txout.nValue;
577 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
578 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
583 /** Amount of bitcoins coming in to this transaction
584 Note that lightweight clients may not know anything besides the hash of previous transactions,
585 so may not be able to calculate this.
587 @param[in] mapInputs Map of previous transactions that have outputs we're spending
588 @return Sum of value of all inputs (scriptSigs)
589 @see CTransaction::FetchInputs
591 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
593 static bool AllowFree(double dPriority)
595 // Large (in bytes) low-priority (new, small-coin) transactions
597 return dPriority > COIN * 144 / 250;
600 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
602 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
604 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
606 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
609 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
610 return error("CTransaction::ReadFromDisk() : fseek failed");
615 catch (const std::exception&) {
616 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
619 // Return file pointer
622 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
623 return error("CTransaction::ReadFromDisk() : second fseek failed");
624 *pfileRet = filein.release();
629 friend bool operator==(const CTransaction& a, const CTransaction& b)
631 return (a.nVersion == b.nVersion &&
632 a.nTime == b.nTime &&
635 a.nLockTime == b.nLockTime);
638 friend bool operator!=(const CTransaction& a, const CTransaction& b)
643 std::string ToStringShort() const
646 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
650 std::string ToString() const
653 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
654 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
655 GetHash().ToString().substr(0,10).c_str(),
661 for (unsigned int i = 0; i < vin.size(); i++)
662 str += " " + vin[i].ToString() + "\n";
663 for (unsigned int i = 0; i < vout.size(); i++)
664 str += " " + vout[i].ToString() + "\n";
670 printf("%s", ToString().c_str());
674 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
675 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
676 bool ReadFromDisk(COutPoint prevout);
677 bool DisconnectInputs(CTxDB& txdb);
679 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
681 @param[in] txdb Transaction database
682 @param[in] mapTestPool List of pending changes to the transaction index database
683 @param[in] fBlock True if being called to add a new best-block to the chain
684 @param[in] fMiner True if being called by CreateNewBlock
685 @param[out] inputsRet Pointers to this transaction's inputs
686 @param[out] fInvalid returns true if transaction is invalid
687 @return Returns true if all inputs are in txdb or mapTestPool
689 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
690 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
692 /** Sanity check previous transactions, then, if all checks succeed,
693 mark them as spent by this transaction.
695 @param[in] inputs Previous transactions (from FetchInputs)
696 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
697 @param[in] posThisTx Position of this transaction on disk
698 @param[in] pindexBlock
699 @param[in] fBlock true if called from ConnectBlock
700 @param[in] fMiner true if called from CreateNewBlock
701 @param[in] fScriptChecks enable scripts validation?
702 @param[in] flags STRICT_FLAGS script validation flags
703 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
704 @return Returns true if all checks succeed
706 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
707 bool fBlock, bool fMiner, bool fScriptChecks=true,
708 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
709 bool ClientConnectInputs();
710 bool CheckTransaction() const;
711 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
712 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
715 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
718 /** Closure representing one script verification
719 * Note that this stores references to the spending transaction */
723 CScript scriptPubKey;
724 const CTransaction *ptxTo;
731 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
732 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
733 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
735 bool operator()() const;
737 void swap(CScriptCheck &check) {
738 scriptPubKey.swap(check.scriptPubKey);
739 std::swap(ptxTo, check.ptxTo);
740 std::swap(nIn, check.nIn);
741 std::swap(nFlags, check.nFlags);
742 std::swap(nHashType, check.nHashType);
749 /** A transaction with a merkle branch linking it to the block chain. */
750 class CMerkleTx : public CTransaction
754 std::vector<uint256> vMerkleBranch;
758 mutable bool fMerkleVerified;
766 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
775 fMerkleVerified = false;
781 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
782 nVersion = this->nVersion;
783 READWRITE(hashBlock);
784 READWRITE(vMerkleBranch);
789 int SetMerkleBranch(const CBlock* pblock=NULL);
790 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
791 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
792 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
793 int GetBlocksToMaturity() const;
794 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
795 bool AcceptToMemoryPool();
801 /** A txdb record that contains the disk location of a transaction and the
802 * locations of transactions that spend its outputs. vSpent is really only
803 * used as a flag, but having the location is very helpful for debugging.
809 std::vector<CDiskTxPos> vSpent;
816 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
819 vSpent.resize(nOutputs);
824 if (!(nType & SER_GETHASH))
841 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
843 return (a.pos == b.pos &&
844 a.vSpent == b.vSpent);
847 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
851 int GetDepthInMainChain() const;
856 /** Nodes collect new transactions into a block, hash them into a hash tree,
857 * and scan through nonce values to make the block's hash satisfy proof-of-work
858 * requirements. When they solve the proof-of-work, they broadcast the block
859 * to everyone and the block is added to the block chain. The first transaction
860 * in the block is a special one that creates a new coin owned by the creator
863 * Blocks are appended to blk0001.dat files on disk. Their location on disk
864 * is indexed by CBlockIndex objects in memory.
870 static const int CURRENT_VERSION=6;
872 uint256 hashPrevBlock;
873 uint256 hashMerkleRoot;
879 std::vector<CTransaction> vtx;
881 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
882 std::vector<unsigned char> vchBlockSig;
885 mutable std::vector<uint256> vMerkleTree;
887 // Denial-of-service detection:
889 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
898 READWRITE(this->nVersion);
899 nVersion = this->nVersion;
900 READWRITE(hashPrevBlock);
901 READWRITE(hashMerkleRoot);
906 // ConnectBlock depends on vtx following header to generate CDiskTxPos
907 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
910 READWRITE(vchBlockSig);
914 const_cast<CBlock*>(this)->vtx.clear();
915 const_cast<CBlock*>(this)->vchBlockSig.clear();
921 nVersion = CBlock::CURRENT_VERSION;
938 uint256 GetHash() const
940 return scrypt_blockhash((const uint8_t*)&nVersion);
943 int64_t GetBlockTime() const
945 return (int64_t)nTime;
948 void UpdateTime(const CBlockIndex* pindexPrev);
950 // ppcoin: entropy bit for stake modifier if chosen by modifier
951 unsigned int GetStakeEntropyBit(unsigned int nHeight) const
953 // Protocol switch to support p2pool at novacoin block #9689
954 if (nHeight >= 9689 || fTestNet)
956 // Take last bit of block hash as entropy bit
957 unsigned int nEntropyBit = (GetHash().Get64()) & (uint64_t)1;
958 if (fDebug && GetBoolArg("-printstakemodifier"))
959 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
963 // Before novacoin block #9689 - get from pregenerated table
964 int nBitNum = nHeight & 0xFF;
965 int nItemNum = nHeight / 0xFF;
967 unsigned int nEntropyBit = (unsigned int) ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get64();
968 if (fDebug && GetBoolArg("-printstakemodifier"))
969 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%d nEntropyBit=%u\n", nHeight, nEntropyBit);
973 // ppcoin: two types of block: proof-of-work or proof-of-stake
974 bool IsProofOfStake() const
976 return (vtx.size() > 1 && vtx[1].IsCoinStake());
979 bool IsProofOfWork() const
981 return !IsProofOfStake();
984 std::pair<COutPoint, unsigned int> GetProofOfStake() const
986 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
989 // ppcoin: get max transaction timestamp
990 int64_t GetMaxTransactionTime() const
992 int64_t maxTransactionTime = 0;
993 for (const CTransaction& tx : vtx)
994 maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
995 return maxTransactionTime;
998 uint256 BuildMerkleTree() const
1000 vMerkleTree.clear();
1001 for (const CTransaction& tx : vtx)
1002 vMerkleTree.push_back(tx.GetHash());
1004 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1006 for (int i = 0; i < nSize; i += 2)
1008 int i2 = std::min(i+1, nSize-1);
1009 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1010 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1014 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1017 std::vector<uint256> GetMerkleBranch(int nIndex) const
1019 if (vMerkleTree.empty())
1021 std::vector<uint256> vMerkleBranch;
1023 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1025 int i = std::min(nIndex^1, nSize-1);
1026 vMerkleBranch.push_back(vMerkleTree[j+i]);
1030 return vMerkleBranch;
1033 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1037 for (const uint256& otherside : vMerkleBranch)
1040 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1042 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1049 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1051 // Open history file to append
1052 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1054 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1056 // Write index header
1057 unsigned int nSize = fileout.GetSerializeSize(*this);
1058 fileout << FLATDATA(pchMessageStart) << nSize;
1061 long fileOutPos = ftell(fileout);
1063 return error("CBlock::WriteToDisk() : ftell failed");
1064 nBlockPosRet = fileOutPos;
1067 // Flush stdio buffers and commit to disk before returning
1069 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1070 FileCommit(fileout);
1075 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1079 // Open history file to read
1080 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1082 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1083 if (!fReadTransactions)
1084 filein.nType |= SER_BLOCKHEADERONLY;
1090 catch (const std::exception&) {
1091 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1095 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1096 return error("CBlock::ReadFromDisk() : errors in block header");
1105 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
1106 GetHash().ToString().c_str(),
1108 hashPrevBlock.ToString().c_str(),
1109 hashMerkleRoot.ToString().c_str(),
1110 nTime, nBits, nNonce,
1112 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1113 for (unsigned int i = 0; i < vtx.size(); i++)
1118 printf(" vMerkleTree: ");
1119 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1120 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1125 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1126 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1127 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1128 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1129 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1130 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1132 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1133 bool CheckBlockSignature() const;
1136 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1144 /** The block chain is a tree shaped structure starting with the
1145 * genesis block at the root, with each block potentially having multiple
1146 * candidates to be the next block. pprev and pnext link a path through the
1147 * main/longest chain. A blockindex may have multiple pprev pointing back
1148 * to it, but pnext will only point forward to the longest branch, or will
1149 * be null if the block is not part of the longest chain.
1154 const uint256* phashBlock;
1159 uint256 nChainTrust; // ppcoin: trust score of block chain
1163 int64_t nMoneySupply;
1165 uint32_t nFlags; // ppcoin: block index flags
1168 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1169 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1170 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
1173 uint64_t nStakeModifier; // hash modifier for proof-of-stake
1174 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
1176 // proof-of-stake specific fields
1177 COutPoint prevoutStake;
1178 uint32_t nStakeTime;
1179 uint256 hashProofOfStake;
1183 uint256 hashMerkleRoot;
1201 nStakeModifierChecksum = 0;
1202 hashProofOfStake = 0;
1203 prevoutStake.SetNull();
1213 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1219 nBlockPos = nBlockPosIn;
1226 nStakeModifierChecksum = 0;
1227 hashProofOfStake = 0;
1228 if (block.IsProofOfStake())
1231 prevoutStake = block.vtx[1].vin[0].prevout;
1232 nStakeTime = block.vtx[1].nTime;
1236 prevoutStake.SetNull();
1240 nVersion = block.nVersion;
1241 hashMerkleRoot = block.hashMerkleRoot;
1242 nTime = block.nTime;
1243 nBits = block.nBits;
1244 nNonce = block.nNonce;
1247 CBlock GetBlockHeader() const
1250 block.nVersion = nVersion;
1252 block.hashPrevBlock = pprev->GetBlockHash();
1253 block.hashMerkleRoot = hashMerkleRoot;
1254 block.nTime = nTime;
1255 block.nBits = nBits;
1256 block.nNonce = nNonce;
1260 uint256 GetBlockHash() const
1265 int64_t GetBlockTime() const
1267 return (int64_t)nTime;
1270 uint256 GetBlockTrust() const;
1272 bool IsInMainChain() const
1274 return (pnext || this == pindexBest);
1277 bool CheckIndex() const
1282 enum { nMedianTimeSpan=11 };
1284 int64_t GetMedianTimePast() const
1286 int64_t pmedian[nMedianTimeSpan];
1287 int64_t* pbegin = &pmedian[nMedianTimeSpan];
1288 int64_t* pend = &pmedian[nMedianTimeSpan];
1290 const CBlockIndex* pindex = this;
1291 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1292 *(--pbegin) = pindex->GetBlockTime();
1294 std::sort(pbegin, pend);
1295 return pbegin[(pend - pbegin)/2];
1298 int64_t GetMedianTime() const
1300 const CBlockIndex* pindex = this;
1301 for (int i = 0; i < nMedianTimeSpan/2; i++)
1304 return GetBlockTime();
1305 pindex = pindex->pnext;
1307 return pindex->GetMedianTimePast();
1311 * Returns true if there are nRequired or more blocks of minVersion or above
1312 * in the last nToCheck blocks, starting at pstart and going backwards.
1314 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1315 unsigned int nRequired, unsigned int nToCheck);
1318 bool IsProofOfWork() const
1320 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1323 bool IsProofOfStake() const
1325 return (nFlags & BLOCK_PROOF_OF_STAKE);
1328 void SetProofOfStake()
1330 nFlags |= BLOCK_PROOF_OF_STAKE;
1333 unsigned int GetStakeEntropyBit() const
1335 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1338 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1340 if (nEntropyBit > 1)
1342 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1346 bool GeneratedStakeModifier() const
1348 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
1351 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
1353 nStakeModifier = nModifier;
1354 if (fGeneratedStakeModifier)
1355 nFlags |= BLOCK_STAKE_MODIFIER;
1358 std::string ToString() const
1360 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)",
1361 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
1362 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1363 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1364 nStakeModifier, nStakeModifierChecksum,
1365 hashProofOfStake.ToString().c_str(),
1366 prevoutStake.ToString().c_str(), nStakeTime,
1367 hashMerkleRoot.ToString().c_str(),
1368 GetBlockHash().ToString().c_str());
1373 printf("%s\n", ToString().c_str());
1379 /** Used to marshal pointers into hashes for db storage. */
1380 class CDiskBlockIndex : public CBlockIndex
1396 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1398 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1399 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1404 if (!(nType & SER_GETHASH))
1405 READWRITE(nVersion);
1407 READWRITE(hashNext);
1409 READWRITE(nBlockPos);
1412 READWRITE(nMoneySupply);
1414 READWRITE(nStakeModifier);
1415 if (IsProofOfStake())
1417 READWRITE(prevoutStake);
1418 READWRITE(nStakeTime);
1419 READWRITE(hashProofOfStake);
1423 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1424 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1425 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1429 READWRITE(this->nVersion);
1430 READWRITE(hashPrev);
1431 READWRITE(hashMerkleRoot);
1435 READWRITE(blockHash);
1438 uint256 GetBlockHash() const
1440 if (fUseFastIndex && (nTime < GetAdjustedTime() - nOneDay) && blockHash != 0)
1444 block.nVersion = nVersion;
1445 block.hashPrevBlock = hashPrev;
1446 block.hashMerkleRoot = hashMerkleRoot;
1447 block.nTime = nTime;
1448 block.nBits = nBits;
1449 block.nNonce = nNonce;
1451 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1456 std::string ToString() const
1458 std::string str = "CDiskBlockIndex(";
1459 str += CBlockIndex::ToString();
1460 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1461 GetBlockHash().ToString().c_str(),
1462 hashPrev.ToString().c_str(),
1463 hashNext.ToString().c_str());
1469 printf("%s\n", ToString().c_str());
1480 /** Describes a place in the block chain to another node such that if the
1481 * other node doesn't have the same branch, it can find a recent common trunk.
1482 * The further back it is, the further before the fork it may be.
1487 std::vector<uint256> vHave;
1494 explicit CBlockLocator(const CBlockIndex* pindex)
1499 explicit CBlockLocator(uint256 hashBlock)
1501 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1502 if (mi != mapBlockIndex.end())
1506 CBlockLocator(const std::vector<uint256>& vHaveIn)
1513 if (!(nType & SER_GETHASH))
1514 READWRITE(nVersion);
1525 return vHave.empty();
1528 void Set(const CBlockIndex* pindex)
1534 vHave.push_back(pindex->GetBlockHash());
1536 // Exponentially larger steps back
1537 for (int i = 0; pindex && i < nStep; i++)
1538 pindex = pindex->pprev;
1539 if (vHave.size() > 10)
1542 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1545 int GetDistanceBack()
1547 // Retrace how far back it was in the sender's branch
1550 for (const uint256& hash : vHave)
1552 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1553 if (mi != mapBlockIndex.end())
1555 CBlockIndex* pindex = (*mi).second;
1556 if (pindex->IsInMainChain())
1566 CBlockIndex* GetBlockIndex()
1568 // Find the first block the caller has in the main chain
1569 for (const uint256& hash : vHave)
1571 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1572 if (mi != mapBlockIndex.end())
1574 CBlockIndex* pindex = (*mi).second;
1575 if (pindex->IsInMainChain())
1579 return pindexGenesisBlock;
1582 uint256 GetBlockHash()
1584 // Find the first block the caller has in the main chain
1585 for (const uint256& hash : vHave)
1587 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1588 if (mi != mapBlockIndex.end())
1590 CBlockIndex* pindex = (*mi).second;
1591 if (pindex->IsInMainChain())
1595 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1600 CBlockIndex* pindex = GetBlockIndex();
1603 return pindex->nHeight;
1617 mutable CCriticalSection cs;
1618 std::map<uint256, CTransaction> mapTx;
1619 std::map<COutPoint, CInPoint> mapNextTx;
1621 bool accept(CTxDB& txdb, CTransaction &tx,
1622 bool fCheckInputs, bool* pfMissingInputs);
1623 bool addUnchecked(const uint256& hash, CTransaction &tx);
1624 bool remove(CTransaction &tx);
1626 void queryHashes(std::vector<uint256>& vtxid);
1631 return mapTx.size();
1634 bool exists(uint256 hash)
1636 return (mapTx.count(hash) != 0);
1639 CTransaction& lookup(uint256 hash)
1645 extern CTxMemPool mempool;