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;
35 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
36 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
37 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
38 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
40 static const int64 MIN_TX_FEE = CENT;
41 static const int64 MIN_RELAY_TX_FEE = CENT;
42 static const int64 MAX_MONEY = 2000000000 * COIN;
43 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
44 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
45 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
47 static const unsigned int ENTROPY_SWITCH_TIME = 1362791041; // Sat, 09 Mar 2013 01:04:01 GMT
48 static const unsigned int STAKE_SWITCH_TIME = 1371686400; // Thu, 20 Jun 2013 00:00:00 GMT
49 static const unsigned int TARGETS_SWITCH_TIME = 1374278400; // Sat, 20 Jul 2013 00:00:00 GMT
50 static const unsigned int CHAINCHECKS_SWITCH_TIME = 1379635200; // Fri, 20 Sep 2013 00:00:00 GMT
51 static const unsigned int STAKECURVE_SWITCH_TIME = 1382227200; // Sun, 20 Oct 2013 00:00:00 GMT
52 static const unsigned int OUTPUT_SWITCH_TIME = 1398916800; // Thu, 01 May 2014 04:00:00 GMT
55 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
56 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
57 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
60 static const int fHaveUPnP = true;
62 static const int fHaveUPnP = false;
65 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
66 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
68 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
69 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
71 extern libzerocoin::Params* ZCParams;
72 extern CScript COINBASE_FLAGS;
73 extern CCriticalSection cs_main;
74 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
75 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
76 extern CBlockIndex* pindexGenesisBlock;
77 extern unsigned int nStakeMinAge;
78 extern unsigned int nNodeLifespan;
79 extern int nCoinbaseMaturity;
80 extern int nBestHeight;
81 extern uint256 nBestChainTrust;
82 extern uint256 nBestInvalidTrust;
83 extern uint256 hashBestChain;
84 extern CBlockIndex* pindexBest;
85 extern unsigned int nTransactionsUpdated;
86 extern uint64 nLastBlockTx;
87 extern uint64 nLastBlockSize;
88 extern int64 nLastCoinStakeSearchInterval;
89 extern const std::string strMessageMagic;
90 extern int64 nTimeBestReceived;
91 extern CCriticalSection cs_setpwalletRegistered;
92 extern std::set<CWallet*> setpwalletRegistered;
93 extern unsigned char pchMessageStart[4];
94 extern std::map<uint256, CBlock*> mapOrphanBlocks;
97 extern int64 nTransactionFee;
98 extern int64 nMinimumInputValue;
99 extern bool fUseFastIndex;
100 extern unsigned int nDerivationMethodIndex;
102 // Minimum disk space required - used in CheckDiskSpace()
103 static const uint64 nMinDiskSpace = 52428800;
113 void RegisterWallet(CWallet* pwalletIn);
114 void UnregisterWallet(CWallet* pwalletIn);
115 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
116 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
117 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
118 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
119 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
120 bool LoadBlockIndex(bool fAllowNew=true);
121 void PrintBlockTree();
122 CBlockIndex* FindBlockByHeight(int nHeight);
123 bool ProcessMessages(CNode* pfrom);
124 bool SendMessages(CNode* pto, bool fSendTrickle);
125 bool LoadExternalBlockFile(FILE* fileIn);
127 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
128 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
129 int64 GetProofOfWorkReward(unsigned int nBits);
130 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
131 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
132 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
133 int GetNumBlocksOfPeers();
134 bool IsInitialBlockDownload();
135 std::string GetWarnings(std::string strFor);
136 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow);
137 uint256 WantedByOrphan(const CBlock* pblockOrphan);
138 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
139 void StakeMiner(CWallet *pwallet);
140 void ResendWalletTransactions();
142 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
151 READWRITE(VARINT(nFile));
152 READWRITE(VARINT(nPos));
155 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
156 return (a.nFile == b.nFile && a.nPos == b.nPos);
159 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
163 void SetNull() { nFile = -1; nPos = 0; }
164 bool IsNull() const { return (nFile == -1); }
168 /** An inpoint - a combination of a transaction and an index n into its vin */
175 CInPoint() { SetNull(); }
176 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
177 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
178 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
183 /** An outpoint - a combination of a transaction hash and an index n into its vout */
190 COutPoint() { SetNull(); }
191 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
192 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
193 void SetNull() { hash = 0; n = (unsigned int) -1; }
194 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
196 friend bool operator<(const COutPoint& a, const COutPoint& b)
198 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
201 friend bool operator==(const COutPoint& a, const COutPoint& b)
203 return (a.hash == b.hash && a.n == b.n);
206 friend bool operator!=(const COutPoint& a, const COutPoint& b)
211 std::string ToString() const
213 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
218 printf("%s\n", ToString().c_str());
225 /** An input of a transaction. It contains the location of the previous
226 * transaction's output that it claims and a signature that matches the
227 * output's public key.
234 unsigned int nSequence;
238 nSequence = std::numeric_limits<unsigned int>::max();
241 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
244 scriptSig = scriptSigIn;
245 nSequence = nSequenceIn;
248 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
250 prevout = COutPoint(hashPrevTx, nOut);
251 scriptSig = scriptSigIn;
252 nSequence = nSequenceIn;
258 READWRITE(scriptSig);
259 READWRITE(nSequence);
264 return (nSequence == std::numeric_limits<unsigned int>::max());
267 friend bool operator==(const CTxIn& a, const CTxIn& b)
269 return (a.prevout == b.prevout &&
270 a.scriptSig == b.scriptSig &&
271 a.nSequence == b.nSequence);
274 friend bool operator!=(const CTxIn& a, const CTxIn& b)
279 std::string ToStringShort() const
281 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
284 std::string ToString() const
288 str += prevout.ToString();
289 if (prevout.IsNull())
290 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
292 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
293 if (nSequence != std::numeric_limits<unsigned int>::max())
294 str += strprintf(", nSequence=%u", nSequence);
301 printf("%s\n", ToString().c_str());
308 /** An output of a transaction. It contains the public key that the next input
309 * must be able to sign with to claim it.
315 CScript scriptPubKey;
322 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
325 scriptPubKey = scriptPubKeyIn;
331 READWRITE(scriptPubKey);
337 scriptPubKey.clear();
342 return (nValue == -1);
348 scriptPubKey.clear();
353 return (nValue == 0 && scriptPubKey.empty());
356 uint256 GetHash() const
358 return SerializeHash(*this);
361 friend bool operator==(const CTxOut& a, const CTxOut& b)
363 return (a.nValue == b.nValue &&
364 a.scriptPubKey == b.scriptPubKey);
367 friend bool operator!=(const CTxOut& a, const CTxOut& b)
372 std::string ToStringShort() const
374 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0, 10).c_str());
377 std::string ToString() const
379 if (IsEmpty()) return "CTxOut(empty)";
380 if (scriptPubKey.size() < 6)
381 return "CTxOut(error)";
382 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
387 printf("%s\n", ToString().c_str());
401 // Modes for script/signature checking
404 CS_NEVER, // never validate scripts
405 CS_AFTER_CHECKPOINT, // validate scripts after the last checkpoint
406 CS_ALWAYS // always validate scripts
409 /** The basic transaction that is broadcasted on the network and contained in
410 * blocks. A transaction can contain multiple inputs and outputs.
415 static const int CURRENT_VERSION=1;
418 std::vector<CTxIn> vin;
419 std::vector<CTxOut> vout;
420 unsigned int nLockTime;
422 // Denial-of-service detection:
424 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
433 READWRITE(this->nVersion);
434 nVersion = this->nVersion;
438 READWRITE(nLockTime);
443 nVersion = CTransaction::CURRENT_VERSION;
444 nTime = GetAdjustedTime();
448 nDoS = 0; // Denial-of-service prevention
453 return (vin.empty() && vout.empty());
456 uint256 GetHash() const
458 return SerializeHash(*this);
461 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
463 // Time based nLockTime implemented in 0.1.6
466 if (nBlockHeight == 0)
467 nBlockHeight = nBestHeight;
469 nBlockTime = GetAdjustedTime();
470 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
472 BOOST_FOREACH(const CTxIn& txin, vin)
478 bool IsNewerThan(const CTransaction& old) const
480 if (vin.size() != old.vin.size())
482 for (unsigned int i = 0; i < vin.size(); i++)
483 if (vin[i].prevout != old.vin[i].prevout)
487 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
488 for (unsigned int i = 0; i < vin.size(); i++)
490 if (vin[i].nSequence != old.vin[i].nSequence)
492 if (vin[i].nSequence <= nLowest)
495 nLowest = vin[i].nSequence;
497 if (old.vin[i].nSequence < nLowest)
500 nLowest = old.vin[i].nSequence;
507 bool IsCoinBase() const
509 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
512 bool IsCoinStake() const
514 // ppcoin: the coin stake transaction is marked with the first output empty
515 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
518 /** Check for standard transaction types
519 @return True if all outputs (scriptPubKeys) use only standard transaction forms
521 bool IsStandard() const;
523 /** Check for standard transaction types
524 @param[in] mapInputs Map of previous transactions that have outputs we're spending
525 @return True if all inputs (scriptSigs) use only standard transaction forms
526 @see CTransaction::FetchInputs
528 bool AreInputsStandard(CCoinsView& mapInputs) const;
530 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
531 @return number of sigops this transaction's outputs will produce when spent
532 @see CTransaction::FetchInputs
534 unsigned int GetLegacySigOpCount() const;
536 /** Count ECDSA signature operations in pay-to-script-hash inputs.
538 @param[in] mapInputs Map of previous transactions that have outputs we're spending
539 @return maximum number of sigops required to validate this transaction's inputs
540 @see CTransaction::FetchInputs
542 unsigned int GetP2SHSigOpCount(CCoinsView& mapInputs) const;
544 /** Amount of bitcoins spent by this transaction.
545 @return sum of all outputs (note: does not include fees)
547 int64 GetValueOut() const
550 BOOST_FOREACH(const CTxOut& txout, vout)
552 nValueOut += txout.nValue;
553 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
554 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
559 /** Amount of bitcoins coming in to this transaction
560 Note that lightweight clients may not know anything besides the hash of previous transactions,
561 so may not be able to calculate this.
563 @param[in] mapInputs Map of previous transactions that have outputs we're spending
564 @return Sum of value of all inputs (scriptSigs)
565 @see CTransaction::FetchInputs
567 int64 GetValueIn(CCoinsView& mapInputs) const;
569 static bool AllowFree(double dPriority)
571 // Large (in bytes) low-priority (new, small-coin) transactions
573 return dPriority > COIN * 144 / 250;
576 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
578 friend bool operator==(const CTransaction& a, const CTransaction& b)
580 return (a.nVersion == b.nVersion &&
581 a.nTime == b.nTime &&
584 a.nLockTime == b.nLockTime);
587 friend bool operator!=(const CTransaction& a, const CTransaction& b)
592 std::string ToStringShort() const
595 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
599 std::string ToString() const
602 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
603 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
604 GetHash().ToString().substr(0,10).c_str(),
610 for (unsigned int i = 0; i < vin.size(); i++)
611 str += " " + vin[i].ToString() + "\n";
612 for (unsigned int i = 0; i < vout.size(); i++)
613 str += " " + vout[i].ToString() + "\n";
619 printf("%s", ToString().c_str());
623 // Do all possible client-mode checks
624 bool ClientCheckInputs() const;
626 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
627 bool HaveInputs(CCoinsView &view) const;
629 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
630 // This does not modify the UTXO set
631 bool CheckInputs(CCoinsView &view, enum CheckSig_mode csmode, bool fStrictPayToScriptHash=true, bool fStrictEncodings=true, CBlock *pblock=NULL) const;
633 // Apply the effects of this transaction on the UTXO set represented by view
634 bool UpdateCoins(CCoinsView &view, CTxUndo &txundo, int nHeight, unsigned int nBlockTime, const uint256 &txhash) const;
636 // Context-independent validity checks
637 bool CheckTransaction() const;
639 // Try to accept this transaction into the memory pool
640 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
641 bool GetCoinAge(uint64& nCoinAge) const; // Get transaction coin age
643 static CTxOut GetOutputFor(const CTxIn& input, CCoinsView& mapInputs);
647 /** wrapper for CTxOut that provides a more compact serialization */
648 class CTxOutCompressor
654 static uint64 CompressAmount(uint64 nAmount);
655 static uint64 DecompressAmount(uint64 nAmount);
657 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
659 IMPLEMENT_SERIALIZE(({
661 uint64 nVal = CompressAmount(txout.nValue);
662 READWRITE(VARINT(nVal));
665 READWRITE(VARINT(nVal));
666 txout.nValue = DecompressAmount(nVal);
668 CScriptCompressor cscript(REF(txout.scriptPubKey));
673 /** Undo information for a CTxIn
675 * Contains the prevout's CTxOut being spent, and if this was the
676 * last output of the affected transaction, its metadata as well
677 * (coinbase or not, height, transaction version)
682 CTxOut txout; // the txout data before being spent
683 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
684 bool fCoinStake; // if the outpoint was the last unspent: whether it belonged to a coinstake
685 unsigned int nHeight; // if the outpoint was the last unspent: its height
686 int nVersion; // if the outpoint was the last unspent: its version
687 unsigned int nTime; // if the outpoint was the last unspent: its timestamp
688 unsigned int nBlockTime; // if the outpoint was the last unspent: its block timestamp
690 CTxInUndo() : txout(), fCoinBase(false), fCoinStake(false), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) {}
691 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, bool fCoinStakeIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0, int nTimeIn = 0, int nBlockTimeIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), fCoinStake(fCoinStakeIn), nHeight(nHeightIn), nVersion(nVersionIn), nTime(nTimeIn), nBlockTime(nBlockTimeIn) { }
693 unsigned int GetSerializeSize(int nType, int nVersion) const {
694 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
695 ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion) +
696 ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion) +
697 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
698 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
701 template<typename Stream>
702 void Serialize(Stream &s, int nType, int nVersion) const {
703 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
704 ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
705 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
707 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
708 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
711 template<typename Stream>
712 void Unserialize(Stream &s, int nType, int nVersion) {
713 unsigned int nCodeHeight = 0, nCodeTime = 0;
714 ::Unserialize(s, VARINT(nCodeHeight), nType, nVersion);
715 nHeight = nCodeHeight / 2;
716 fCoinBase = nCodeHeight & 1;
717 ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
718 nTime = nCodeTime / 2;
719 fCoinStake = nCodeTime & 1;
720 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
722 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
723 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
727 /** Undo information for a CTransaction */
731 // undo information for all txins
732 std::vector<CTxInUndo> vprevout;
739 /** Undo information for a CBlock */
743 std::vector<CTxUndo> vtxundo; // for all but the coinbase
749 bool WriteToDisk(CDiskBlockPos &pos)
751 // Open history file to append
752 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
754 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
756 // Write index header
757 unsigned int nSize = fileout.GetSerializeSize(*this);
758 fileout << FLATDATA(pchMessageStart) << nSize;
761 long fileOutPos = ftell(fileout);
763 return error("CBlockUndo::WriteToDisk() : ftell failed");
764 pos.nPos = (unsigned int)fileOutPos;
767 // Flush stdio buffers and commit to disk before returning
769 if (!IsInitialBlockDownload())
777 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
782 * - unspentness bitvector, for vout[2] and further; least significant byte first
783 * - the non-spent CTxOuts (via CTxOutCompressor)
785 * - VARINT(nTime + is_coinstake)
786 * - VARINT(nBlockTime)
788 * The nCode value consists of:
789 * - bit 1: IsCoinBase()
790 * - bit 2: vout[0] is not spent
791 * - bit 4: vout[1] is not spent
792 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
793 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
794 * least one non-spent output).
796 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e40f1d75240f1d752
797 * <><><--------------------------------------------><----><------><------>
799 * version code vout[1] height timestamp block timestamp
802 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
803 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
804 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
805 * * 8358: compact amount representation for 60000000000 (600 BTC)
806 * * 00: special txout type pay-to-pubkey-hash
807 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
809 * - time = 1389883712
811 * - block time = 1389883712
814 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b40f1d75240f1d752
815 * <><><--><--------------------------------------------------><----------------------------------------------><----><------><------>
817 * version code unspentness vout[4] vout[16] height timestamp block timestamp
820 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
821 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
822 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
823 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
824 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
825 * * 00: special txout type pay-to-pubkey-hash
826 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
827 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
828 * * bbd123: compact amount representation for 110397 (0.001 BTC)
829 * * 00: special txout type pay-to-pubkey-hash
830 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
832 * - time = 1389883712
834 * - block time = 1389883712
839 // whether transaction is a coinbase
842 // whether transaction is a coinstake
845 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
846 std::vector<CTxOut> vout;
848 // at which height this transaction was included in the active blockchain
851 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
852 // as new tx version will probably only be introduced at certain heights
855 // transaction timestamp + coinstake flag
859 unsigned int nBlockTime;
861 // construct a CCoins from a CTransaction, at a given height/timestamp
862 CCoins(const CTransaction &tx, int nHeightIn, int nBlockTimeIn) : fCoinBase(tx.IsCoinBase()), fCoinStake(tx.IsCoinStake()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion), nTime(tx.nTime), nBlockTime(nBlockTimeIn) { }
865 CCoins() : fCoinBase(false), fCoinStake(false), vout(0), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) { }
867 // remove spent outputs at the end of vout
869 while (vout.size() > 0 && vout.back().IsNull())
874 friend bool operator==(const CCoins &a, const CCoins &b) {
875 return a.fCoinBase == b.fCoinBase &&
876 a.fCoinStake == b.fCoinStake &&
877 a.nHeight == b.nHeight &&
878 a.nVersion == b.nVersion &&
879 a.nTime == b.nTime &&
880 a.nBlockTime == b.nBlockTime &&
883 friend bool operator!=(const CCoins &a, const CCoins &b) {
887 // calculate number of bytes for the bitmask, and its number of non-zero bytes
888 // each bit in the bitmask represents the availability of one output, but the
889 // availabilities of the first two outputs are encoded separately
890 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
891 unsigned int nLastUsedByte = 0;
892 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
894 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
895 if (!vout[2+b*8+i].IsNull()) {
901 nLastUsedByte = b + 1;
905 nBytes += nLastUsedByte;
908 bool IsCoinBase() const {
912 bool IsCoinStake() const {
916 unsigned int GetSerializeSize(int nType, int nVersion) const {
917 unsigned int nSize = 0;
918 unsigned int nMaskSize = 0, nMaskCode = 0;
919 CalcMaskSize(nMaskSize, nMaskCode);
920 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
921 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
922 assert(fFirst || fSecond || nMaskCode);
923 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fCoinStake ? 1 : 0) + (fSecond ? 4 : 0);
925 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
926 // size of header code
927 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
931 for (unsigned int i = 0; i < vout.size(); i++)
932 if (!vout[i].IsNull())
933 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
935 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
936 // timestamp and coinstake flag
937 nSize += ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
939 nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
943 template<typename Stream>
944 void Serialize(Stream &s, int nType, int nVersion) const {
945 unsigned int nMaskSize = 0, nMaskCode = 0;
946 CalcMaskSize(nMaskSize, nMaskCode);
947 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
948 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
949 assert(fFirst || fSecond || nMaskCode);
950 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
952 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
954 ::Serialize(s, VARINT(nCode), nType, nVersion);
956 for (unsigned int b = 0; b<nMaskSize; b++) {
957 unsigned char chAvail = 0;
958 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
959 if (!vout[2+b*8+i].IsNull())
961 ::Serialize(s, chAvail, nType, nVersion);
964 for (unsigned int i = 0; i < vout.size(); i++) {
965 if (!vout[i].IsNull())
966 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
969 ::Serialize(s, VARINT(nHeight), nType, nVersion);
970 // transaction timestamp and coinstake flag
971 ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
973 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
976 template<typename Stream>
977 void Unserialize(Stream &s, int nType, int nVersion) {
978 unsigned int nCode = 0, nCodeTime = 0;
980 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
982 ::Unserialize(s, VARINT(nCode), nType, nVersion);
983 fCoinBase = nCode & 1;
984 std::vector<bool> vAvail(2, false);
985 vAvail[0] = nCode & 2;
986 vAvail[1] = nCode & 4;
987 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
989 while (nMaskCode > 0) {
990 unsigned char chAvail = 0;
991 ::Unserialize(s, chAvail, nType, nVersion);
992 for (unsigned int p = 0; p < 8; p++) {
993 bool f = (chAvail & (1 << p)) != 0;
1000 vout.assign(vAvail.size(), CTxOut());
1001 for (unsigned int i = 0; i < vAvail.size(); i++) {
1003 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1006 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1007 // transaction timestamp
1008 ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
1009 nTime = nCodeTime / 2;
1010 fCoinStake = nCodeTime & 1;
1012 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1016 // mark an outpoint spent, and construct undo information
1017 bool Spend(const COutPoint &out, CTxInUndo &undo) {
1018 if (out.n >= vout.size())
1020 if (vout[out.n].IsNull())
1022 undo = CTxInUndo(vout[out.n]);
1023 vout[out.n].SetNull();
1025 if (vout.size() == 0) {
1026 undo.nHeight = nHeight;
1028 undo.nBlockTime = nBlockTime;
1029 undo.fCoinBase = fCoinBase;
1030 undo.fCoinStake = fCoinStake;
1031 undo.nVersion = this->nVersion;
1036 // mark a vout spent
1037 bool Spend(int nPos) {
1039 COutPoint out(0, nPos);
1040 return Spend(out, undo);
1043 // check whether a particular output is still available
1044 bool IsAvailable(unsigned int nPos) const {
1045 return (nPos < vout.size() && !vout[nPos].IsNull());
1048 // check whether the entire CCoins is spent
1049 // note that only !IsPruned() CCoins can be serialized
1050 bool IsPruned() const {
1051 BOOST_FOREACH(const CTxOut &out, vout)
1061 /** A transaction with a merkle branch linking it to the block chain. */
1062 class CMerkleTx : public CTransaction
1066 std::vector<uint256> vMerkleBranch;
1070 mutable bool fMerkleVerified;
1078 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1087 fMerkleVerified = false;
1093 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1094 nVersion = this->nVersion;
1095 READWRITE(hashBlock);
1096 READWRITE(vMerkleBranch);
1101 int SetMerkleBranch(const CBlock* pblock=NULL);
1102 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1103 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1104 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1105 int GetBlocksToMaturity() const;
1106 bool AcceptToMemoryPool(bool fCheckInputs=true);
1111 /** Nodes collect new transactions into a block, hash them into a hash tree,
1112 * and scan through nonce values to make the block's hash satisfy proof-of-work
1113 * requirements. When they solve the proof-of-work, they broadcast the block
1114 * to everyone and the block is added to the block chain. The first transaction
1115 * in the block is a special one that creates a new coin owned by the creator
1122 static const int CURRENT_VERSION=6;
1124 uint256 hashPrevBlock;
1125 uint256 hashMerkleRoot;
1128 unsigned int nNonce;
1131 std::vector<CTransaction> vtx;
1133 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
1134 std::vector<unsigned char> vchBlockSig;
1137 mutable std::vector<uint256> vMerkleTree;
1139 // Denial-of-service detection:
1141 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1150 READWRITE(this->nVersion);
1151 nVersion = this->nVersion;
1152 READWRITE(hashPrevBlock);
1153 READWRITE(hashMerkleRoot);
1158 // ConnectBlock depends on vtx following header to generate CDiskTxPos
1159 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1162 READWRITE(vchBlockSig);
1166 const_cast<CBlock*>(this)->vtx.clear();
1167 const_cast<CBlock*>(this)->vchBlockSig.clear();
1173 nVersion = CBlock::CURRENT_VERSION;
1180 vchBlockSig.clear();
1181 vMerkleTree.clear();
1187 return (nBits == 0);
1190 uint256 GetHash() const
1192 return scrypt_blockhash(CVOIDBEGIN(nVersion));
1195 int64 GetBlockTime() const
1197 return (int64)nTime;
1200 void UpdateTime(const CBlockIndex* pindexPrev);
1202 // ppcoin: entropy bit for stake modifier if chosen by modifier
1203 unsigned int GetStakeEntropyBit(unsigned int nTime) const
1205 // Protocol switch to support p2pool at novacoin block #9689
1206 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
1208 // Take last bit of block hash as entropy bit
1209 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
1210 if (fDebug && GetBoolArg("-printstakemodifier"))
1211 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1214 // Before novacoin block #9689 - old protocol
1215 uint160 hashSig = Hash160(vchBlockSig);
1216 if (fDebug && GetBoolArg("-printstakemodifier"))
1217 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
1218 hashSig >>= 159; // take the first bit of the hash
1219 if (fDebug && GetBoolArg("-printstakemodifier"))
1220 printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
1221 return hashSig.Get64();
1224 // ppcoin: two types of block: proof-of-work or proof-of-stake
1225 bool IsProofOfStake() const
1227 return (vtx.size() > 1 && vtx[1].IsCoinStake());
1230 bool IsProofOfWork() const
1232 return !IsProofOfStake();
1235 std::pair<COutPoint, unsigned int> GetProofOfStake() const
1237 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1240 // ppcoin: get max transaction timestamp
1241 int64 GetMaxTransactionTime() const
1243 int64 maxTransactionTime = 0;
1244 BOOST_FOREACH(const CTransaction& tx, vtx)
1245 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1246 return maxTransactionTime;
1249 uint256 BuildMerkleTree() const
1251 vMerkleTree.clear();
1252 BOOST_FOREACH(const CTransaction& tx, vtx)
1253 vMerkleTree.push_back(tx.GetHash());
1255 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1257 for (int i = 0; i < nSize; i += 2)
1259 int i2 = std::min(i+1, nSize-1);
1260 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1261 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1265 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1268 const uint256 &GetTxHash(unsigned int nIndex) const {
1269 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1270 assert(nIndex < vtx.size());
1271 return vMerkleTree[nIndex];
1274 std::vector<uint256> GetMerkleBranch(int nIndex) const
1276 if (vMerkleTree.empty())
1278 std::vector<uint256> vMerkleBranch;
1280 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1282 int i = std::min(nIndex^1, nSize-1);
1283 vMerkleBranch.push_back(vMerkleTree[j+i]);
1287 return vMerkleBranch;
1290 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1294 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1297 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1299 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1305 bool WriteToDisk(CDiskBlockPos &pos)
1307 // Open history file to append
1308 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1310 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1312 // Write index header
1313 unsigned int nSize = fileout.GetSerializeSize(*this);
1314 fileout << FLATDATA(pchMessageStart) << nSize;
1317 long fileOutPos = ftell(fileout);
1319 return error("CBlock::WriteToDisk() : ftell failed");
1320 pos.nPos = (unsigned int)fileOutPos;
1323 // Flush stdio buffers and commit to disk before returning
1325 if (!IsInitialBlockDownload())
1326 FileCommit(fileout);
1331 bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1335 // Open history file to read
1336 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1338 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1339 if (!fReadTransactions)
1340 filein.nType |= SER_BLOCKHEADERONLY;
1346 catch (std::exception &e) {
1347 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1351 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1352 return error("CBlock::ReadFromDisk() : errors in block header");
1359 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1360 GetHash().ToString().c_str(),
1362 hashPrevBlock.ToString().c_str(),
1363 hashMerkleRoot.ToString().c_str(),
1364 nTime, nBits, nNonce,
1366 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1367 for (unsigned int i = 0; i < vtx.size(); i++)
1372 printf(" vMerkleTree: ");
1373 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1374 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1378 // Undo the effects of this block (with given index) on the UTXO set represented by coins
1379 bool DisconnectBlock(CBlockIndex *pindex, CCoinsView &coins);
1381 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1382 bool ConnectBlock(CBlockIndex *pindex, CCoinsView &coins, bool fJustCheck=false);
1384 // Read a block from disk
1385 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1387 // Make this block (with given index) the new tip of the active block chain
1388 bool SetBestChain(CBlockIndex* pindexNew);
1390 // Add this block to the block index, and if necessary, switch the active block chain to this
1391 bool AddToBlockIndex(const CDiskBlockPos &pos);
1393 // Context-independent validity checks
1394 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=false) const;
1396 // Store block on disk
1399 // Get total coinage consumed
1400 bool GetCoinAge(uint64& nCoinAge) const;
1402 // Generate proof-of-stake block signature
1403 bool SignBlock(CWallet& keystore);
1405 // Get generator key
1406 bool GetGenerator(CKey& GeneratorKey) const;
1408 // Validate proof-of-stake block signature
1409 bool CheckSignature(bool& fFatal, uint256& hashProofOfStake) const;
1411 // Legacy proof-of-work signature
1412 bool CheckLegacySignature() const;
1416 class CBlockFileInfo
1419 unsigned int nBlocks; // number of blocks stored in file
1420 unsigned int nSize; // number of used bytes of block file
1421 unsigned int nUndoSize; // number of used bytes in the undo file
1422 unsigned int nHeightFirst; // lowest height of block in file
1423 unsigned int nHeightLast; // highest height of block in file
1424 uint64 nTimeFirst; // earliest time of block in file
1425 uint64 nTimeLast; // latest time of block in file
1427 IMPLEMENT_SERIALIZE(
1428 READWRITE(VARINT(nBlocks));
1429 READWRITE(VARINT(nSize));
1430 READWRITE(VARINT(nUndoSize));
1431 READWRITE(VARINT(nHeightFirst));
1432 READWRITE(VARINT(nHeightLast));
1433 READWRITE(VARINT(nTimeFirst));
1434 READWRITE(VARINT(nTimeLast));
1451 std::string ToString() const {
1452 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u..%u, time=%s..%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
1455 // update statistics (does not update nSize)
1456 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1457 if (nBlocks==0 || nHeightFirst > nHeightIn)
1458 nHeightFirst = nHeightIn;
1459 if (nBlocks==0 || nTimeFirst > nTimeIn)
1460 nTimeFirst = nTimeIn;
1462 if (nHeightIn > nHeightFirst)
1463 nHeightLast = nHeightIn;
1464 if (nTimeIn > nTimeLast)
1465 nTimeLast = nTimeIn;
1470 extern CCriticalSection cs_LastBlockFile;
1471 extern CBlockFileInfo infoLastBlockFile;
1472 extern int nLastBlockFile;
1474 /** The block chain is a tree shaped structure starting with the
1475 * genesis block at the root, with each block potentially having multiple
1476 * candidates to be the next block. pprev and pnext link a path through the
1477 * main/longest chain. A blockindex may have multiple pprev pointing back
1478 * to it, but pnext will only point forward to the longest branch, or will
1479 * be null if the block is not part of the longest chain.
1484 const uint256* phashBlock;
1489 unsigned int nUndoPos;
1490 uint256 nChainTrust; // trust score of block chain
1495 unsigned int nFlags;
1498 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1499 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1500 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1503 uint64 nStakeModifier; // hash modifier for proof-of-stake
1504 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1506 // proof-of-stake specific fields
1507 COutPoint prevoutStake;
1508 unsigned int nStakeTime;
1509 uint256 hashProofOfStake;
1513 uint256 hashMerkleRoot;
1516 unsigned int nNonce;
1532 nStakeModifierChecksum = 0;
1533 hashProofOfStake = 0;
1534 prevoutStake.SetNull();
1544 CBlockIndex(CBlock& block)
1557 nStakeModifierChecksum = 0;
1558 hashProofOfStake = 0;
1559 if (block.IsProofOfStake())
1562 prevoutStake = block.vtx[1].vin[0].prevout;
1563 nStakeTime = block.vtx[1].nTime;
1567 prevoutStake.SetNull();
1571 nVersion = block.nVersion;
1572 hashMerkleRoot = block.hashMerkleRoot;
1573 nTime = block.nTime;
1574 nBits = block.nBits;
1575 nNonce = block.nNonce;
1578 CDiskBlockPos GetBlockPos() const {
1582 CDiskBlockPos GetUndoPos() const {
1583 CDiskBlockPos ret = pos;
1587 ret.nPos = nUndoPos - 1;
1591 CBlock GetBlockHeader() const
1594 block.nVersion = nVersion;
1596 block.hashPrevBlock = pprev->GetBlockHash();
1597 block.hashMerkleRoot = hashMerkleRoot;
1598 block.nTime = nTime;
1599 block.nBits = nBits;
1600 block.nNonce = nNonce;
1604 uint256 GetBlockHash() const
1609 int64 GetBlockTime() const
1611 return (int64)nTime;
1614 uint256 GetBlockTrust() const;
1616 bool IsInMainChain() const
1618 return (pnext || this == pindexBest);
1621 bool CheckIndex() const
1626 enum { nMedianTimeSpan=11 };
1628 int64 GetMedianTimePast() const
1630 int64 pmedian[nMedianTimeSpan];
1631 int64* pbegin = &pmedian[nMedianTimeSpan];
1632 int64* pend = &pmedian[nMedianTimeSpan];
1634 const CBlockIndex* pindex = this;
1635 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1636 *(--pbegin) = pindex->GetBlockTime();
1638 std::sort(pbegin, pend);
1639 return pbegin[(pend - pbegin)/2];
1642 int64 GetMedianTime() const
1644 const CBlockIndex* pindex = this;
1645 for (int i = 0; i < nMedianTimeSpan/2; i++)
1648 return GetBlockTime();
1649 pindex = pindex->pnext;
1651 return pindex->GetMedianTimePast();
1655 * Returns true if there are nRequired or more blocks of minVersion or above
1656 * in the last nToCheck blocks, starting at pstart and going backwards.
1658 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1659 unsigned int nRequired, unsigned int nToCheck);
1661 bool IsProofOfWork() const
1663 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1666 bool IsProofOfStake() const
1668 return (nFlags & BLOCK_PROOF_OF_STAKE);
1671 void SetProofOfStake()
1673 nFlags |= BLOCK_PROOF_OF_STAKE;
1676 unsigned int GetStakeEntropyBit() const
1678 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1681 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1683 if (nEntropyBit > 1)
1685 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1689 bool GeneratedStakeModifier() const
1691 return (nFlags & BLOCK_STAKE_MODIFIER);
1694 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1696 nStakeModifier = nModifier;
1697 if (fGeneratedStakeModifier)
1698 nFlags |= BLOCK_STAKE_MODIFIER;
1701 std::string ToString() const
1703 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)",
1704 pprev, pnext, nHeight,
1705 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1706 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1707 nStakeModifier, nStakeModifierChecksum,
1708 hashProofOfStake.ToString().c_str(),
1709 prevoutStake.ToString().c_str(), nStakeTime,
1710 hashMerkleRoot.ToString().c_str(),
1711 GetBlockHash().ToString().c_str());
1717 printf("%s\n", ToString().c_str());
1721 /** Used to marshal pointers into hashes for db storage. */
1722 class CDiskBlockIndex : public CBlockIndex
1734 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1735 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1740 if (!(nType & SER_GETHASH))
1741 READWRITE(nVersion);
1745 READWRITE(nUndoPos);
1747 READWRITE(nMoneySupply);
1749 READWRITE(nStakeModifier);
1750 if (IsProofOfStake())
1752 READWRITE(prevoutStake);
1753 READWRITE(nStakeTime);
1754 READWRITE(hashProofOfStake);
1758 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1759 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1760 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1762 READWRITE(blockHash);
1765 READWRITE(this->nVersion);
1766 READWRITE(hashPrev);
1767 READWRITE(hashMerkleRoot);
1773 uint256 GetBlockHash() const
1775 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1779 block.nVersion = nVersion;
1780 block.hashPrevBlock = hashPrev;
1781 block.hashMerkleRoot = hashMerkleRoot;
1782 block.nTime = nTime;
1783 block.nBits = nBits;
1784 block.nNonce = nNonce;
1786 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1792 std::string ToString() const
1794 std::string str = "CDiskBlockIndex(";
1795 str += CBlockIndex::ToString();
1796 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1797 GetBlockHash().ToString().c_str(),
1798 hashPrev.ToString().substr(0,20).c_str());
1804 printf("%s\n", ToString().c_str());
1809 /** Describes a place in the block chain to another node such that if the
1810 * other node doesn't have the same branch, it can find a recent common trunk.
1811 * The further back it is, the further before the fork it may be.
1816 std::vector<uint256> vHave;
1823 explicit CBlockLocator(const CBlockIndex* pindex)
1828 explicit CBlockLocator(uint256 hashBlock)
1830 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1831 if (mi != mapBlockIndex.end())
1835 CBlockLocator(const std::vector<uint256>& vHaveIn)
1842 if (!(nType & SER_GETHASH))
1843 READWRITE(nVersion);
1854 return vHave.empty();
1857 void Set(const CBlockIndex* pindex)
1863 vHave.push_back(pindex->GetBlockHash());
1865 // Exponentially larger steps back
1866 for (int i = 0; pindex && i < nStep; i++)
1867 pindex = pindex->pprev;
1868 if (vHave.size() > 10)
1871 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1874 int GetDistanceBack()
1876 // Retrace how far back it was in the sender's branch
1879 BOOST_FOREACH(const uint256& hash, vHave)
1881 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1882 if (mi != mapBlockIndex.end())
1884 CBlockIndex* pindex = (*mi).second;
1885 if (pindex->IsInMainChain())
1895 CBlockIndex* GetBlockIndex()
1897 // Find the first block the caller has in the main chain
1898 BOOST_FOREACH(const uint256& hash, vHave)
1900 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1901 if (mi != mapBlockIndex.end())
1903 CBlockIndex* pindex = (*mi).second;
1904 if (pindex->IsInMainChain())
1908 return pindexGenesisBlock;
1911 uint256 GetBlockHash()
1913 // Find the first block the caller has in the main chain
1914 BOOST_FOREACH(const uint256& hash, vHave)
1916 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1917 if (mi != mapBlockIndex.end())
1919 CBlockIndex* pindex = (*mi).second;
1920 if (pindex->IsInMainChain())
1924 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1929 CBlockIndex* pindex = GetBlockIndex();
1932 return pindex->nHeight;
1943 mutable CCriticalSection cs;
1944 std::map<uint256, CTransaction> mapTx;
1945 std::map<COutPoint, CInPoint> mapNextTx;
1947 bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1948 bool addUnchecked(const uint256& hash, CTransaction &tx);
1949 bool remove(CTransaction &tx);
1951 void queryHashes(std::vector<uint256>& vtxid);
1952 void pruneSpent(const uint256& hash, CCoins &coins);
1954 unsigned long size()
1957 return mapTx.size();
1960 bool exists(uint256 hash)
1962 return (mapTx.count(hash) != 0);
1965 CTransaction& lookup(uint256 hash)
1971 extern CTxMemPool mempool;
1973 /** Abstract view on the open txout dataset. */
1977 // Retrieve the CCoins (unspent transaction outputs) for a given txid
1978 virtual bool GetCoins(uint256 txid, CCoins &coins);
1980 // Modify the CCoins for a given txid
1981 virtual bool SetCoins(uint256 txid, const CCoins &coins);
1983 // Just check whether we have data for a given txid.
1984 // This may (but cannot always) return true for fully spent transactions
1985 virtual bool HaveCoins(uint256 txid);
1987 // Retrieve the block index whose state this CCoinsView currently represents
1988 virtual CBlockIndex *GetBestBlock();
1990 // Modify the currently active block index
1991 virtual bool SetBestBlock(CBlockIndex *pindex);
1992 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1995 /** CCoinsView backed by another CCoinsView */
1996 class CCoinsViewBacked : public CCoinsView
2002 CCoinsViewBacked(CCoinsView &viewIn);
2003 bool GetCoins(uint256 txid, CCoins &coins);
2004 bool SetCoins(uint256 txid, const CCoins &coins);
2005 bool HaveCoins(uint256 txid);
2006 CBlockIndex *GetBestBlock();
2007 bool SetBestBlock(CBlockIndex *pindex);
2008 void SetBackend(CCoinsView &viewIn);
2009 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2012 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2013 class CCoinsViewCache : public CCoinsViewBacked
2016 CBlockIndex *pindexTip;
2017 std::map<uint256,CCoins> cacheCoins;
2018 std::map<uint256,CCoins> cacheCoinsReadOnly;
2021 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2022 bool GetCoins(uint256 txid, CCoins &coins);
2023 bool GetCoinsReadOnly(uint256 txid, CCoins &coins);
2024 bool SetCoins(uint256 txid, const CCoins &coins);
2025 bool HaveCoins(uint256 txid);
2026 CBlockIndex *GetBestBlock();
2027 bool SetBestBlock(CBlockIndex *pindex);
2028 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2030 unsigned int GetCacheSize();
2033 /** CCoinsView that brings transactions from a memorypool into view.
2034 It does not check for spendings by memory pool transactions. */
2035 class CCoinsViewMemPool : public CCoinsViewBacked
2038 CTxMemPool &mempool;
2041 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2042 bool GetCoins(uint256 txid, CCoins &coins);
2043 bool HaveCoins(uint256 txid);
2046 extern CCoinsViewCache *pcoinsTip;