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"
28 class CRequestTracker;
35 static const unsigned int MAX_BLOCK_SIZE = 1000000;
36 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
37 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
38 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
39 static const unsigned int MAX_INV_SZ = 50000;
41 static const int64_t MIN_TX_FEE = CENT/10;
42 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
44 static const int64_t MAX_MONEY = std::numeric_limits<int64_t>::max();
45 static const int64_t MAX_MINT_PROOF_OF_WORK = 100 * COIN;
46 static const int64_t MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
47 static const int64_t MIN_TXOUT_AMOUNT = CENT/100;
50 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
51 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
52 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
53 // Maximum number of script-checking threads allowed
54 static const int MAX_SCRIPTCHECK_THREADS = 16;
56 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
57 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
59 inline int64_t PastDrift(int64_t nTime) { return nTime - 2 * nOneHour; } // up to 2 hours from the past
60 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
62 extern CScript COINBASE_FLAGS;
63 extern CCriticalSection cs_main;
64 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
65 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
66 extern CBlockIndex* pindexGenesisBlock;
67 extern unsigned int nNodeLifespan;
68 extern unsigned int nStakeMinAge;
69 extern int nCoinbaseMaturity;
70 extern int nBestHeight;
71 extern uint256 nBestChainTrust;
72 extern uint256 nBestInvalidTrust;
73 extern uint256 hashBestChain;
74 extern CBlockIndex* pindexBest;
75 extern unsigned int nTransactionsUpdated;
76 extern uint64_t nLastBlockTx;
77 extern uint64_t nLastBlockSize;
78 extern uint32_t nLastCoinStakeSearchInterval;
79 extern const std::string strMessageMagic;
80 extern int64_t nTimeBestReceived;
81 extern CCriticalSection cs_setpwalletRegistered;
82 extern std::set<CWallet*> setpwalletRegistered;
83 extern unsigned char pchMessageStart[4];
84 extern std::map<uint256, CBlock*> mapOrphanBlocks;
87 extern int64_t nTransactionFee;
88 extern int64_t nMinimumInputValue;
89 extern bool fUseFastIndex;
90 extern int nScriptCheckThreads;
91 extern const uint256 entropyStore[38];
93 // Minimum disk space required - used in CheckDiskSpace()
94 static const uint64_t nMinDiskSpace = 52428800;
101 void RegisterWallet(CWallet* pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn);
103 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
104 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
105 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
106 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
107 FILE* AppendBlockFile(unsigned int& nFileRet);
109 void UnloadBlockIndex();
110 bool LoadBlockIndex(bool fAllowNew=true);
111 void PrintBlockTree();
112 CBlockIndex* FindBlockByHeight(int nHeight);
113 bool ProcessMessages(CNode* pfrom);
114 bool SendMessages(CNode* pto);
115 bool LoadExternalBlockFile(FILE* fileIn);
117 // Run an instance of the script checking thread
118 void ThreadScriptCheck(void* parg);
119 // Stop the script checking threads
120 void ThreadScriptCheckQuit();
122 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
123 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
124 int64_t GetProofOfWorkReward(unsigned int nBits);
125 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
126 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
127 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
128 int GetNumBlocksOfPeers();
129 bool IsInitialBlockDownload();
130 std::string GetWarnings(std::string strFor);
131 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
132 uint256 WantedByOrphan(const CBlock* pblockOrphan);
133 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
134 void ResendWalletTransactions(bool fForceResend=false);
136 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
141 /** Position on disk for a particular transaction. */
154 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
157 nBlockPos = nBlockPosIn;
161 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
162 void SetNull() { nFile = std::numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
163 bool IsNull() const { return (nFile == std::numeric_limits<uint32_t>::max()); }
165 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
167 return (a.nFile == b.nFile &&
168 a.nBlockPos == b.nBlockPos &&
169 a.nTxPos == b.nTxPos);
172 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
178 std::string ToString() const
183 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
188 printf("%s", ToString().c_str());
194 /** An inpoint - a combination of a transaction and an index n into its vin */
201 CInPoint() { SetNull(); }
202 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
203 void SetNull() { ptx = NULL; n = std::numeric_limits<uint32_t>::max(); }
204 bool IsNull() const { return (ptx == NULL && n == std::numeric_limits<uint32_t>::max()); }
209 /** An outpoint - a combination of a transaction hash and an index n into its vout */
216 COutPoint() { SetNull(); }
217 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
218 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
219 void SetNull() { hash = 0; n = std::numeric_limits<uint32_t>::max(); }
220 bool IsNull() const { return (hash == 0 && n == std::numeric_limits<uint32_t>::max()); }
222 friend bool operator<(const COutPoint& a, const COutPoint& b)
224 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
227 friend bool operator==(const COutPoint& a, const COutPoint& b)
229 return (a.hash == b.hash && a.n == b.n);
232 friend bool operator!=(const COutPoint& a, const COutPoint& b)
237 std::string ToString() const
239 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
244 printf("%s\n", ToString().c_str());
251 /** An input of a transaction. It contains the location of the previous
252 * transaction's output that it claims and a signature that matches the
253 * output's public key.
264 nSequence = std::numeric_limits<unsigned int>::max();
267 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
270 scriptSig = scriptSigIn;
271 nSequence = nSequenceIn;
274 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
276 prevout = COutPoint(hashPrevTx, nOut);
277 scriptSig = scriptSigIn;
278 nSequence = nSequenceIn;
284 READWRITE(scriptSig);
285 READWRITE(nSequence);
290 return (nSequence == std::numeric_limits<unsigned int>::max());
293 friend bool operator==(const CTxIn& a, const CTxIn& b)
295 return (a.prevout == b.prevout &&
296 a.scriptSig == b.scriptSig &&
297 a.nSequence == b.nSequence);
300 friend bool operator!=(const CTxIn& a, const CTxIn& b)
305 std::string ToStringShort() const
307 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
310 std::string ToString() const
314 str += prevout.ToString();
315 if (prevout.IsNull())
316 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
318 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
319 if (nSequence != std::numeric_limits<unsigned int>::max())
320 str += strprintf(", nSequence=%u", nSequence);
327 printf("%s\n", ToString().c_str());
334 /** An output of a transaction. It contains the public key that the next input
335 * must be able to sign with to claim it.
341 CScript scriptPubKey;
348 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
351 scriptPubKey = scriptPubKeyIn;
357 READWRITE(scriptPubKey);
363 scriptPubKey.clear();
368 return (nValue == -1);
374 scriptPubKey.clear();
379 return (nValue == 0 && scriptPubKey.empty());
382 uint256 GetHash() const
384 return SerializeHash(*this);
387 friend bool operator==(const CTxOut& a, const CTxOut& b)
389 return (a.nValue == b.nValue &&
390 a.scriptPubKey == b.scriptPubKey);
393 friend bool operator!=(const CTxOut& a, const CTxOut& b)
398 std::string ToStringShort() const
400 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
403 std::string ToString() const
405 if (IsEmpty()) return "CTxOut(empty)";
406 if (scriptPubKey.size() < 6)
407 return "CTxOut(error)";
408 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
413 printf("%s\n", ToString().c_str());
427 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
429 /** The basic transaction that is broadcasted on the network and contained in
430 * blocks. A transaction can contain multiple inputs and outputs.
435 static const int CURRENT_VERSION=1;
438 std::vector<CTxIn> vin;
439 std::vector<CTxOut> vout;
442 // Denial-of-service detection:
444 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
453 READWRITE(this->nVersion);
454 nVersion = this->nVersion;
458 READWRITE(nLockTime);
463 nVersion = CTransaction::CURRENT_VERSION;
464 nTime = (uint32_t) GetAdjustedTime();
468 nDoS = 0; // Denial-of-service prevention
473 return (vin.empty() && vout.empty());
476 uint256 GetHash() const
478 return SerializeHash(*this);
481 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const
483 // Time based nLockTime implemented in 0.1.6
486 if (nBlockHeight == 0)
487 nBlockHeight = nBestHeight;
489 nBlockTime = GetAdjustedTime();
490 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
492 for (const CTxIn& txin : vin)
498 bool IsNewerThan(const CTransaction& old) const
500 if (vin.size() != old.vin.size())
502 for (unsigned int i = 0; i < vin.size(); i++)
503 if (vin[i].prevout != old.vin[i].prevout)
507 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
508 for (unsigned int i = 0; i < vin.size(); i++)
510 if (vin[i].nSequence != old.vin[i].nSequence)
512 if (vin[i].nSequence <= nLowest)
515 nLowest = vin[i].nSequence;
517 if (old.vin[i].nSequence < nLowest)
520 nLowest = old.vin[i].nSequence;
527 bool IsCoinBase() const
529 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
532 bool IsCoinStake() const
534 // ppcoin: the coin stake transaction is marked with the first output empty
535 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
538 /** Check for standard transaction types
539 @return True if all outputs (scriptPubKeys) use only standard transaction forms
541 bool IsStandard(std::string& strReason) const;
542 bool IsStandard() const
544 std::string strReason;
545 return IsStandard(strReason);
548 /** Check for standard transaction types
549 @param[in] mapInputs Map of previous transactions that have outputs we're spending
550 @return True if all inputs (scriptSigs) use only standard transaction forms
551 @see CTransaction::FetchInputs
553 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
555 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
556 @return number of sigops this transaction's outputs will produce when spent
557 @see CTransaction::FetchInputs
559 unsigned int GetLegacySigOpCount() const;
561 /** Count ECDSA signature operations in pay-to-script-hash inputs.
563 @param[in] mapInputs Map of previous transactions that have outputs we're spending
564 @return maximum number of sigops required to validate this transaction's inputs
565 @see CTransaction::FetchInputs
567 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
569 /** Amount of bitcoins spent by this transaction.
570 @return sum of all outputs (note: does not include fees)
572 int64_t GetValueOut() const
574 int64_t nValueOut = 0;
575 for (const CTxOut& txout : vout)
577 nValueOut += txout.nValue;
578 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
579 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
584 /** Amount of bitcoins coming in to this transaction
585 Note that lightweight clients may not know anything besides the hash of previous transactions,
586 so may not be able to calculate this.
588 @param[in] mapInputs Map of previous transactions that have outputs we're spending
589 @return Sum of value of all inputs (scriptSigs)
590 @see CTransaction::FetchInputs
592 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
594 static bool AllowFree(double dPriority)
596 // Large (in bytes) low-priority (new, small-coin) transactions
598 return dPriority > COIN * 144 / 250;
601 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
603 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
605 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
607 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
610 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
611 return error("CTransaction::ReadFromDisk() : fseek failed");
616 catch (const std::exception&) {
617 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
620 // Return file pointer
623 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
624 return error("CTransaction::ReadFromDisk() : second fseek failed");
625 *pfileRet = filein.release();
630 friend bool operator==(const CTransaction& a, const CTransaction& b)
632 return (a.nVersion == b.nVersion &&
633 a.nTime == b.nTime &&
636 a.nLockTime == b.nLockTime);
639 friend bool operator!=(const CTransaction& a, const CTransaction& b)
644 std::string ToStringShort() const
647 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
651 std::string ToString() const
654 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
655 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
656 GetHash().ToString().substr(0,10).c_str(),
662 for (unsigned int i = 0; i < vin.size(); i++)
663 str += " " + vin[i].ToString() + "\n";
664 for (unsigned int i = 0; i < vout.size(); i++)
665 str += " " + vout[i].ToString() + "\n";
671 printf("%s", ToString().c_str());
675 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
676 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
677 bool ReadFromDisk(COutPoint prevout);
678 bool DisconnectInputs(CTxDB& txdb);
680 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
682 @param[in] txdb Transaction database
683 @param[in] mapTestPool List of pending changes to the transaction index database
684 @param[in] fBlock True if being called to add a new best-block to the chain
685 @param[in] fMiner True if being called by CreateNewBlock
686 @param[out] inputsRet Pointers to this transaction's inputs
687 @param[out] fInvalid returns true if transaction is invalid
688 @return Returns true if all inputs are in txdb or mapTestPool
690 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
691 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
693 /** Sanity check previous transactions, then, if all checks succeed,
694 mark them as spent by this transaction.
696 @param[in] inputs Previous transactions (from FetchInputs)
697 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
698 @param[in] posThisTx Position of this transaction on disk
699 @param[in] pindexBlock
700 @param[in] fBlock true if called from ConnectBlock
701 @param[in] fMiner true if called from CreateNewBlock
702 @param[in] fScriptChecks enable scripts validation?
703 @param[in] flags STRICT_FLAGS script validation flags
704 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
705 @return Returns true if all checks succeed
707 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
708 bool fBlock, bool fMiner, bool fScriptChecks=true,
709 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
710 bool ClientConnectInputs();
711 bool CheckTransaction() const;
712 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
713 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
716 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
719 /** Closure representing one script verification
720 * Note that this stores references to the spending transaction */
724 CScript scriptPubKey;
725 const CTransaction *ptxTo;
732 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
733 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
734 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
736 bool operator()() const;
738 void swap(CScriptCheck &check) {
739 scriptPubKey.swap(check.scriptPubKey);
740 std::swap(ptxTo, check.ptxTo);
741 std::swap(nIn, check.nIn);
742 std::swap(nFlags, check.nFlags);
743 std::swap(nHashType, check.nHashType);
750 /** A transaction with a merkle branch linking it to the block chain. */
751 class CMerkleTx : public CTransaction
755 std::vector<uint256> vMerkleBranch;
759 mutable bool fMerkleVerified;
767 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
776 fMerkleVerified = false;
782 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
783 nVersion = this->nVersion;
784 READWRITE(hashBlock);
785 READWRITE(vMerkleBranch);
790 int SetMerkleBranch(const CBlock* pblock=NULL);
791 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
792 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
793 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
794 int GetBlocksToMaturity() const;
795 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
796 bool AcceptToMemoryPool();
802 /** A txdb record that contains the disk location of a transaction and the
803 * locations of transactions that spend its outputs. vSpent is really only
804 * used as a flag, but having the location is very helpful for debugging.
810 std::vector<CDiskTxPos> vSpent;
817 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
820 vSpent.resize(nOutputs);
825 if (!(nType & SER_GETHASH))
842 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
844 return (a.pos == b.pos &&
845 a.vSpent == b.vSpent);
848 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
852 int GetDepthInMainChain() const;
857 /** Nodes collect new transactions into a block, hash them into a hash tree,
858 * and scan through nonce values to make the block's hash satisfy proof-of-work
859 * requirements. When they solve the proof-of-work, they broadcast the block
860 * to everyone and the block is added to the block chain. The first transaction
861 * in the block is a special one that creates a new coin owned by the creator
864 * Blocks are appended to blk0001.dat files on disk. Their location on disk
865 * is indexed by CBlockIndex objects in memory.
871 static const int CURRENT_VERSION=6;
873 uint256 hashPrevBlock;
874 uint256 hashMerkleRoot;
880 std::vector<CTransaction> vtx;
882 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
883 std::vector<unsigned char> vchBlockSig;
886 mutable std::vector<uint256> vMerkleTree;
888 // Denial-of-service detection:
890 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
899 READWRITE(this->nVersion);
900 nVersion = this->nVersion;
901 READWRITE(hashPrevBlock);
902 READWRITE(hashMerkleRoot);
907 // ConnectBlock depends on vtx following header to generate CDiskTxPos
908 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
911 READWRITE(vchBlockSig);
915 const_cast<CBlock*>(this)->vtx.clear();
916 const_cast<CBlock*>(this)->vchBlockSig.clear();
922 nVersion = CBlock::CURRENT_VERSION;
939 uint256 GetHash() const
941 return scrypt_blockhash((const uint8_t*)&nVersion);
944 int64_t GetBlockTime() const
946 return (int64_t)nTime;
949 void UpdateTime(const CBlockIndex* pindexPrev);
951 // ppcoin: entropy bit for stake modifier if chosen by modifier
952 unsigned int GetStakeEntropyBit(unsigned int nHeight) const
954 // Protocol switch to support p2pool at novacoin block #9689
955 if (nHeight >= 9689 || fTestNet)
957 // Take last bit of block hash as entropy bit
958 unsigned int nEntropyBit = (GetHash().Get64()) & (uint64_t)1;
959 if (fDebug && GetBoolArg("-printstakemodifier"))
960 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
964 // Before novacoin block #9689 - get from pregenerated table
965 int nBitNum = nHeight & 0xFF;
966 int nItemNum = nHeight / 0xFF;
968 unsigned int nEntropyBit = (unsigned int) ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get64();
969 if (fDebug && GetBoolArg("-printstakemodifier"))
970 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%d nEntropyBit=%u\n", nHeight, nEntropyBit);
974 // ppcoin: two types of block: proof-of-work or proof-of-stake
975 bool IsProofOfStake() const
977 return (vtx.size() > 1 && vtx[1].IsCoinStake());
980 bool IsProofOfWork() const
982 return !IsProofOfStake();
985 std::pair<COutPoint, unsigned int> GetProofOfStake() const
987 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
990 // ppcoin: get max transaction timestamp
991 int64_t GetMaxTransactionTime() const
993 int64_t maxTransactionTime = 0;
994 for (const CTransaction& tx : vtx)
995 maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
996 return maxTransactionTime;
999 uint256 BuildMerkleTree() const
1001 vMerkleTree.clear();
1002 for (const CTransaction& tx : vtx)
1003 vMerkleTree.push_back(tx.GetHash());
1005 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1007 for (int i = 0; i < nSize; i += 2)
1009 int i2 = std::min(i+1, nSize-1);
1010 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1011 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1015 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1018 std::vector<uint256> GetMerkleBranch(int nIndex) const
1020 if (vMerkleTree.empty())
1022 std::vector<uint256> vMerkleBranch;
1024 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1026 int i = std::min(nIndex^1, nSize-1);
1027 vMerkleBranch.push_back(vMerkleTree[j+i]);
1031 return vMerkleBranch;
1034 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1038 for (const uint256& otherside : vMerkleBranch)
1041 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1043 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1050 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1052 // Open history file to append
1053 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1055 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1057 // Write index header
1058 unsigned int nSize = fileout.GetSerializeSize(*this);
1059 fileout << FLATDATA(pchMessageStart) << nSize;
1062 long fileOutPos = ftell(fileout);
1064 return error("CBlock::WriteToDisk() : ftell failed");
1065 nBlockPosRet = fileOutPos;
1068 // Flush stdio buffers and commit to disk before returning
1070 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1071 FileCommit(fileout);
1076 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1080 // Open history file to read
1081 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1083 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1084 if (!fReadTransactions)
1085 filein.nType |= SER_BLOCKHEADERONLY;
1091 catch (const std::exception&) {
1092 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1096 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1097 return error("CBlock::ReadFromDisk() : errors in block header");
1106 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
1107 GetHash().ToString().c_str(),
1109 hashPrevBlock.ToString().c_str(),
1110 hashMerkleRoot.ToString().c_str(),
1111 nTime, nBits, nNonce,
1113 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1114 for (unsigned int i = 0; i < vtx.size(); i++)
1119 printf(" vMerkleTree: ");
1120 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1121 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1126 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1127 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1128 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1129 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1130 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1131 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1133 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1134 bool CheckBlockSignature() const;
1137 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1145 /** The block chain is a tree shaped structure starting with the
1146 * genesis block at the root, with each block potentially having multiple
1147 * candidates to be the next block. pprev and pnext link a path through the
1148 * main/longest chain. A blockindex may have multiple pprev pointing back
1149 * to it, but pnext will only point forward to the longest branch, or will
1150 * be null if the block is not part of the longest chain.
1155 const uint256* phashBlock;
1160 uint256 nChainTrust; // ppcoin: trust score of block chain
1164 int64_t nMoneySupply;
1166 uint32_t nFlags; // ppcoin: block index flags
1169 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1170 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1171 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
1174 uint64_t nStakeModifier; // hash modifier for proof-of-stake
1175 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
1177 // proof-of-stake specific fields
1178 COutPoint prevoutStake;
1179 uint32_t nStakeTime;
1180 uint256 hashProofOfStake;
1184 uint256 hashMerkleRoot;
1202 nStakeModifierChecksum = 0;
1203 hashProofOfStake = 0;
1204 prevoutStake.SetNull();
1214 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1220 nBlockPos = nBlockPosIn;
1227 nStakeModifierChecksum = 0;
1228 hashProofOfStake = 0;
1229 if (block.IsProofOfStake())
1232 prevoutStake = block.vtx[1].vin[0].prevout;
1233 nStakeTime = block.vtx[1].nTime;
1237 prevoutStake.SetNull();
1241 nVersion = block.nVersion;
1242 hashMerkleRoot = block.hashMerkleRoot;
1243 nTime = block.nTime;
1244 nBits = block.nBits;
1245 nNonce = block.nNonce;
1248 CBlock GetBlockHeader() const
1251 block.nVersion = nVersion;
1253 block.hashPrevBlock = pprev->GetBlockHash();
1254 block.hashMerkleRoot = hashMerkleRoot;
1255 block.nTime = nTime;
1256 block.nBits = nBits;
1257 block.nNonce = nNonce;
1261 uint256 GetBlockHash() const
1266 int64_t GetBlockTime() const
1268 return (int64_t)nTime;
1271 uint256 GetBlockTrust() const;
1273 bool IsInMainChain() const
1275 return (pnext || this == pindexBest);
1278 bool CheckIndex() const
1283 enum { nMedianTimeSpan=11 };
1285 int64_t GetMedianTimePast() const
1287 int64_t pmedian[nMedianTimeSpan];
1288 int64_t* pbegin = &pmedian[nMedianTimeSpan];
1289 int64_t* pend = &pmedian[nMedianTimeSpan];
1291 const CBlockIndex* pindex = this;
1292 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1293 *(--pbegin) = pindex->GetBlockTime();
1295 std::sort(pbegin, pend);
1296 return pbegin[(pend - pbegin)/2];
1299 int64_t GetMedianTime() const
1301 const CBlockIndex* pindex = this;
1302 for (int i = 0; i < nMedianTimeSpan/2; i++)
1305 return GetBlockTime();
1306 pindex = pindex->pnext;
1308 return pindex->GetMedianTimePast();
1312 * Returns true if there are nRequired or more blocks of minVersion or above
1313 * in the last nToCheck blocks, starting at pstart and going backwards.
1315 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1316 unsigned int nRequired, unsigned int nToCheck);
1319 bool IsProofOfWork() const
1321 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1324 bool IsProofOfStake() const
1326 return (nFlags & BLOCK_PROOF_OF_STAKE);
1329 void SetProofOfStake()
1331 nFlags |= BLOCK_PROOF_OF_STAKE;
1334 unsigned int GetStakeEntropyBit() const
1336 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1339 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1341 if (nEntropyBit > 1)
1343 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1347 bool GeneratedStakeModifier() const
1349 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
1352 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
1354 nStakeModifier = nModifier;
1355 if (fGeneratedStakeModifier)
1356 nFlags |= BLOCK_STAKE_MODIFIER;
1359 std::string ToString() const
1361 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)",
1362 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
1363 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1364 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1365 nStakeModifier, nStakeModifierChecksum,
1366 hashProofOfStake.ToString().c_str(),
1367 prevoutStake.ToString().c_str(), nStakeTime,
1368 hashMerkleRoot.ToString().c_str(),
1369 GetBlockHash().ToString().c_str());
1374 printf("%s\n", ToString().c_str());
1380 /** Used to marshal pointers into hashes for db storage. */
1381 class CDiskBlockIndex : public CBlockIndex
1397 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1399 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1400 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1405 if (!(nType & SER_GETHASH))
1406 READWRITE(nVersion);
1408 READWRITE(hashNext);
1410 READWRITE(nBlockPos);
1413 READWRITE(nMoneySupply);
1415 READWRITE(nStakeModifier);
1416 if (IsProofOfStake())
1418 READWRITE(prevoutStake);
1419 READWRITE(nStakeTime);
1420 READWRITE(hashProofOfStake);
1424 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1425 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1426 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1430 READWRITE(this->nVersion);
1431 READWRITE(hashPrev);
1432 READWRITE(hashMerkleRoot);
1436 READWRITE(blockHash);
1439 uint256 GetBlockHash() const
1441 if (fUseFastIndex && (nTime < GetAdjustedTime() - nOneDay) && blockHash != 0)
1445 block.nVersion = nVersion;
1446 block.hashPrevBlock = hashPrev;
1447 block.hashMerkleRoot = hashMerkleRoot;
1448 block.nTime = nTime;
1449 block.nBits = nBits;
1450 block.nNonce = nNonce;
1452 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1457 std::string ToString() const
1459 std::string str = "CDiskBlockIndex(";
1460 str += CBlockIndex::ToString();
1461 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1462 GetBlockHash().ToString().c_str(),
1463 hashPrev.ToString().c_str(),
1464 hashNext.ToString().c_str());
1470 printf("%s\n", ToString().c_str());
1481 /** Describes a place in the block chain to another node such that if the
1482 * other node doesn't have the same branch, it can find a recent common trunk.
1483 * The further back it is, the further before the fork it may be.
1488 std::vector<uint256> vHave;
1495 explicit CBlockLocator(const CBlockIndex* pindex)
1500 explicit CBlockLocator(uint256 hashBlock)
1502 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1503 if (mi != mapBlockIndex.end())
1507 CBlockLocator(const std::vector<uint256>& vHaveIn)
1514 if (!(nType & SER_GETHASH))
1515 READWRITE(nVersion);
1526 return vHave.empty();
1529 void Set(const CBlockIndex* pindex)
1535 vHave.push_back(pindex->GetBlockHash());
1537 // Exponentially larger steps back
1538 for (int i = 0; pindex && i < nStep; i++)
1539 pindex = pindex->pprev;
1540 if (vHave.size() > 10)
1543 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1546 int GetDistanceBack()
1548 // Retrace how far back it was in the sender's branch
1551 for (const uint256& hash : vHave)
1553 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1554 if (mi != mapBlockIndex.end())
1556 CBlockIndex* pindex = (*mi).second;
1557 if (pindex->IsInMainChain())
1567 CBlockIndex* GetBlockIndex()
1569 // Find the first block the caller has in the main chain
1570 for (const uint256& hash : vHave)
1572 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1573 if (mi != mapBlockIndex.end())
1575 CBlockIndex* pindex = (*mi).second;
1576 if (pindex->IsInMainChain())
1580 return pindexGenesisBlock;
1583 uint256 GetBlockHash()
1585 // Find the first block the caller has in the main chain
1586 for (const uint256& hash : vHave)
1588 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1589 if (mi != mapBlockIndex.end())
1591 CBlockIndex* pindex = (*mi).second;
1592 if (pindex->IsInMainChain())
1596 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1601 CBlockIndex* pindex = GetBlockIndex();
1604 return pindex->nHeight;
1618 mutable CCriticalSection cs;
1619 std::map<uint256, CTransaction> mapTx;
1620 std::map<COutPoint, CInPoint> mapNextTx;
1622 bool accept(CTxDB& txdb, CTransaction &tx,
1623 bool fCheckInputs, bool* pfMissingInputs);
1624 bool addUnchecked(const uint256& hash, CTransaction &tx);
1625 bool remove(CTransaction &tx);
1627 void queryHashes(std::vector<uint256>& vtxid);
1632 return mapTx.size();
1635 bool exists(uint256 hash)
1637 return (mapTx.count(hash) != 0);
1640 CTransaction& lookup(uint256 hash)
1646 extern CTxMemPool mempool;