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"
33 static const unsigned int MAX_BLOCK_SIZE = 1000000;
34 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
35 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
36 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
37 static const unsigned int MAX_INV_SZ = 50000;
39 static const int64_t MIN_TX_FEE = CENT/10;
40 static const int64_t MIN_RELAY_TX_FEE = CENT/50;
42 static const int64_t MAX_MONEY = std::numeric_limits<int64_t>::max();
43 static const int64_t MAX_MINT_PROOF_OF_WORK = 100 * COIN;
44 static const int64_t MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
45 static const int64_t MIN_TXOUT_AMOUNT = CENT/100;
48 inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
49 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
50 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
51 // Maximum number of script-checking threads allowed
52 static const int MAX_SCRIPTCHECK_THREADS = 16;
54 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
55 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
57 inline int64_t PastDrift(int64_t nTime) { return nTime - 2 * nOneHour; } // up to 2 hours from the past
58 inline int64_t FutureDrift(int64_t nTime) { return nTime + 2 * nOneHour; } // up to 2 hours from the future
60 extern CScript COINBASE_FLAGS;
61 extern CCriticalSection cs_main;
62 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
63 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
64 extern CBlockIndex* pindexGenesisBlock;
65 extern unsigned int nNodeLifespan;
66 extern unsigned int nStakeMinAge;
67 extern int nCoinbaseMaturity;
68 extern int nBestHeight;
69 extern uint256 nBestChainTrust;
70 extern uint256 nBestInvalidTrust;
71 extern uint256 hashBestChain;
72 extern CBlockIndex* pindexBest;
73 extern unsigned int nTransactionsUpdated;
74 extern uint64_t nLastBlockTx;
75 extern uint64_t nLastBlockSize;
76 extern uint32_t nLastCoinStakeSearchInterval;
77 extern const std::string strMessageMagic;
78 extern int64_t nTimeBestReceived;
79 extern CCriticalSection cs_setpwalletRegistered;
80 extern std::set<CWallet*> setpwalletRegistered;
81 extern unsigned char pchMessageStart[4];
82 extern std::map<uint256, CBlock*> mapOrphanBlocks;
85 extern int64_t nTransactionFee;
86 extern int64_t nMinimumInputValue;
87 extern bool fUseFastIndex;
88 extern int nScriptCheckThreads;
89 extern const uint256 entropyStore[38];
91 // Minimum disk space required - used in CheckDiskSpace()
92 static const uint64_t nMinDiskSpace = 52428800;
99 void RegisterWallet(CWallet* pwalletIn);
100 void UnregisterWallet(CWallet* pwalletIn);
101 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
102 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
103 bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
104 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
105 FILE* AppendBlockFile(unsigned int& nFileRet);
107 void UnloadBlockIndex();
108 bool LoadBlockIndex(bool fAllowNew=true);
109 void PrintBlockTree();
110 CBlockIndex* FindBlockByHeight(int nHeight);
111 bool ProcessMessages(CNode* pfrom);
112 bool SendMessages(CNode* pto);
113 bool LoadExternalBlockFile(FILE* fileIn);
115 // Run an instance of the script checking thread
116 void ThreadScriptCheck(void* parg);
117 // Stop the script checking threads
118 void ThreadScriptCheckQuit();
120 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
121 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
122 int64_t GetProofOfWorkReward(unsigned int nBits);
123 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly=false);
124 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
125 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
126 int GetNumBlocksOfPeers();
127 bool IsInitialBlockDownload();
128 std::string GetWarnings(std::string strFor);
129 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
130 uint256 WantedByOrphan(const CBlock* pblockOrphan);
131 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
132 void ResendWalletTransactions(bool fForceResend=false);
134 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
139 /** Position on disk for a particular transaction. */
152 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
155 nBlockPos = nBlockPosIn;
159 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
160 void SetNull() { nFile = std::numeric_limits<uint32_t>::max(); nBlockPos = 0; nTxPos = 0; }
161 bool IsNull() const { return (nFile == std::numeric_limits<uint32_t>::max()); }
163 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
165 return (a.nFile == b.nFile &&
166 a.nBlockPos == b.nBlockPos &&
167 a.nTxPos == b.nTxPos);
170 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
176 std::string ToString() const
181 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
186 printf("%s", ToString().c_str());
192 /** An inpoint - a combination of a transaction and an index n into its vin */
199 CInPoint() { SetNull(); }
200 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
201 void SetNull() { ptx = NULL; n = std::numeric_limits<uint32_t>::max(); }
202 bool IsNull() const { return (ptx == NULL && n == std::numeric_limits<uint32_t>::max()); }
207 /** An outpoint - a combination of a transaction hash and an index n into its vout */
214 COutPoint() { SetNull(); }
215 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
216 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
217 void SetNull() { hash = 0; n = std::numeric_limits<uint32_t>::max(); }
218 bool IsNull() const { return (hash == 0 && n == std::numeric_limits<uint32_t>::max()); }
220 friend bool operator<(const COutPoint& a, const COutPoint& b)
222 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
225 friend bool operator==(const COutPoint& a, const COutPoint& b)
227 return (a.hash == b.hash && a.n == b.n);
230 friend bool operator!=(const COutPoint& a, const COutPoint& b)
235 std::string ToString() const
237 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
242 printf("%s\n", ToString().c_str());
249 /** An input of a transaction. It contains the location of the previous
250 * transaction's output that it claims and a signature that matches the
251 * output's public key.
262 nSequence = std::numeric_limits<unsigned int>::max();
265 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
268 scriptSig = scriptSigIn;
269 nSequence = nSequenceIn;
272 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
274 prevout = COutPoint(hashPrevTx, nOut);
275 scriptSig = scriptSigIn;
276 nSequence = nSequenceIn;
282 READWRITE(scriptSig);
283 READWRITE(nSequence);
288 return (nSequence == std::numeric_limits<unsigned int>::max());
291 friend bool operator==(const CTxIn& a, const CTxIn& b)
293 return (a.prevout == b.prevout &&
294 a.scriptSig == b.scriptSig &&
295 a.nSequence == b.nSequence);
298 friend bool operator!=(const CTxIn& a, const CTxIn& b)
303 std::string ToStringShort() const
305 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
308 std::string ToString() const
312 str += prevout.ToString();
313 if (prevout.IsNull())
314 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
316 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
317 if (nSequence != std::numeric_limits<unsigned int>::max())
318 str += strprintf(", nSequence=%u", nSequence);
325 printf("%s\n", ToString().c_str());
332 /** An output of a transaction. It contains the public key that the next input
333 * must be able to sign with to claim it.
339 CScript scriptPubKey;
346 CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
349 scriptPubKey = scriptPubKeyIn;
355 READWRITE(scriptPubKey);
361 scriptPubKey.clear();
366 return (nValue == -1);
372 scriptPubKey.clear();
377 return (nValue == 0 && scriptPubKey.empty());
380 uint256 GetHash() const
382 return SerializeHash(*this);
385 friend bool operator==(const CTxOut& a, const CTxOut& b)
387 return (a.nValue == b.nValue &&
388 a.scriptPubKey == b.scriptPubKey);
391 friend bool operator!=(const CTxOut& a, const CTxOut& b)
396 std::string ToStringShort() const
398 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
401 std::string ToString() const
403 if (IsEmpty()) return "CTxOut(empty)";
404 if (scriptPubKey.size() < 6)
405 return "CTxOut(error)";
406 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
411 printf("%s\n", ToString().c_str());
425 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
427 /** The basic transaction that is broadcasted on the network and contained in
428 * blocks. A transaction can contain multiple inputs and outputs.
433 static const int CURRENT_VERSION=1;
436 std::vector<CTxIn> vin;
437 std::vector<CTxOut> vout;
440 // Denial-of-service detection:
442 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
451 READWRITE(this->nVersion);
452 nVersion = this->nVersion;
456 READWRITE(nLockTime);
461 nVersion = CTransaction::CURRENT_VERSION;
462 nTime = (uint32_t) GetAdjustedTime();
466 nDoS = 0; // Denial-of-service prevention
471 return (vin.empty() && vout.empty());
474 uint256 GetHash() const
476 return SerializeHash(*this);
479 bool IsFinal(int nBlockHeight=0, int64_t nBlockTime=0) const
481 // Time based nLockTime implemented in 0.1.6
484 if (nBlockHeight == 0)
485 nBlockHeight = nBestHeight;
487 nBlockTime = GetAdjustedTime();
488 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
490 for (const CTxIn& txin : vin)
496 bool IsNewerThan(const CTransaction& old) const
498 if (vin.size() != old.vin.size())
500 for (unsigned int i = 0; i < vin.size(); i++)
501 if (vin[i].prevout != old.vin[i].prevout)
505 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
506 for (unsigned int i = 0; i < vin.size(); i++)
508 if (vin[i].nSequence != old.vin[i].nSequence)
510 if (vin[i].nSequence <= nLowest)
513 nLowest = vin[i].nSequence;
515 if (old.vin[i].nSequence < nLowest)
518 nLowest = old.vin[i].nSequence;
525 bool IsCoinBase() const
527 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
530 bool IsCoinStake() const
532 // ppcoin: the coin stake transaction is marked with the first output empty
533 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
536 /** Check for standard transaction types
537 @return True if all outputs (scriptPubKeys) use only standard transaction forms
539 bool IsStandard(std::string& strReason) const;
540 bool IsStandard() const
542 std::string strReason;
543 return IsStandard(strReason);
546 /** Check for standard transaction types
547 @param[in] mapInputs Map of previous transactions that have outputs we're spending
548 @return True if all inputs (scriptSigs) use only standard transaction forms
549 @see CTransaction::FetchInputs
551 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
553 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
554 @return number of sigops this transaction's outputs will produce when spent
555 @see CTransaction::FetchInputs
557 unsigned int GetLegacySigOpCount() const;
559 /** Count ECDSA signature operations in pay-to-script-hash inputs.
561 @param[in] mapInputs Map of previous transactions that have outputs we're spending
562 @return maximum number of sigops required to validate this transaction's inputs
563 @see CTransaction::FetchInputs
565 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
567 /** Amount of bitcoins spent by this transaction.
568 @return sum of all outputs (note: does not include fees)
570 int64_t GetValueOut() const
572 int64_t nValueOut = 0;
573 for (const CTxOut& txout : vout)
575 nValueOut += txout.nValue;
576 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
577 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
582 /** Amount of bitcoins coming in to this transaction
583 Note that lightweight clients may not know anything besides the hash of previous transactions,
584 so may not be able to calculate this.
586 @param[in] mapInputs Map of previous transactions that have outputs we're spending
587 @return Sum of value of all inputs (scriptSigs)
588 @see CTransaction::FetchInputs
590 int64_t GetValueIn(const MapPrevTx& mapInputs) const;
592 static bool AllowFree(double dPriority)
594 // Large (in bytes) low-priority (new, small-coin) transactions
596 return dPriority > COIN * 144 / 250;
599 int64_t GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
601 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
603 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
605 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
608 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
609 return error("CTransaction::ReadFromDisk() : fseek failed");
614 catch (const std::exception&) {
615 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
618 // Return file pointer
621 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
622 return error("CTransaction::ReadFromDisk() : second fseek failed");
623 *pfileRet = filein.release();
628 friend bool operator==(const CTransaction& a, const CTransaction& b)
630 return (a.nVersion == b.nVersion &&
631 a.nTime == b.nTime &&
634 a.nLockTime == b.nLockTime);
637 friend bool operator!=(const CTransaction& a, const CTransaction& b)
642 std::string ToStringShort() const
645 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
649 std::string ToString() const
652 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
653 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
654 GetHash().ToString().substr(0,10).c_str(),
660 for (unsigned int i = 0; i < vin.size(); i++)
661 str += " " + vin[i].ToString() + "\n";
662 for (unsigned int i = 0; i < vout.size(); i++)
663 str += " " + vout[i].ToString() + "\n";
669 printf("%s", ToString().c_str());
673 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
674 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
675 bool ReadFromDisk(COutPoint prevout);
676 bool DisconnectInputs(CTxDB& txdb);
678 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
680 @param[in] txdb Transaction database
681 @param[in] mapTestPool List of pending changes to the transaction index database
682 @param[in] fBlock True if being called to add a new best-block to the chain
683 @param[in] fMiner True if being called by CreateNewBlock
684 @param[out] inputsRet Pointers to this transaction's inputs
685 @param[out] fInvalid returns true if transaction is invalid
686 @return Returns true if all inputs are in txdb or mapTestPool
688 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
689 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
691 /** Sanity check previous transactions, then, if all checks succeed,
692 mark them as spent by this transaction.
694 @param[in] inputs Previous transactions (from FetchInputs)
695 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
696 @param[in] posThisTx Position of this transaction on disk
697 @param[in] pindexBlock
698 @param[in] fBlock true if called from ConnectBlock
699 @param[in] fMiner true if called from CreateNewBlock
700 @param[in] fScriptChecks enable scripts validation?
701 @param[in] flags STRICT_FLAGS script validation flags
702 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
703 @return Returns true if all checks succeed
705 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
706 bool fBlock, bool fMiner, bool fScriptChecks=true,
707 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
708 bool ClientConnectInputs();
709 bool CheckTransaction() const;
710 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
711 bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
714 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
717 /** Closure representing one script verification
718 * Note that this stores references to the spending transaction */
722 CScript scriptPubKey;
723 const CTransaction *ptxTo;
730 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
731 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
732 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
734 bool operator()() const;
736 void swap(CScriptCheck &check) {
737 scriptPubKey.swap(check.scriptPubKey);
738 std::swap(ptxTo, check.ptxTo);
739 std::swap(nIn, check.nIn);
740 std::swap(nFlags, check.nFlags);
741 std::swap(nHashType, check.nHashType);
748 /** A transaction with a merkle branch linking it to the block chain. */
749 class CMerkleTx : public CTransaction
753 std::vector<uint256> vMerkleBranch;
757 mutable bool fMerkleVerified;
765 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
774 fMerkleVerified = false;
780 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
781 nVersion = this->nVersion;
782 READWRITE(hashBlock);
783 READWRITE(vMerkleBranch);
788 int SetMerkleBranch(const CBlock* pblock=NULL);
789 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
790 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
791 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
792 int GetBlocksToMaturity() const;
793 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
794 bool AcceptToMemoryPool();
800 /** A txdb record that contains the disk location of a transaction and the
801 * locations of transactions that spend its outputs. vSpent is really only
802 * used as a flag, but having the location is very helpful for debugging.
808 std::vector<CDiskTxPos> vSpent;
815 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
818 vSpent.resize(nOutputs);
823 if (!(nType & SER_GETHASH))
840 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
842 return (a.pos == b.pos &&
843 a.vSpent == b.vSpent);
846 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
850 int GetDepthInMainChain() const;
855 /** Nodes collect new transactions into a block, hash them into a hash tree,
856 * and scan through nonce values to make the block's hash satisfy proof-of-work
857 * requirements. When they solve the proof-of-work, they broadcast the block
858 * to everyone and the block is added to the block chain. The first transaction
859 * in the block is a special one that creates a new coin owned by the creator
862 * Blocks are appended to blk0001.dat files on disk. Their location on disk
863 * is indexed by CBlockIndex objects in memory.
869 static const int CURRENT_VERSION=6;
871 uint256 hashPrevBlock;
872 uint256 hashMerkleRoot;
878 std::vector<CTransaction> vtx;
880 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
881 std::vector<unsigned char> vchBlockSig;
884 mutable std::vector<uint256> vMerkleTree;
886 // Denial-of-service detection:
888 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
897 READWRITE(this->nVersion);
898 nVersion = this->nVersion;
899 READWRITE(hashPrevBlock);
900 READWRITE(hashMerkleRoot);
905 // ConnectBlock depends on vtx following header to generate CDiskTxPos
906 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
909 READWRITE(vchBlockSig);
913 const_cast<CBlock*>(this)->vtx.clear();
914 const_cast<CBlock*>(this)->vchBlockSig.clear();
920 nVersion = CBlock::CURRENT_VERSION;
937 uint256 GetHash() const;
939 int64_t GetBlockTime() const
941 return (int64_t)nTime;
944 void UpdateTime(const CBlockIndex* pindexPrev);
946 // ppcoin: entropy bit for stake modifier if chosen by modifier
947 unsigned int GetStakeEntropyBit(unsigned int nHeight) const
949 // Protocol switch to support p2pool at novacoin block #9689
950 if (nHeight >= 9689 || fTestNet)
952 // Take last bit of block hash as entropy bit
953 unsigned int nEntropyBit = (GetHash().Get64()) & (uint64_t)1;
954 if (fDebug && GetBoolArg("-printstakemodifier"))
955 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
959 // Before novacoin block #9689 - get from pregenerated table
960 int nBitNum = nHeight & 0xFF;
961 int nItemNum = nHeight / 0xFF;
963 unsigned int nEntropyBit = (unsigned int) ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get64();
964 if (fDebug && GetBoolArg("-printstakemodifier"))
965 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%d nEntropyBit=%u\n", nHeight, nEntropyBit);
969 // ppcoin: two types of block: proof-of-work or proof-of-stake
970 bool IsProofOfStake() const
972 return (vtx.size() > 1 && vtx[1].IsCoinStake());
975 bool IsProofOfWork() const
977 return !IsProofOfStake();
980 std::pair<COutPoint, unsigned int> GetProofOfStake() const
982 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
985 // ppcoin: get max transaction timestamp
986 int64_t GetMaxTransactionTime() const
988 int64_t maxTransactionTime = 0;
989 for (const CTransaction& tx : vtx)
990 maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
991 return maxTransactionTime;
994 uint256 BuildMerkleTree() const
997 for (const CTransaction& tx : vtx)
998 vMerkleTree.push_back(tx.GetHash());
1000 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1002 for (int i = 0; i < nSize; i += 2)
1004 int i2 = std::min(i+1, nSize-1);
1005 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1006 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1010 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1013 std::vector<uint256> GetMerkleBranch(int nIndex) const
1015 if (vMerkleTree.empty())
1017 std::vector<uint256> vMerkleBranch;
1019 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1021 int i = std::min(nIndex^1, nSize-1);
1022 vMerkleBranch.push_back(vMerkleTree[j+i]);
1026 return vMerkleBranch;
1029 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1033 for (const uint256& otherside : vMerkleBranch)
1036 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1038 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1045 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1047 // Open history file to append
1048 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1050 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1052 // Write index header
1053 unsigned int nSize = fileout.GetSerializeSize(*this);
1054 fileout << FLATDATA(pchMessageStart) << nSize;
1057 long fileOutPos = ftell(fileout);
1059 return error("CBlock::WriteToDisk() : ftell failed");
1060 nBlockPosRet = fileOutPos;
1063 // Flush stdio buffers and commit to disk before returning
1065 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1066 FileCommit(fileout);
1071 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1075 // Open history file to read
1076 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1078 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1079 if (!fReadTransactions)
1080 filein.nType |= SER_BLOCKHEADERONLY;
1086 catch (const std::exception&) {
1087 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1091 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1092 return error("CBlock::ReadFromDisk() : errors in block header");
1101 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
1102 GetHash().ToString().c_str(),
1104 hashPrevBlock.ToString().c_str(),
1105 hashMerkleRoot.ToString().c_str(),
1106 nTime, nBits, nNonce,
1108 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1109 for (unsigned int i = 0; i < vtx.size(); i++)
1114 printf(" vMerkleTree: ");
1115 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1116 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1121 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1122 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1123 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1124 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1125 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1126 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1128 bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1129 bool CheckBlockSignature() const;
1132 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1140 /** The block chain is a tree shaped structure starting with the
1141 * genesis block at the root, with each block potentially having multiple
1142 * candidates to be the next block. pprev and pnext link a path through the
1143 * main/longest chain. A blockindex may have multiple pprev pointing back
1144 * to it, but pnext will only point forward to the longest branch, or will
1145 * be null if the block is not part of the longest chain.
1150 const uint256* phashBlock;
1155 uint256 nChainTrust; // ppcoin: trust score of block chain
1159 int64_t nMoneySupply;
1161 uint32_t nFlags; // ppcoin: block index flags
1164 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1165 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1166 BLOCK_STAKE_MODIFIER = (1 << 2) // regenerated stake modifier
1169 uint64_t nStakeModifier; // hash modifier for proof-of-stake
1170 uint32_t nStakeModifierChecksum; // checksum of index; in-memeory only
1172 // proof-of-stake specific fields
1173 COutPoint prevoutStake;
1174 uint32_t nStakeTime;
1175 uint256 hashProofOfStake;
1179 uint256 hashMerkleRoot;
1197 nStakeModifierChecksum = 0;
1198 hashProofOfStake = 0;
1199 prevoutStake.SetNull();
1209 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1215 nBlockPos = nBlockPosIn;
1222 nStakeModifierChecksum = 0;
1223 hashProofOfStake = 0;
1224 if (block.IsProofOfStake())
1227 prevoutStake = block.vtx[1].vin[0].prevout;
1228 nStakeTime = block.vtx[1].nTime;
1232 prevoutStake.SetNull();
1236 nVersion = block.nVersion;
1237 hashMerkleRoot = block.hashMerkleRoot;
1238 nTime = block.nTime;
1239 nBits = block.nBits;
1240 nNonce = block.nNonce;
1243 CBlock GetBlockHeader() const
1246 block.nVersion = nVersion;
1248 block.hashPrevBlock = pprev->GetBlockHash();
1249 block.hashMerkleRoot = hashMerkleRoot;
1250 block.nTime = nTime;
1251 block.nBits = nBits;
1252 block.nNonce = nNonce;
1256 uint256 GetBlockHash() const
1261 int64_t GetBlockTime() const
1263 return (int64_t)nTime;
1266 uint256 GetBlockTrust() const;
1268 bool IsInMainChain() const
1270 return (pnext || this == pindexBest);
1273 bool CheckIndex() const
1278 enum { nMedianTimeSpan=11 };
1280 int64_t GetMedianTimePast() const
1282 int64_t pmedian[nMedianTimeSpan];
1283 int64_t* pbegin = &pmedian[nMedianTimeSpan];
1284 int64_t* pend = &pmedian[nMedianTimeSpan];
1286 const CBlockIndex* pindex = this;
1287 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1288 *(--pbegin) = pindex->GetBlockTime();
1290 std::sort(pbegin, pend);
1291 return pbegin[(pend - pbegin)/2];
1294 int64_t GetMedianTime() const
1296 const CBlockIndex* pindex = this;
1297 for (int i = 0; i < nMedianTimeSpan/2; i++)
1300 return GetBlockTime();
1301 pindex = pindex->pnext;
1303 return pindex->GetMedianTimePast();
1307 * Returns true if there are nRequired or more blocks of minVersion or above
1308 * in the last nToCheck blocks, starting at pstart and going backwards.
1310 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1311 unsigned int nRequired, unsigned int nToCheck);
1314 bool IsProofOfWork() const
1316 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1319 bool IsProofOfStake() const
1321 return (nFlags & BLOCK_PROOF_OF_STAKE);
1324 void SetProofOfStake()
1326 nFlags |= BLOCK_PROOF_OF_STAKE;
1329 unsigned int GetStakeEntropyBit() const
1331 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1334 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1336 if (nEntropyBit > 1)
1338 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1342 bool GeneratedStakeModifier() const
1344 return (nFlags & BLOCK_STAKE_MODIFIER) != 0;
1347 void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
1349 nStakeModifier = nModifier;
1350 if (fGeneratedStakeModifier)
1351 nFlags |= BLOCK_STAKE_MODIFIER;
1354 std::string ToString() const
1356 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)",
1357 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
1358 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1359 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1360 nStakeModifier, nStakeModifierChecksum,
1361 hashProofOfStake.ToString().c_str(),
1362 prevoutStake.ToString().c_str(), nStakeTime,
1363 hashMerkleRoot.ToString().c_str(),
1364 GetBlockHash().ToString().c_str());
1369 printf("%s\n", ToString().c_str());
1375 /** Used to marshal pointers into hashes for db storage. */
1376 class CDiskBlockIndex : public CBlockIndex
1392 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1394 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1395 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1400 if (!(nType & SER_GETHASH))
1401 READWRITE(nVersion);
1403 READWRITE(hashNext);
1405 READWRITE(nBlockPos);
1408 READWRITE(nMoneySupply);
1410 READWRITE(nStakeModifier);
1411 if (IsProofOfStake())
1413 READWRITE(prevoutStake);
1414 READWRITE(nStakeTime);
1415 READWRITE(hashProofOfStake);
1419 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1420 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1421 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1425 READWRITE(this->nVersion);
1426 READWRITE(hashPrev);
1427 READWRITE(hashMerkleRoot);
1431 READWRITE(blockHash);
1434 uint256 GetBlockHash() const
1436 if (fUseFastIndex && (nTime < GetAdjustedTime() - nOneDay) && blockHash != 0)
1440 block.nVersion = nVersion;
1441 block.hashPrevBlock = hashPrev;
1442 block.hashMerkleRoot = hashMerkleRoot;
1443 block.nTime = nTime;
1444 block.nBits = nBits;
1445 block.nNonce = nNonce;
1447 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1452 std::string ToString() const
1454 std::string str = "CDiskBlockIndex(";
1455 str += CBlockIndex::ToString();
1456 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1457 GetBlockHash().ToString().c_str(),
1458 hashPrev.ToString().c_str(),
1459 hashNext.ToString().c_str());
1465 printf("%s\n", ToString().c_str());
1476 /** Describes a place in the block chain to another node such that if the
1477 * other node doesn't have the same branch, it can find a recent common trunk.
1478 * The further back it is, the further before the fork it may be.
1483 std::vector<uint256> vHave;
1490 explicit CBlockLocator(const CBlockIndex* pindex)
1495 explicit CBlockLocator(uint256 hashBlock)
1497 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1498 if (mi != mapBlockIndex.end())
1502 CBlockLocator(const std::vector<uint256>& vHaveIn)
1509 if (!(nType & SER_GETHASH))
1510 READWRITE(nVersion);
1521 return vHave.empty();
1524 void Set(const CBlockIndex* pindex)
1530 vHave.push_back(pindex->GetBlockHash());
1532 // Exponentially larger steps back
1533 for (int i = 0; pindex && i < nStep; i++)
1534 pindex = pindex->pprev;
1535 if (vHave.size() > 10)
1538 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1541 int GetDistanceBack()
1543 // Retrace how far back it was in the sender's branch
1546 for (const uint256& hash : vHave)
1548 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1549 if (mi != mapBlockIndex.end())
1551 CBlockIndex* pindex = (*mi).second;
1552 if (pindex->IsInMainChain())
1562 CBlockIndex* GetBlockIndex()
1564 // Find the first block the caller has in the main chain
1565 for (const uint256& hash : vHave)
1567 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1568 if (mi != mapBlockIndex.end())
1570 CBlockIndex* pindex = (*mi).second;
1571 if (pindex->IsInMainChain())
1575 return pindexGenesisBlock;
1578 uint256 GetBlockHash()
1580 // Find the first block the caller has in the main chain
1581 for (const uint256& hash : vHave)
1583 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1584 if (mi != mapBlockIndex.end())
1586 CBlockIndex* pindex = (*mi).second;
1587 if (pindex->IsInMainChain())
1591 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1596 CBlockIndex* pindex = GetBlockIndex();
1599 return pindex->nHeight;
1613 mutable CCriticalSection cs;
1614 std::map<uint256, CTransaction> mapTx;
1615 std::map<COutPoint, CInPoint> mapNextTx;
1617 bool accept(CTxDB& txdb, CTransaction &tx,
1618 bool fCheckInputs, bool* pfMissingInputs);
1619 bool addUnchecked(const uint256& hash, CTransaction &tx);
1620 bool remove(CTransaction &tx);
1622 void queryHashes(std::vector<uint256>& vtxid);
1627 return mapTx.size();
1630 bool exists(uint256 hash)
1632 return (mapTx.count(hash) != 0);
1635 CTransaction& lookup(uint256 hash)
1641 extern CTxMemPool mempool;