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.
13 #include "zerocoin/Zerocoin.h"
26 class CRequestTracker;
29 static const unsigned int MAX_BLOCK_SIZE = 1000000;
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
32 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
33 static const unsigned int MAX_INV_SZ = 50000;
34 static const int64 MIN_TX_FEE = CENT;
35 static const int64 MIN_RELAY_TX_FEE = CENT;
36 static const int64 MAX_MONEY = 2000000000 * COIN;
37 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
38 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
39 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
41 static const unsigned int ENTROPY_SWITCH_TIME = 1362791041; // Sat, 09 Mar 2013 01:04:01 GMT
42 static const unsigned int STAKE_SWITCH_TIME = 1371686400; // Thu, 20 Jun 2013 00:00:00 GMT
43 static const unsigned int TARGETS_SWITCH_TIME = 1374278400; // Sat, 20 Jul 2013 00:00:00 GMT
44 static const unsigned int CHAINCHECKS_SWITCH_TIME = 1379635200; // Fri, 20 Sep 2013 00:00:00 GMT
45 static const unsigned int STAKECURVE_SWITCH_TIME = 1382227200; // Sun, 20 Oct 2013 00:00:00 GMT
46 static const unsigned int OUTPUT_SWITCH_TIME = 1398916800; // Thu, 01 May 2014 04:00:00 GMT
49 inline bool MoneyRange(int64 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
54 static const int fHaveUPnP = true;
56 static const int fHaveUPnP = false;
59 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
60 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
62 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
63 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
65 extern libzerocoin::Params* ZCParams;
66 extern CScript COINBASE_FLAGS;
67 extern CCriticalSection cs_main;
68 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
69 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
70 extern CBlockIndex* pindexGenesisBlock;
71 extern unsigned int nStakeMinAge;
72 extern unsigned int nNodeLifespan;
73 extern int nCoinbaseMaturity;
74 extern int nBestHeight;
75 extern uint256 nBestChainTrust;
76 extern uint256 nBestInvalidTrust;
77 extern uint256 hashBestChain;
78 extern CBlockIndex* pindexBest;
79 extern unsigned int nTransactionsUpdated;
80 extern uint64 nLastBlockTx;
81 extern uint64 nLastBlockSize;
82 extern int64 nLastCoinStakeSearchInterval;
83 extern const std::string strMessageMagic;
84 extern int64 nTimeBestReceived;
85 extern CCriticalSection cs_setpwalletRegistered;
86 extern std::set<CWallet*> setpwalletRegistered;
87 extern unsigned char pchMessageStart[4];
88 extern std::map<uint256, CBlock*> mapOrphanBlocks;
91 extern int64 nTransactionFee;
92 extern int64 nMinimumInputValue;
93 extern bool fUseFastIndex;
94 extern unsigned int nDerivationMethodIndex;
96 // Minimum disk space required - used in CheckDiskSpace()
97 static const uint64 nMinDiskSpace = 52428800;
104 void RegisterWallet(CWallet* pwalletIn);
105 void UnregisterWallet(CWallet* pwalletIn);
106 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
107 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
108 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
109 FILE* OpenBlockFile(const CDiskBlockPos &pos, const char* pszMode="rb");
110 bool LoadBlockIndex(bool fAllowNew=true);
111 void PrintBlockTree();
112 CBlockIndex* FindBlockByHeight(int nHeight);
113 bool ProcessMessages(CNode* pfrom);
114 bool SendMessages(CNode* pto, bool fSendTrickle);
115 bool LoadExternalBlockFile(FILE* fileIn);
117 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
118 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
119 int64 GetProofOfWorkReward(unsigned int nBits);
120 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
121 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
122 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
123 int GetNumBlocksOfPeers();
124 bool IsInitialBlockDownload();
125 std::string GetWarnings(std::string strFor);
126 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
127 uint256 WantedByOrphan(const CBlock* pblockOrphan);
128 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
129 void StakeMiner(CWallet *pwallet);
130 void ResendWalletTransactions();
132 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
144 CDiskBlockPos(int nHeightIn, int nAlternativeIn = 0) {
146 nAlternative = nAlternativeIn;
149 std::string GetAlternative() const {
150 char c[9]={0,0,0,0,0,0,0,0,0};
152 unsigned int n = nAlternative;
153 while (n > 0 && cp>c) {
155 *(--cp) = 'a' + (n % 26);
158 return std::string(cp);
161 boost::filesystem::path GetDirectory(const boost::filesystem::path &base) const {
162 assert(nHeight != -1);
163 return base / strprintf("era%02u", nHeight / 210000) /
164 strprintf("cycle%04u", nHeight / 2016);
167 boost::filesystem::path GetFileName(const boost::filesystem::path &base) const {
168 return GetDirectory(base) / strprintf("%08u%s.blk", nHeight, GetAlternative().c_str());
171 boost::filesystem::path GetUndoFile(const boost::filesystem::path &base) const {
172 return GetDirectory(base) / strprintf("%08u%s.und", nHeight, GetAlternative().c_str());
175 // TODO: make thread-safe (lockfile, atomic file creation, ...?)
176 void MakeUnique(const boost::filesystem::path &base) {
177 while (boost::filesystem::exists(GetFileName(base)))
181 IMPLEMENT_SERIALIZE(({
182 CDiskBlockPos *me = const_cast<CDiskBlockPos*>(this);
184 unsigned int nCode = (nHeight + 1) * 2 + (nAlternative > 0);
185 READWRITE(VARINT(nCode));
186 if (nAlternative > 0) {
187 unsigned int nAlt = nAlternative - 1;
188 READWRITE(VARINT(nAlt));
191 unsigned int nCode = 0;
192 READWRITE(VARINT(nCode));
193 me->nHeight = (nCode / 2) - 1;
195 unsigned int nAlt = 0;
196 READWRITE(VARINT(nAlt));
197 me->nAlternative = 1 + nAlt;
199 me->nAlternative = 0;
204 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
205 return ((a.nHeight == b.nHeight) && (a.nAlternative == b.nAlternative));
208 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
212 void SetNull() { nHeight = -1; nAlternative = 0; }
213 bool IsNull() const { return ((nHeight == -1) && (nAlternative == 0)); }
215 void SetMemPool() { nHeight = -1; nAlternative = -1; }
216 bool IsMemPool() const { return ((nHeight == -1) && (nAlternative == -1)); }
220 /** Position on disk for a particular transaction. */
224 CDiskBlockPos blockPos;
227 CDiskTxPos(bool fInMemPool = false)
231 blockPos.SetMemPool();
235 CDiskTxPos(const CDiskBlockPos &block, unsigned int nTxPosIn) : blockPos(block), nTxPos(nTxPosIn) { }
239 READWRITE(VARINT(nTxPos));
242 void SetNull() { blockPos.SetNull(); nTxPos = 0; }
243 bool IsNull() const { return blockPos.IsNull(); }
244 bool IsMemPool() const { return blockPos.IsMemPool(); }
246 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
248 return (a.blockPos == b.blockPos &&
249 a.nTxPos == b.nTxPos);
252 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
258 std::string ToString() const
262 else if (blockPos.IsMemPool())
265 return strprintf("(%s, nTxPos=%u)", blockPos.GetFileName("").string().c_str(), nTxPos);
270 printf("%s", ToString().c_str());
276 /** An inpoint - a combination of a transaction and an index n into its vin */
283 CInPoint() { SetNull(); }
284 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
285 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
286 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
291 /** An outpoint - a combination of a transaction hash and an index n into its vout */
298 COutPoint() { SetNull(); }
299 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
300 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
301 void SetNull() { hash = 0; n = (unsigned int) -1; }
302 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
304 friend bool operator<(const COutPoint& a, const COutPoint& b)
306 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
309 friend bool operator==(const COutPoint& a, const COutPoint& b)
311 return (a.hash == b.hash && a.n == b.n);
314 friend bool operator!=(const COutPoint& a, const COutPoint& b)
319 std::string ToString() const
321 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
326 printf("%s\n", ToString().c_str());
333 /** An input of a transaction. It contains the location of the previous
334 * transaction's output that it claims and a signature that matches the
335 * output's public key.
342 unsigned int nSequence;
346 nSequence = std::numeric_limits<unsigned int>::max();
349 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
352 scriptSig = scriptSigIn;
353 nSequence = nSequenceIn;
356 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
358 prevout = COutPoint(hashPrevTx, nOut);
359 scriptSig = scriptSigIn;
360 nSequence = nSequenceIn;
366 READWRITE(scriptSig);
367 READWRITE(nSequence);
372 return (nSequence == std::numeric_limits<unsigned int>::max());
375 friend bool operator==(const CTxIn& a, const CTxIn& b)
377 return (a.prevout == b.prevout &&
378 a.scriptSig == b.scriptSig &&
379 a.nSequence == b.nSequence);
382 friend bool operator!=(const CTxIn& a, const CTxIn& b)
387 std::string ToStringShort() const
389 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
392 std::string ToString() const
396 str += prevout.ToString();
397 if (prevout.IsNull())
398 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
400 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
401 if (nSequence != std::numeric_limits<unsigned int>::max())
402 str += strprintf(", nSequence=%u", nSequence);
409 printf("%s\n", ToString().c_str());
416 /** An output of a transaction. It contains the public key that the next input
417 * must be able to sign with to claim it.
423 CScript scriptPubKey;
430 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
433 scriptPubKey = scriptPubKeyIn;
439 READWRITE(scriptPubKey);
445 scriptPubKey.clear();
450 return (nValue == -1);
456 scriptPubKey.clear();
461 return (nValue == 0 && scriptPubKey.empty());
464 uint256 GetHash() const
466 return SerializeHash(*this);
469 friend bool operator==(const CTxOut& a, const CTxOut& b)
471 return (a.nValue == b.nValue &&
472 a.scriptPubKey == b.scriptPubKey);
475 friend bool operator!=(const CTxOut& a, const CTxOut& b)
480 std::string ToStringShort() const
482 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
485 std::string ToString() const
487 if (IsEmpty()) return "CTxOut(empty)";
488 if (scriptPubKey.size() < 6)
489 return "CTxOut(error)";
490 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
495 printf("%s\n", ToString().c_str());
509 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
511 /** The basic transaction that is broadcasted on the network and contained in
512 * blocks. A transaction can contain multiple inputs and outputs.
517 static const int CURRENT_VERSION=1;
520 std::vector<CTxIn> vin;
521 std::vector<CTxOut> vout;
522 unsigned int nLockTime;
524 // Denial-of-service detection:
526 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
535 READWRITE(this->nVersion);
536 nVersion = this->nVersion;
540 READWRITE(nLockTime);
545 nVersion = CTransaction::CURRENT_VERSION;
546 nTime = GetAdjustedTime();
550 nDoS = 0; // Denial-of-service prevention
555 return (vin.empty() && vout.empty());
558 uint256 GetHash() const
560 return SerializeHash(*this);
563 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
565 // Time based nLockTime implemented in 0.1.6
568 if (nBlockHeight == 0)
569 nBlockHeight = nBestHeight;
571 nBlockTime = GetAdjustedTime();
572 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
574 BOOST_FOREACH(const CTxIn& txin, vin)
580 bool IsNewerThan(const CTransaction& old) const
582 if (vin.size() != old.vin.size())
584 for (unsigned int i = 0; i < vin.size(); i++)
585 if (vin[i].prevout != old.vin[i].prevout)
589 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
590 for (unsigned int i = 0; i < vin.size(); i++)
592 if (vin[i].nSequence != old.vin[i].nSequence)
594 if (vin[i].nSequence <= nLowest)
597 nLowest = vin[i].nSequence;
599 if (old.vin[i].nSequence < nLowest)
602 nLowest = old.vin[i].nSequence;
609 bool IsCoinBase() const
611 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
614 bool IsCoinStake() const
616 // ppcoin: the coin stake transaction is marked with the first output empty
617 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
620 /** Check for standard transaction types
621 @return True if all outputs (scriptPubKeys) use only standard transaction forms
623 bool IsStandard() const;
625 /** Check for standard transaction types
626 @param[in] mapInputs Map of previous transactions that have outputs we're spending
627 @return True if all inputs (scriptSigs) use only standard transaction forms
628 @see CTransaction::FetchInputs
630 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
632 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
633 @return number of sigops this transaction's outputs will produce when spent
634 @see CTransaction::FetchInputs
636 unsigned int GetLegacySigOpCount() const;
638 /** Count ECDSA signature operations in pay-to-script-hash inputs.
640 @param[in] mapInputs Map of previous transactions that have outputs we're spending
641 @return maximum number of sigops required to validate this transaction's inputs
642 @see CTransaction::FetchInputs
644 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
646 /** Amount of bitcoins spent by this transaction.
647 @return sum of all outputs (note: does not include fees)
649 int64 GetValueOut() const
652 BOOST_FOREACH(const CTxOut& txout, vout)
654 nValueOut += txout.nValue;
655 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
656 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
661 /** Amount of bitcoins coming in to this transaction
662 Note that lightweight clients may not know anything besides the hash of previous transactions,
663 so may not be able to calculate this.
665 @param[in] mapInputs Map of previous transactions that have outputs we're spending
666 @return Sum of value of all inputs (scriptSigs)
667 @see CTransaction::FetchInputs
669 int64 GetValueIn(const MapPrevTx& mapInputs) const;
671 static bool AllowFree(double dPriority)
673 // Large (in bytes) low-priority (new, small-coin) transactions
675 return dPriority > COIN * 144 / 250;
678 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
680 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
682 CAutoFile filein = CAutoFile(OpenBlockFile(pos.blockPos, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
684 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
687 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
688 return error("CTransaction::ReadFromDisk() : fseek failed");
693 catch (std::exception &e) {
694 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
697 // Return file pointer
700 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
701 return error("CTransaction::ReadFromDisk() : second fseek failed");
702 *pfileRet = filein.release();
707 friend bool operator==(const CTransaction& a, const CTransaction& b)
709 return (a.nVersion == b.nVersion &&
710 a.nTime == b.nTime &&
713 a.nLockTime == b.nLockTime);
716 friend bool operator!=(const CTransaction& a, const CTransaction& b)
721 std::string ToStringShort() const
724 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
728 std::string ToString() const
731 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
732 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
733 GetHash().ToString().substr(0,10).c_str(),
739 for (unsigned int i = 0; i < vin.size(); i++)
740 str += " " + vin[i].ToString() + "\n";
741 for (unsigned int i = 0; i < vout.size(); i++)
742 str += " " + vout[i].ToString() + "\n";
748 printf("%s", ToString().c_str());
752 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
753 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
754 bool ReadFromDisk(COutPoint prevout);
755 bool DisconnectInputs(CTxDB& txdb);
757 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
759 @param[in] txdb Transaction database
760 @param[in] mapTestPool List of pending changes to the transaction index database
761 @param[in] fBlock True if being called to add a new best-block to the chain
762 @param[in] fMiner True if being called by CreateNewBlock
763 @param[out] inputsRet Pointers to this transaction's inputs
764 @param[out] fInvalid returns true if transaction is invalid
765 @return Returns true if all inputs are in txdb or mapTestPool
767 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
768 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
770 /** Sanity check previous transactions, then, if all checks succeed,
771 mark them as spent by this transaction.
773 @param[in] inputs Previous transactions (from FetchInputs)
774 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
775 @param[in] posThisTx Position of this transaction on disk
776 @param[in] pindexBlock
777 @param[in] fBlock true if called from ConnectBlock
778 @param[in] fMiner true if called from CreateNewBlock
779 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
780 @return Returns true if all checks succeed
782 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
783 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
784 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
785 bool ClientConnectInputs();
786 bool CheckTransaction() const;
787 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
788 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
791 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
795 /** wrapper for CTxOut that provides a more compact serialization */
796 class CTxOutCompressor
802 static uint64 CompressAmount(uint64 nAmount);
803 static uint64 DecompressAmount(uint64 nAmount);
805 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
807 IMPLEMENT_SERIALIZE(({
809 uint64 nVal = CompressAmount(txout.nValue);
810 READWRITE(VARINT(nVal));
813 READWRITE(VARINT(nVal));
814 txout.nValue = DecompressAmount(nVal);
816 CScriptCompressor cscript(REF(txout.scriptPubKey));
821 /** Undo information for a CTxIn
823 * Contains the prevout's CTxOut being spent, and if this was the
824 * last output of the affected transaction, its metadata as well
825 * (coinbase or not, height, transaction version)
830 CTxOut txout; // the txout data before being spent
831 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
832 unsigned int nHeight; // if the outpoint was the last unspent: its height
833 int nVersion; // if the outpoint was the last unspent: its version
835 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
836 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
838 unsigned int GetSerializeSize(int nType, int nVersion) const {
839 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
840 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
841 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
844 template<typename Stream>
845 void Serialize(Stream &s, int nType, int nVersion) const {
846 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
848 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
849 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
852 template<typename Stream>
853 void Unserialize(Stream &s, int nType, int nVersion) {
854 unsigned int nCode = 0;
855 ::Unserialize(s, VARINT(nCode), nType, nVersion);
857 fCoinBase = nCode & 1;
859 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
860 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
864 /** Undo information for a CTransaction */
868 std::vector<CTxInUndo> vprevout;
875 /** Undo information for a CBlock */
879 std::vector<CTxUndo> vtxundo;
886 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
891 * - unspentness bitvector, for vout[2] and further; least significant byte first
892 * - the non-spent CTxOuts (via CTxOutCompressor)
895 * The nCode value consists of:
896 * - bit 1: IsCoinBase()
897 * - bit 2: vout[0] is not spent
898 * - bit 4: vout[1] is not spent
899 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
900 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
901 * least one non-spent output).
903 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
904 * <><><--------------------------------------------><---->
906 * version code vout[1] height
909 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
910 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
911 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
912 * * 8358: compact amount representation for 60000000000 (600 BTC)
913 * * 00: special txout type pay-to-pubkey-hash
914 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
918 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
919 * <><><--><--------------------------------------------------><----------------------------------------------><---->
921 * version code unspentness vout[4] vout[16] height
924 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
925 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
926 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
927 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
928 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
929 * * 00: special txout type pay-to-pubkey-hash
930 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
931 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
932 * * bbd123: compact amount representation for 110397 (0.001 BTC)
933 * * 00: special txout type pay-to-pubkey-hash
934 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
940 // whether transaction is a coinbase
943 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
944 std::vector<CTxOut> vout;
946 // at which height this transaction was included in the active blockchain
949 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
950 // as new tx version will probably only be introduced at certain heights
953 // construct a CCoins from a CTransaction, at a given height
954 CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
957 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
959 // remove spent outputs at the end of vout
961 while (vout.size() > 0 && vout.back().IsNull())
966 friend bool operator==(const CCoins &a, const CCoins &b) {
967 return a.fCoinBase == b.fCoinBase &&
968 a.nHeight == b.nHeight &&
969 a.nVersion == b.nVersion &&
972 friend bool operator!=(const CCoins &a, const CCoins &b) {
976 // calculate number of bytes for the bitmask, and its number of non-zero bytes
977 // each bit in the bitmask represents the availability of one output, but the
978 // availabilities of the first two outputs are encoded separately
979 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
980 unsigned int nLastUsedByte = 0;
981 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
983 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
984 if (!vout[2+b*8+i].IsNull()) {
990 nLastUsedByte = b + 1;
994 nBytes += nLastUsedByte;
997 bool IsCoinBase() const {
1001 unsigned int GetSerializeSize(int nType, int nVersion) const {
1002 unsigned int nSize = 0;
1003 unsigned int nMaskSize = 0, nMaskCode = 0;
1004 CalcMaskSize(nMaskSize, nMaskCode);
1005 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
1006 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
1007 assert(fFirst || fSecond || nMaskCode);
1008 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
1010 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
1011 // size of header code
1012 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
1013 // spentness bitmask
1016 for (unsigned int i = 0; i < vout.size(); i++)
1017 if (!vout[i].IsNull())
1018 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
1020 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
1024 template<typename Stream>
1025 void Serialize(Stream &s, int nType, int nVersion) const {
1026 unsigned int nMaskSize = 0, nMaskCode = 0;
1027 CalcMaskSize(nMaskSize, nMaskCode);
1028 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
1029 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
1030 assert(fFirst || fSecond || nMaskCode);
1031 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
1033 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
1035 ::Serialize(s, VARINT(nCode), nType, nVersion);
1036 // spentness bitmask
1037 for (unsigned int b = 0; b<nMaskSize; b++) {
1038 unsigned char chAvail = 0;
1039 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
1040 if (!vout[2+b*8+i].IsNull())
1041 chAvail |= (1 << i);
1042 ::Serialize(s, chAvail, nType, nVersion);
1045 for (unsigned int i = 0; i < vout.size(); i++) {
1046 if (!vout[i].IsNull())
1047 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
1050 ::Serialize(s, VARINT(nHeight), nType, nVersion);
1053 template<typename Stream>
1054 void Unserialize(Stream &s, int nType, int nVersion) {
1055 unsigned int nCode = 0;
1057 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
1059 ::Unserialize(s, VARINT(nCode), nType, nVersion);
1060 fCoinBase = nCode & 1;
1061 std::vector<bool> vAvail(2, false);
1062 vAvail[0] = nCode & 2;
1063 vAvail[1] = nCode & 4;
1064 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
1065 // spentness bitmask
1066 while (nMaskCode > 0) {
1067 unsigned char chAvail = 0;
1068 ::Unserialize(s, chAvail, nType, nVersion);
1069 for (unsigned int p = 0; p < 8; p++) {
1070 bool f = (chAvail & (1 << p)) != 0;
1071 vAvail.push_back(f);
1077 vout.assign(vAvail.size(), CTxOut());
1078 for (unsigned int i = 0; i < vAvail.size(); i++) {
1080 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1083 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1087 // mark an outpoint spent, and construct undo information
1088 bool Spend(const COutPoint &out, CTxInUndo &undo) {
1089 if (out.n >= vout.size())
1091 if (vout[out.n].IsNull())
1093 undo = CTxInUndo(vout[out.n]);
1094 vout[out.n].SetNull();
1096 if (vout.size() == 0) {
1097 undo.nHeight = nHeight;
1098 undo.fCoinBase = fCoinBase;
1099 undo.nVersion = this->nVersion;
1104 // mark a vout spent
1105 bool Spend(int nPos) {
1107 COutPoint out(0, nPos);
1108 return Spend(out, undo);
1111 // check whether a particular output is still available
1112 bool IsAvailable(unsigned int nPos) const {
1113 return (nPos < vout.size() && !vout[nPos].IsNull());
1116 // check whether the entire CCoins is spent
1117 // note that only !IsPruned() CCoins can be serialized
1118 bool IsPruned() const {
1119 BOOST_FOREACH(const CTxOut &out, vout)
1129 /** A transaction with a merkle branch linking it to the block chain. */
1130 class CMerkleTx : public CTransaction
1134 std::vector<uint256> vMerkleBranch;
1138 mutable bool fMerkleVerified;
1146 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1155 fMerkleVerified = false;
1161 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1162 nVersion = this->nVersion;
1163 READWRITE(hashBlock);
1164 READWRITE(vMerkleBranch);
1169 int SetMerkleBranch(const CBlock* pblock=NULL);
1170 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1171 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1172 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1173 int GetBlocksToMaturity() const;
1174 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
1175 bool AcceptToMemoryPool();
1181 /** A txdb record that contains the disk location of a transaction and the
1182 * locations of transactions that spend its outputs. vSpent is really only
1183 * used as a flag, but having the location is very helpful for debugging.
1189 std::vector<CDiskTxPos> vSpent;
1196 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1199 vSpent.resize(nOutputs);
1204 if (!(nType & SER_GETHASH))
1205 READWRITE(nVersion);
1218 return pos.IsNull();
1221 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1223 return (a.pos == b.pos &&
1224 a.vSpent == b.vSpent);
1227 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1231 int GetDepthInMainChain() const;
1239 /** Nodes collect new transactions into a block, hash them into a hash tree,
1240 * and scan through nonce values to make the block's hash satisfy proof-of-work
1241 * requirements. When they solve the proof-of-work, they broadcast the block
1242 * to everyone and the block is added to the block chain. The first transaction
1243 * in the block is a special one that creates a new coin owned by the creator
1246 * Blocks are appended to blk0001.dat files on disk. Their location on disk
1247 * is indexed by CBlockIndex objects in memory.
1253 static const int CURRENT_VERSION=6;
1255 uint256 hashPrevBlock;
1256 uint256 hashMerkleRoot;
1259 unsigned int nNonce;
1262 std::vector<CTransaction> vtx;
1264 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
1265 std::vector<unsigned char> vchBlockSig;
1268 mutable std::vector<uint256> vMerkleTree;
1270 // Denial-of-service detection:
1272 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1281 READWRITE(this->nVersion);
1282 nVersion = this->nVersion;
1283 READWRITE(hashPrevBlock);
1284 READWRITE(hashMerkleRoot);
1289 // ConnectBlock depends on vtx following header to generate CDiskTxPos
1290 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1293 READWRITE(vchBlockSig);
1297 const_cast<CBlock*>(this)->vtx.clear();
1298 const_cast<CBlock*>(this)->vchBlockSig.clear();
1304 nVersion = CBlock::CURRENT_VERSION;
1311 vchBlockSig.clear();
1312 vMerkleTree.clear();
1318 return (nBits == 0);
1321 uint256 GetHash() const
1323 return scrypt_blockhash(CVOIDBEGIN(nVersion));
1326 int64 GetBlockTime() const
1328 return (int64)nTime;
1331 void UpdateTime(const CBlockIndex* pindexPrev);
1333 // ppcoin: entropy bit for stake modifier if chosen by modifier
1334 unsigned int GetStakeEntropyBit(unsigned int nTime) const
1336 // Protocol switch to support p2pool at novacoin block #9689
1337 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
1339 // Take last bit of block hash as entropy bit
1340 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
1341 if (fDebug && GetBoolArg("-printstakemodifier"))
1342 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1345 // Before novacoin block #9689 - old protocol
1346 uint160 hashSig = Hash160(vchBlockSig);
1347 if (fDebug && GetBoolArg("-printstakemodifier"))
1348 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
1349 hashSig >>= 159; // take the first bit of the hash
1350 if (fDebug && GetBoolArg("-printstakemodifier"))
1351 printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
1352 return hashSig.Get64();
1355 // ppcoin: two types of block: proof-of-work or proof-of-stake
1356 bool IsProofOfStake() const
1358 return (vtx.size() > 1 && vtx[1].IsCoinStake());
1361 bool IsProofOfWork() const
1363 return !IsProofOfStake();
1366 std::pair<COutPoint, unsigned int> GetProofOfStake() const
1368 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1371 // ppcoin: get max transaction timestamp
1372 int64 GetMaxTransactionTime() const
1374 int64 maxTransactionTime = 0;
1375 BOOST_FOREACH(const CTransaction& tx, vtx)
1376 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1377 return maxTransactionTime;
1380 uint256 BuildMerkleTree() const
1382 vMerkleTree.clear();
1383 BOOST_FOREACH(const CTransaction& tx, vtx)
1384 vMerkleTree.push_back(tx.GetHash());
1386 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1388 for (int i = 0; i < nSize; i += 2)
1390 int i2 = std::min(i+1, nSize-1);
1391 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1392 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1396 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1399 std::vector<uint256> GetMerkleBranch(int nIndex) const
1401 if (vMerkleTree.empty())
1403 std::vector<uint256> vMerkleBranch;
1405 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1407 int i = std::min(nIndex^1, nSize-1);
1408 vMerkleBranch.push_back(vMerkleTree[j+i]);
1412 return vMerkleBranch;
1415 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1419 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1422 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1424 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1431 bool WriteToDisk(CDiskBlockPos &pos)
1433 // Open history file to append
1434 pos.MakeUnique(GetDataDir());
1435 CAutoFile fileout = CAutoFile(OpenBlockFile(pos, "ab"), SER_DISK, CLIENT_VERSION);
1437 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1442 // Flush stdio buffers and commit to disk before returning
1444 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1445 FileCommit(fileout);
1450 bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1454 // Open history file to read
1455 CAutoFile filein = CAutoFile(OpenBlockFile(pos, "rb"), SER_DISK, CLIENT_VERSION);
1457 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1458 if (!fReadTransactions)
1459 filein.nType |= SER_BLOCKHEADERONLY;
1465 catch (std::exception &e) {
1466 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1470 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1471 return error("CBlock::ReadFromDisk() : errors in block header");
1480 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1481 GetHash().ToString().c_str(),
1483 hashPrevBlock.ToString().c_str(),
1484 hashMerkleRoot.ToString().c_str(),
1485 nTime, nBits, nNonce,
1487 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1488 for (unsigned int i = 0; i < vtx.size(); i++)
1493 printf(" vMerkleTree: ");
1494 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1495 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1500 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1501 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1502 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1503 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1504 bool AddToBlockIndex(const CDiskBlockPos &pos);
1505 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1507 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1508 bool SignBlock(CWallet& keystore);
1509 bool CheckBlockSignature(bool fProofOfStake) const;
1512 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1520 /** The block chain is a tree shaped structure starting with the
1521 * genesis block at the root, with each block potentially having multiple
1522 * candidates to be the next block. pprev and pnext link a path through the
1523 * main/longest chain. A blockindex may have multiple pprev pointing back
1524 * to it, but pnext will only point forward to the longest branch, or will
1525 * be null if the block is not part of the longest chain.
1530 const uint256* phashBlock;
1533 uint256 nChainTrust; // ppcoin: trust score of block chain
1535 unsigned int nAlternative;
1540 unsigned int nFlags;
1543 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1544 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1545 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1548 uint64 nStakeModifier; // hash modifier for proof-of-stake
1549 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1551 // proof-of-stake specific fields
1552 COutPoint prevoutStake;
1553 unsigned int nStakeTime;
1554 uint256 hashProofOfStake;
1558 uint256 hashMerkleRoot;
1561 unsigned int nNonce;
1574 nStakeModifierChecksum = 0;
1575 hashProofOfStake = 0;
1576 prevoutStake.SetNull();
1587 CBlockIndex(CBlock& block)
1598 nStakeModifierChecksum = 0;
1599 hashProofOfStake = 0;
1600 if (block.IsProofOfStake())
1603 prevoutStake = block.vtx[1].vin[0].prevout;
1604 nStakeTime = block.vtx[1].nTime;
1608 prevoutStake.SetNull();
1613 nVersion = block.nVersion;
1614 hashMerkleRoot = block.hashMerkleRoot;
1615 nTime = block.nTime;
1616 nBits = block.nBits;
1617 nNonce = block.nNonce;
1620 CDiskBlockPos GetBlockPos() const {
1621 return CDiskBlockPos(nHeight, nAlternative);
1624 CBlock GetBlockHeader() const
1627 block.nVersion = nVersion;
1629 block.hashPrevBlock = pprev->GetBlockHash();
1630 block.hashMerkleRoot = hashMerkleRoot;
1631 block.nTime = nTime;
1632 block.nBits = nBits;
1633 block.nNonce = nNonce;
1637 uint256 GetBlockHash() const
1642 int64 GetBlockTime() const
1644 return (int64)nTime;
1647 uint256 GetBlockTrust() const;
1649 bool IsInMainChain() const
1651 return (pnext || this == pindexBest);
1654 bool CheckIndex() const
1659 enum { nMedianTimeSpan=11 };
1661 int64 GetMedianTimePast() const
1663 int64 pmedian[nMedianTimeSpan];
1664 int64* pbegin = &pmedian[nMedianTimeSpan];
1665 int64* pend = &pmedian[nMedianTimeSpan];
1667 const CBlockIndex* pindex = this;
1668 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1669 *(--pbegin) = pindex->GetBlockTime();
1671 std::sort(pbegin, pend);
1672 return pbegin[(pend - pbegin)/2];
1675 int64 GetMedianTime() const
1677 const CBlockIndex* pindex = this;
1678 for (int i = 0; i < nMedianTimeSpan/2; i++)
1681 return GetBlockTime();
1682 pindex = pindex->pnext;
1684 return pindex->GetMedianTimePast();
1688 * Returns true if there are nRequired or more blocks of minVersion or above
1689 * in the last nToCheck blocks, starting at pstart and going backwards.
1691 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1692 unsigned int nRequired, unsigned int nToCheck);
1695 bool IsProofOfWork() const
1697 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1700 bool IsProofOfStake() const
1702 return (nFlags & BLOCK_PROOF_OF_STAKE);
1705 void SetProofOfStake()
1707 nFlags |= BLOCK_PROOF_OF_STAKE;
1710 unsigned int GetStakeEntropyBit() const
1712 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1715 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1717 if (nEntropyBit > 1)
1719 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1723 bool GeneratedStakeModifier() const
1725 return (nFlags & BLOCK_STAKE_MODIFIER);
1728 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1730 nStakeModifier = nModifier;
1731 if (fGeneratedStakeModifier)
1732 nFlags |= BLOCK_STAKE_MODIFIER;
1735 std::string ToString() const
1737 return strprintf("CBlockIndex(nprev=%p, pnext=%p nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1738 pprev, pnext, nHeight,
1739 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1740 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1741 nStakeModifier, nStakeModifierChecksum,
1742 hashProofOfStake.ToString().c_str(),
1743 prevoutStake.ToString().c_str(), nStakeTime,
1744 hashMerkleRoot.ToString().c_str(),
1745 GetBlockHash().ToString().c_str());
1750 printf("%s\n", ToString().c_str());
1756 /** Used to marshal pointers into hashes for db storage. */
1757 class CDiskBlockIndex : public CBlockIndex
1773 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1775 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1776 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1781 if (!(nType & SER_GETHASH))
1782 READWRITE(nVersion);
1784 READWRITE(hashNext);
1786 READWRITE(nAlternative);
1788 READWRITE(nMoneySupply);
1790 READWRITE(nStakeModifier);
1791 if (IsProofOfStake())
1793 READWRITE(prevoutStake);
1794 READWRITE(nStakeTime);
1795 READWRITE(hashProofOfStake);
1799 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1800 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1801 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1805 READWRITE(this->nVersion);
1806 READWRITE(hashPrev);
1807 READWRITE(hashMerkleRoot);
1811 READWRITE(blockHash);
1814 uint256 GetBlockHash() const
1816 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1820 block.nVersion = nVersion;
1821 block.hashPrevBlock = hashPrev;
1822 block.hashMerkleRoot = hashMerkleRoot;
1823 block.nTime = nTime;
1824 block.nBits = nBits;
1825 block.nNonce = nNonce;
1827 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1832 std::string ToString() const
1834 std::string str = "CDiskBlockIndex(";
1835 str += CBlockIndex::ToString();
1836 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1837 GetBlockHash().ToString().c_str(),
1838 hashPrev.ToString().c_str(),
1839 hashNext.ToString().c_str());
1845 printf("%s\n", ToString().c_str());
1856 /** Describes a place in the block chain to another node such that if the
1857 * other node doesn't have the same branch, it can find a recent common trunk.
1858 * The further back it is, the further before the fork it may be.
1863 std::vector<uint256> vHave;
1870 explicit CBlockLocator(const CBlockIndex* pindex)
1875 explicit CBlockLocator(uint256 hashBlock)
1877 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1878 if (mi != mapBlockIndex.end())
1882 CBlockLocator(const std::vector<uint256>& vHaveIn)
1889 if (!(nType & SER_GETHASH))
1890 READWRITE(nVersion);
1901 return vHave.empty();
1904 void Set(const CBlockIndex* pindex)
1910 vHave.push_back(pindex->GetBlockHash());
1912 // Exponentially larger steps back
1913 for (int i = 0; pindex && i < nStep; i++)
1914 pindex = pindex->pprev;
1915 if (vHave.size() > 10)
1918 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1921 int GetDistanceBack()
1923 // Retrace how far back it was in the sender's branch
1926 BOOST_FOREACH(const uint256& hash, vHave)
1928 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1929 if (mi != mapBlockIndex.end())
1931 CBlockIndex* pindex = (*mi).second;
1932 if (pindex->IsInMainChain())
1942 CBlockIndex* GetBlockIndex()
1944 // Find the first block the caller has in the main chain
1945 BOOST_FOREACH(const uint256& hash, vHave)
1947 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1948 if (mi != mapBlockIndex.end())
1950 CBlockIndex* pindex = (*mi).second;
1951 if (pindex->IsInMainChain())
1955 return pindexGenesisBlock;
1958 uint256 GetBlockHash()
1960 // Find the first block the caller has in the main chain
1961 BOOST_FOREACH(const uint256& hash, vHave)
1963 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1964 if (mi != mapBlockIndex.end())
1966 CBlockIndex* pindex = (*mi).second;
1967 if (pindex->IsInMainChain())
1971 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1976 CBlockIndex* pindex = GetBlockIndex();
1979 return pindex->nHeight;
1993 mutable CCriticalSection cs;
1994 std::map<uint256, CTransaction> mapTx;
1995 std::map<COutPoint, CInPoint> mapNextTx;
1997 bool accept(CTxDB& txdb, CTransaction &tx,
1998 bool fCheckInputs, bool* pfMissingInputs);
1999 bool addUnchecked(const uint256& hash, CTransaction &tx);
2000 bool remove(CTransaction &tx);
2002 void queryHashes(std::vector<uint256>& vtxid);
2004 unsigned long size()
2007 return mapTx.size();
2010 bool exists(uint256 hash)
2012 return (mapTx.count(hash) != 0);
2015 CTransaction& lookup(uint256 hash)
2021 extern CTxMemPool mempool;