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.
25 struct CBlockIndexWorkComparator;
27 /** The maximum allowed size for a serialized block, in bytes (network rule) */
28 static const unsigned int MAX_BLOCK_SIZE = 1000000;
29 /** The maximum size for mined blocks */
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 /** The maximum allowed number of signature check operations in a block (network rule) */
32 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 /** The maximum number of orphan transactions kept in memory */
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 /** The maximum number of entries in an 'inv' protocol message */
36 static const unsigned int MAX_INV_SZ = 50000;
37 /** The maximum size of a blk?????.dat file (since 0.8) */
38 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
39 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
40 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
41 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
42 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
43 /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
44 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
45 /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
46 static const int64 MIN_TX_FEE = 50000;
47 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
48 static const int64 MIN_RELAY_TX_FEE = 10000;
49 /** No amount larger than this (in satoshi) is valid */
50 static const int64 MAX_MONEY = 21000000 * COIN;
51 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
52 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
53 static const int COINBASE_MATURITY = 100;
54 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
55 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
57 static const int fHaveUPnP = true;
59 static const int fHaveUPnP = false;
63 extern CScript COINBASE_FLAGS;
70 extern CCriticalSection cs_main;
71 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
72 extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
73 extern uint256 hashGenesisBlock;
74 extern CBlockIndex* pindexGenesisBlock;
75 extern int nBestHeight;
76 extern CBigNum bnBestChainWork;
77 extern CBigNum bnBestInvalidWork;
78 extern uint256 hashBestChain;
79 extern CBlockIndex* pindexBest;
80 extern unsigned int nTransactionsUpdated;
81 extern uint64 nLastBlockTx;
82 extern uint64 nLastBlockSize;
83 extern const std::string strMessageMagic;
84 extern double dHashesPerSec;
85 extern int64 nHPSTimerStart;
86 extern int64 nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern std::set<CWallet*> setpwalletRegistered;
89 extern unsigned char pchMessageStart[4];
90 extern bool fImporting;
92 extern bool fBenchmark;
93 extern unsigned int nCoinCacheSize;
96 extern int64 nTransactionFee;
98 // Minimum disk space required - used in CheckDiskSpace()
99 static const uint64 nMinDiskSpace = 52428800;
109 class CCoinsViewCache;
111 /** Register a wallet to receive updates from core */
112 void RegisterWallet(CWallet* pwalletIn);
113 /** Unregister a wallet from core */
114 void UnregisterWallet(CWallet* pwalletIn);
115 /** Push an updated transaction to all registered wallets */
116 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
117 /** Process an incoming block */
118 bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
119 /** Check whether enough disk space is available for an incoming block */
120 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
121 /** Open a block file (blk?????.dat) */
122 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
123 /** Open an undo file (rev?????.dat) */
124 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
125 /** Import blocks from an external file */
126 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
127 /** Load the block tree and coins database from disk */
128 bool LoadBlockIndex();
129 /** Print the loaded block tree */
130 void PrintBlockTree();
131 /** Find a block by height in the currently-connected chain */
132 CBlockIndex* FindBlockByHeight(int nHeight);
133 /** Process protocol messages received from a given node */
134 bool ProcessMessages(CNode* pfrom);
135 /** Send queued protocol messages to be sent to a give node */
136 bool SendMessages(CNode* pto, bool fSendTrickle);
137 /** Run the importer thread, which deals with reindexing, loading bootstrap.dat, and whatever is passed to -loadblock */
138 void ThreadImport(void *parg);
139 /** Run the miner threads */
140 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
141 /** Generate a new block, without valid proof-of-work */
142 CBlock* CreateNewBlock(CReserveKey& reservekey);
143 /** Modify the extranonce in a block */
144 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
145 /** Do mining precalculation */
146 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
147 /** Check mined block */
148 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
149 /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
150 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
151 /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
152 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
153 /** Get the number of active peers */
154 int GetNumBlocksOfPeers();
155 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
156 bool IsInitialBlockDownload();
157 /** Format a string that describes several potential problems detected by the core */
158 std::string GetWarnings(std::string strFor);
159 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
160 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
161 /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
162 bool SetBestChain(CBlockIndex* pindexNew);
163 /** Find the best known block, and make it the tip of the block chain */
164 bool ConnectBestBlock();
165 /** Create a new block index entry for a given block hash */
166 CBlockIndex * InsertBlockIndex(uint256 hash);
167 /** Verify a signature */
168 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
180 static inline std::string BlockHashStr(const uint256& hash)
182 return hash.ToString();
185 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
194 READWRITE(VARINT(nFile));
195 READWRITE(VARINT(nPos));
202 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
207 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
208 return (a.nFile == b.nFile && a.nPos == b.nPos);
211 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
215 void SetNull() { nFile = -1; nPos = 0; }
216 bool IsNull() const { return (nFile == -1); }
222 /** An inpoint - a combination of a transaction and an index n into its vin */
229 CInPoint() { SetNull(); }
230 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
231 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
232 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
237 /** An outpoint - a combination of a transaction hash and an index n into its vout */
244 COutPoint() { SetNull(); }
245 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
246 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
247 void SetNull() { hash = 0; n = (unsigned int) -1; }
248 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
250 friend bool operator<(const COutPoint& a, const COutPoint& b)
252 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
255 friend bool operator==(const COutPoint& a, const COutPoint& b)
257 return (a.hash == b.hash && a.n == b.n);
260 friend bool operator!=(const COutPoint& a, const COutPoint& b)
265 std::string ToString() const
267 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
272 printf("%s\n", ToString().c_str());
279 /** An input of a transaction. It contains the location of the previous
280 * transaction's output that it claims and a signature that matches the
281 * output's public key.
288 unsigned int nSequence;
292 nSequence = std::numeric_limits<unsigned int>::max();
295 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
298 scriptSig = scriptSigIn;
299 nSequence = nSequenceIn;
302 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
304 prevout = COutPoint(hashPrevTx, nOut);
305 scriptSig = scriptSigIn;
306 nSequence = nSequenceIn;
312 READWRITE(scriptSig);
313 READWRITE(nSequence);
318 return (nSequence == std::numeric_limits<unsigned int>::max());
321 friend bool operator==(const CTxIn& a, const CTxIn& b)
323 return (a.prevout == b.prevout &&
324 a.scriptSig == b.scriptSig &&
325 a.nSequence == b.nSequence);
328 friend bool operator!=(const CTxIn& a, const CTxIn& b)
333 std::string ToString() const
337 str += prevout.ToString();
338 if (prevout.IsNull())
339 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
341 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
342 if (nSequence != std::numeric_limits<unsigned int>::max())
343 str += strprintf(", nSequence=%u", nSequence);
350 printf("%s\n", ToString().c_str());
357 /** An output of a transaction. It contains the public key that the next input
358 * must be able to sign with to claim it.
364 CScript scriptPubKey;
371 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
374 scriptPubKey = scriptPubKeyIn;
380 READWRITE(scriptPubKey);
386 scriptPubKey.clear();
391 return (nValue == -1);
394 uint256 GetHash() const
396 return SerializeHash(*this);
399 friend bool operator==(const CTxOut& a, const CTxOut& b)
401 return (a.nValue == b.nValue &&
402 a.scriptPubKey == b.scriptPubKey);
405 friend bool operator!=(const CTxOut& a, const CTxOut& b)
410 std::string ToString() const
412 if (scriptPubKey.size() < 6)
413 return "CTxOut(error)";
414 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
419 printf("%s\n", ToString().c_str());
433 /** The basic transaction that is broadcasted on the network and contained in
434 * blocks. A transaction can contain multiple inputs and outputs.
439 static const int CURRENT_VERSION=1;
441 std::vector<CTxIn> vin;
442 std::vector<CTxOut> vout;
443 unsigned int nLockTime;
445 // Denial-of-service detection:
447 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
456 READWRITE(this->nVersion);
457 nVersion = this->nVersion;
460 READWRITE(nLockTime);
465 nVersion = CTransaction::CURRENT_VERSION;
469 nDoS = 0; // Denial-of-service prevention
474 return (vin.empty() && vout.empty());
477 uint256 GetHash() const
479 return SerializeHash(*this);
482 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
484 // Time based nLockTime implemented in 0.1.6
487 if (nBlockHeight == 0)
488 nBlockHeight = nBestHeight;
490 nBlockTime = GetAdjustedTime();
491 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
493 BOOST_FOREACH(const CTxIn& txin, vin)
499 bool IsNewerThan(const CTransaction& old) const
501 if (vin.size() != old.vin.size())
503 for (unsigned int i = 0; i < vin.size(); i++)
504 if (vin[i].prevout != old.vin[i].prevout)
508 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
509 for (unsigned int i = 0; i < vin.size(); i++)
511 if (vin[i].nSequence != old.vin[i].nSequence)
513 if (vin[i].nSequence <= nLowest)
516 nLowest = vin[i].nSequence;
518 if (old.vin[i].nSequence < nLowest)
521 nLowest = old.vin[i].nSequence;
528 bool IsCoinBase() const
530 return (vin.size() == 1 && vin[0].prevout.IsNull());
533 /** Check for standard transaction types
534 @return True if all outputs (scriptPubKeys) use only standard transaction forms
536 bool IsStandard() const;
538 /** Check for standard transaction types
539 @param[in] mapInputs Map of previous transactions that have outputs we're spending
540 @return True if all inputs (scriptSigs) use only standard transaction forms
541 @see CTransaction::FetchInputs
543 bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
545 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
546 @return number of sigops this transaction's outputs will produce when spent
547 @see CTransaction::FetchInputs
549 unsigned int GetLegacySigOpCount() const;
551 /** Count ECDSA signature operations in pay-to-script-hash inputs.
553 @param[in] mapInputs Map of previous transactions that have outputs we're spending
554 @return maximum number of sigops required to validate this transaction's inputs
555 @see CTransaction::FetchInputs
557 unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
559 /** Amount of bitcoins spent by this transaction.
560 @return sum of all outputs (note: does not include fees)
562 int64 GetValueOut() const
565 BOOST_FOREACH(const CTxOut& txout, vout)
567 nValueOut += txout.nValue;
568 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
569 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
574 /** Amount of bitcoins coming in to this transaction
575 Note that lightweight clients may not know anything besides the hash of previous transactions,
576 so may not be able to calculate this.
578 @param[in] mapInputs Map of previous transactions that have outputs we're spending
579 @return Sum of value of all inputs (scriptSigs)
580 @see CTransaction::FetchInputs
582 int64 GetValueIn(CCoinsViewCache& mapInputs) const;
584 static bool AllowFree(double dPriority)
586 // Large (in bytes) low-priority (new, small-coin) transactions
588 return dPriority > COIN * 144 / 250;
591 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
593 friend bool operator==(const CTransaction& a, const CTransaction& b)
595 return (a.nVersion == b.nVersion &&
598 a.nLockTime == b.nLockTime);
601 friend bool operator!=(const CTransaction& a, const CTransaction& b)
607 std::string ToString() const
610 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
611 GetHash().ToString().substr(0,10).c_str(),
616 for (unsigned int i = 0; i < vin.size(); i++)
617 str += " " + vin[i].ToString() + "\n";
618 for (unsigned int i = 0; i < vout.size(); i++)
619 str += " " + vout[i].ToString() + "\n";
625 printf("%s", ToString().c_str());
629 // Do all possible client-mode checks
630 bool ClientCheckInputs() const;
632 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
633 bool HaveInputs(CCoinsViewCache &view) const;
635 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
636 // This does not modify the UTXO set
637 bool CheckInputs(CCoinsViewCache &view, bool fScriptChecks = true, unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC) const;
639 // Apply the effects of this transaction on the UTXO set represented by view
640 bool UpdateCoins(CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
642 // Context-independent validity checks
643 bool CheckTransaction() const;
645 // Try to accept this transaction into the memory pool
646 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
649 static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
652 /** wrapper for CTxOut that provides a more compact serialization */
653 class CTxOutCompressor
659 static uint64 CompressAmount(uint64 nAmount);
660 static uint64 DecompressAmount(uint64 nAmount);
662 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
664 IMPLEMENT_SERIALIZE(({
666 uint64 nVal = CompressAmount(txout.nValue);
667 READWRITE(VARINT(nVal));
670 READWRITE(VARINT(nVal));
671 txout.nValue = DecompressAmount(nVal);
673 CScriptCompressor cscript(REF(txout.scriptPubKey));
678 /** Undo information for a CTxIn
680 * Contains the prevout's CTxOut being spent, and if this was the
681 * last output of the affected transaction, its metadata as well
682 * (coinbase or not, height, transaction version)
687 CTxOut txout; // the txout data before being spent
688 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
689 unsigned int nHeight; // if the outpoint was the last unspent: its height
690 int nVersion; // if the outpoint was the last unspent: its version
692 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
693 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
695 unsigned int GetSerializeSize(int nType, int nVersion) const {
696 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), 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);
705 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
706 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
709 template<typename Stream>
710 void Unserialize(Stream &s, int nType, int nVersion) {
711 unsigned int nCode = 0;
712 ::Unserialize(s, VARINT(nCode), nType, nVersion);
714 fCoinBase = nCode & 1;
716 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
717 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
721 /** Undo information for a CTransaction */
725 // undo information for all txins
726 std::vector<CTxInUndo> vprevout;
733 /** Undo information for a CBlock */
737 std::vector<CTxUndo> vtxundo; // for all but the coinbase
743 bool WriteToDisk(CDiskBlockPos &pos)
745 // Open history file to append
746 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
748 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
750 // Write index header
751 unsigned int nSize = fileout.GetSerializeSize(*this);
752 fileout << FLATDATA(pchMessageStart) << nSize;
755 long fileOutPos = ftell(fileout);
757 return error("CBlockUndo::WriteToDisk() : ftell failed");
758 pos.nPos = (unsigned int)fileOutPos;
761 // Flush stdio buffers and commit to disk before returning
763 if (!IsInitialBlockDownload())
770 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
775 * - unspentness bitvector, for vout[2] and further; least significant byte first
776 * - the non-spent CTxOuts (via CTxOutCompressor)
779 * The nCode value consists of:
780 * - bit 1: IsCoinBase()
781 * - bit 2: vout[0] is not spent
782 * - bit 4: vout[1] is not spent
783 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
784 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
785 * least one non-spent output).
787 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
788 * <><><--------------------------------------------><---->
790 * version code vout[1] height
793 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
794 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
795 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
796 * * 8358: compact amount representation for 60000000000 (600 BTC)
797 * * 00: special txout type pay-to-pubkey-hash
798 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
802 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
803 * <><><--><--------------------------------------------------><----------------------------------------------><---->
805 * version code unspentness vout[4] vout[16] height
808 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
809 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
810 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
811 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
812 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
813 * * 00: special txout type pay-to-pubkey-hash
814 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
815 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
816 * * bbd123: compact amount representation for 110397 (0.001 BTC)
817 * * 00: special txout type pay-to-pubkey-hash
818 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
824 // whether transaction is a coinbase
827 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
828 std::vector<CTxOut> vout;
830 // at which height this transaction was included in the active block chain
833 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
834 // as new tx version will probably only be introduced at certain heights
837 // construct a CCoins from a CTransaction, at a given height
838 CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
841 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
843 // remove spent outputs at the end of vout
845 while (vout.size() > 0 && vout.back().IsNull())
850 friend bool operator==(const CCoins &a, const CCoins &b) {
851 return a.fCoinBase == b.fCoinBase &&
852 a.nHeight == b.nHeight &&
853 a.nVersion == b.nVersion &&
856 friend bool operator!=(const CCoins &a, const CCoins &b) {
860 // calculate number of bytes for the bitmask, and its number of non-zero bytes
861 // each bit in the bitmask represents the availability of one output, but the
862 // availabilities of the first two outputs are encoded separately
863 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
864 unsigned int nLastUsedByte = 0;
865 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
867 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
868 if (!vout[2+b*8+i].IsNull()) {
874 nLastUsedByte = b + 1;
878 nBytes += nLastUsedByte;
881 bool IsCoinBase() const {
885 unsigned int GetSerializeSize(int nType, int nVersion) const {
886 unsigned int nSize = 0;
887 unsigned int nMaskSize = 0, nMaskCode = 0;
888 CalcMaskSize(nMaskSize, nMaskCode);
889 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
890 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
891 assert(fFirst || fSecond || nMaskCode);
892 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
894 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
895 // size of header code
896 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
900 for (unsigned int i = 0; i < vout.size(); i++)
901 if (!vout[i].IsNull())
902 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
904 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
908 template<typename Stream>
909 void Serialize(Stream &s, int nType, int nVersion) const {
910 unsigned int nMaskSize = 0, nMaskCode = 0;
911 CalcMaskSize(nMaskSize, nMaskCode);
912 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
913 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
914 assert(fFirst || fSecond || nMaskCode);
915 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
917 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
919 ::Serialize(s, VARINT(nCode), nType, nVersion);
921 for (unsigned int b = 0; b<nMaskSize; b++) {
922 unsigned char chAvail = 0;
923 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
924 if (!vout[2+b*8+i].IsNull())
926 ::Serialize(s, chAvail, nType, nVersion);
929 for (unsigned int i = 0; i < vout.size(); i++) {
930 if (!vout[i].IsNull())
931 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
934 ::Serialize(s, VARINT(nHeight), nType, nVersion);
937 template<typename Stream>
938 void Unserialize(Stream &s, int nType, int nVersion) {
939 unsigned int nCode = 0;
941 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
943 ::Unserialize(s, VARINT(nCode), nType, nVersion);
944 fCoinBase = nCode & 1;
945 std::vector<bool> vAvail(2, false);
946 vAvail[0] = nCode & 2;
947 vAvail[1] = nCode & 4;
948 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
950 while (nMaskCode > 0) {
951 unsigned char chAvail = 0;
952 ::Unserialize(s, chAvail, nType, nVersion);
953 for (unsigned int p = 0; p < 8; p++) {
954 bool f = (chAvail & (1 << p)) != 0;
961 vout.assign(vAvail.size(), CTxOut());
962 for (unsigned int i = 0; i < vAvail.size(); i++) {
964 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
967 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
971 // mark an outpoint spent, and construct undo information
972 bool Spend(const COutPoint &out, CTxInUndo &undo) {
973 if (out.n >= vout.size())
975 if (vout[out.n].IsNull())
977 undo = CTxInUndo(vout[out.n]);
978 vout[out.n].SetNull();
980 if (vout.size() == 0) {
981 undo.nHeight = nHeight;
982 undo.fCoinBase = fCoinBase;
983 undo.nVersion = this->nVersion;
989 bool Spend(int nPos) {
991 COutPoint out(0, nPos);
992 return Spend(out, undo);
995 // check whether a particular output is still available
996 bool IsAvailable(unsigned int nPos) const {
997 return (nPos < vout.size() && !vout[nPos].IsNull());
1000 // check whether the entire CCoins is spent
1001 // note that only !IsPruned() CCoins can be serialized
1002 bool IsPruned() const {
1003 BOOST_FOREACH(const CTxOut &out, vout)
1010 /** Closure representing one script verification
1011 * Note that this stores references to the spending transaction */
1015 CScript scriptPubKey;
1016 const CTransaction *ptxTo;
1018 unsigned int nFlags;
1023 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
1024 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
1025 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
1027 bool operator()() const;
1029 void swap(CScriptCheck &check) {
1030 scriptPubKey.swap(check.scriptPubKey);
1031 std::swap(ptxTo, check.ptxTo);
1032 std::swap(nIn, check.nIn);
1033 std::swap(nFlags, check.nFlags);
1034 std::swap(nHashType, check.nHashType);
1038 /** A transaction with a merkle branch linking it to the block chain. */
1039 class CMerkleTx : public CTransaction
1043 std::vector<uint256> vMerkleBranch;
1047 mutable bool fMerkleVerified;
1055 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1064 fMerkleVerified = false;
1070 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1071 nVersion = this->nVersion;
1072 READWRITE(hashBlock);
1073 READWRITE(vMerkleBranch);
1078 int SetMerkleBranch(const CBlock* pblock=NULL);
1079 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1080 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1081 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1082 int GetBlocksToMaturity() const;
1083 bool AcceptToMemoryPool(bool fCheckInputs=true);
1097 /** Nodes collect new transactions into a block, hash them into a hash tree,
1098 * and scan through nonce values to make the block's hash satisfy proof-of-work
1099 * requirements. When they solve the proof-of-work, they broadcast the block
1100 * to everyone and the block is added to the block chain. The first transaction
1101 * in the block is a special one that creates a new coin owned by the creator
1108 static const int CURRENT_VERSION=2;
1110 uint256 hashPrevBlock;
1111 uint256 hashMerkleRoot;
1114 unsigned int nNonce;
1123 READWRITE(this->nVersion);
1124 nVersion = this->nVersion;
1125 READWRITE(hashPrevBlock);
1126 READWRITE(hashMerkleRoot);
1134 nVersion = CBlockHeader::CURRENT_VERSION;
1144 return (nBits == 0);
1147 uint256 GetHash() const
1149 return Hash(BEGIN(nVersion), END(nNonce));
1152 int64 GetBlockTime() const
1154 return (int64)nTime;
1157 void UpdateTime(const CBlockIndex* pindexPrev);
1160 class CBlock : public CBlockHeader
1164 std::vector<CTransaction> vtx;
1167 mutable std::vector<uint256> vMerkleTree;
1169 // Denial-of-service detection:
1171 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1178 CBlock(const CBlockHeader &header)
1181 *((CBlockHeader*)this) = header;
1186 READWRITE(*(CBlockHeader*)this);
1192 CBlockHeader::SetNull();
1194 vMerkleTree.clear();
1198 uint256 BuildMerkleTree() const
1200 vMerkleTree.clear();
1201 BOOST_FOREACH(const CTransaction& tx, vtx)
1202 vMerkleTree.push_back(tx.GetHash());
1204 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1206 for (int i = 0; i < nSize; i += 2)
1208 int i2 = std::min(i+1, nSize-1);
1209 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1210 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1214 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1217 const uint256 &GetTxHash(unsigned int nIndex) const {
1218 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1219 assert(nIndex < vtx.size());
1220 return vMerkleTree[nIndex];
1223 std::vector<uint256> GetMerkleBranch(int nIndex) const
1225 if (vMerkleTree.empty())
1227 std::vector<uint256> vMerkleBranch;
1229 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1231 int i = std::min(nIndex^1, nSize-1);
1232 vMerkleBranch.push_back(vMerkleTree[j+i]);
1236 return vMerkleBranch;
1239 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1243 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1246 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1248 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1255 bool WriteToDisk(CDiskBlockPos &pos)
1257 // Open history file to append
1258 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1260 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1262 // Write index header
1263 unsigned int nSize = fileout.GetSerializeSize(*this);
1264 fileout << FLATDATA(pchMessageStart) << nSize;
1267 long fileOutPos = ftell(fileout);
1269 return error("CBlock::WriteToDisk() : ftell failed");
1270 pos.nPos = (unsigned int)fileOutPos;
1273 // Flush stdio buffers and commit to disk before returning
1275 if (!IsInitialBlockDownload())
1276 FileCommit(fileout);
1281 bool ReadFromDisk(const CDiskBlockPos &pos)
1285 // Open history file to read
1286 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1288 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1294 catch (std::exception &e) {
1295 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1299 if (!CheckProofOfWork(GetHash(), nBits))
1300 return error("CBlock::ReadFromDisk() : errors in block header");
1309 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
1310 BlockHashStr(GetHash()).c_str(),
1312 BlockHashStr(hashPrevBlock).c_str(),
1313 hashMerkleRoot.ToString().substr(0,10).c_str(),
1314 nTime, nBits, nNonce,
1316 for (unsigned int i = 0; i < vtx.size(); i++)
1321 printf(" vMerkleTree: ");
1322 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1323 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1328 // Undo the effects of this block (with given index) on the UTXO set represented by coins
1329 bool DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins);
1331 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1332 bool ConnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1334 // Read a block from disk
1335 bool ReadFromDisk(const CBlockIndex* pindex);
1337 // Add this block to the block index, and if necessary, switch the active block chain to this
1338 bool AddToBlockIndex(const CDiskBlockPos &pos);
1340 // Context-independent validity checks
1341 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
1343 // Store block on disk
1344 // if dbp is provided, the file is known to already reside on disk
1345 bool AcceptBlock(CDiskBlockPos *dbp = NULL);
1352 class CBlockFileInfo
1355 unsigned int nBlocks; // number of blocks stored in file
1356 unsigned int nSize; // number of used bytes of block file
1357 unsigned int nUndoSize; // number of used bytes in the undo file
1358 unsigned int nHeightFirst; // lowest height of block in file
1359 unsigned int nHeightLast; // highest height of block in file
1360 uint64 nTimeFirst; // earliest time of block in file
1361 uint64 nTimeLast; // latest time of block in file
1363 IMPLEMENT_SERIALIZE(
1364 READWRITE(VARINT(nBlocks));
1365 READWRITE(VARINT(nSize));
1366 READWRITE(VARINT(nUndoSize));
1367 READWRITE(VARINT(nHeightFirst));
1368 READWRITE(VARINT(nHeightLast));
1369 READWRITE(VARINT(nTimeFirst));
1370 READWRITE(VARINT(nTimeLast));
1387 std::string ToString() const {
1388 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());
1391 // update statistics (does not update nSize)
1392 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1393 if (nBlocks==0 || nHeightFirst > nHeightIn)
1394 nHeightFirst = nHeightIn;
1395 if (nBlocks==0 || nTimeFirst > nTimeIn)
1396 nTimeFirst = nTimeIn;
1398 if (nHeightIn > nHeightFirst)
1399 nHeightLast = nHeightIn;
1400 if (nTimeIn > nTimeLast)
1401 nTimeLast = nTimeIn;
1405 extern CCriticalSection cs_LastBlockFile;
1406 extern CBlockFileInfo infoLastBlockFile;
1407 extern int nLastBlockFile;
1410 BLOCK_VALID_UNKNOWN = 0,
1411 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1412 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1413 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1414 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1415 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
1416 BLOCK_VALID_MASK = 7,
1418 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
1419 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
1420 BLOCK_HAVE_MASK = 24,
1422 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
1423 BLOCK_FAILED_CHILD = 64, // descends from failed block
1424 BLOCK_FAILED_MASK = 96
1427 /** The block chain is a tree shaped structure starting with the
1428 * genesis block at the root, with each block potentially having multiple
1429 * candidates to be the next block. pprev and pnext link a path through the
1430 * main/longest chain. A blockindex may have multiple pprev pointing back
1431 * to it, but pnext will only point forward to the longest branch, or will
1432 * be null if the block is not part of the longest chain.
1437 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1438 const uint256* phashBlock;
1440 // pointer to the index of the predecessor of this block
1443 // (memory only) pointer to the index of the *active* successor of this block
1446 // height of the entry in the chain. The genesis block has height 0
1449 // Which # file this block is stored in (blk?????.dat)
1452 // Byte offset within blk?????.dat where this block's data is stored
1453 unsigned int nDataPos;
1455 // Byte offset within rev?????.dat where this block's undo data is stored
1456 unsigned int nUndoPos;
1458 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
1459 CBigNum bnChainWork;
1461 // Number of transactions in this block.
1462 // Note: in a potential headers-first mode, this number cannot be relied upon
1465 // (memory only) Number of transactions in the chain up to and including this block
1466 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
1468 // Verification status of this block. See enum BlockStatus
1469 unsigned int nStatus;
1473 uint256 hashMerkleRoot;
1476 unsigned int nNonce;
1500 CBlockIndex(CBlockHeader& block)
1514 nVersion = block.nVersion;
1515 hashMerkleRoot = block.hashMerkleRoot;
1516 nTime = block.nTime;
1517 nBits = block.nBits;
1518 nNonce = block.nNonce;
1521 CDiskBlockPos GetBlockPos() const {
1523 if (nStatus & BLOCK_HAVE_DATA) {
1525 ret.nPos = nDataPos;
1530 CDiskBlockPos GetUndoPos() const {
1532 if (nStatus & BLOCK_HAVE_UNDO) {
1534 ret.nPos = nUndoPos;
1539 CBlockHeader GetBlockHeader() const
1542 block.nVersion = nVersion;
1544 block.hashPrevBlock = pprev->GetBlockHash();
1545 block.hashMerkleRoot = hashMerkleRoot;
1546 block.nTime = nTime;
1547 block.nBits = nBits;
1548 block.nNonce = nNonce;
1552 uint256 GetBlockHash() const
1557 int64 GetBlockTime() const
1559 return (int64)nTime;
1562 CBigNum GetBlockWork() const
1565 bnTarget.SetCompact(nBits);
1568 return (CBigNum(1)<<256) / (bnTarget+1);
1571 bool IsInMainChain() const
1573 return (pnext || this == pindexBest);
1576 bool CheckIndex() const
1578 return CheckProofOfWork(GetBlockHash(), nBits);
1581 enum { nMedianTimeSpan=11 };
1583 int64 GetMedianTimePast() const
1585 int64 pmedian[nMedianTimeSpan];
1586 int64* pbegin = &pmedian[nMedianTimeSpan];
1587 int64* pend = &pmedian[nMedianTimeSpan];
1589 const CBlockIndex* pindex = this;
1590 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1591 *(--pbegin) = pindex->GetBlockTime();
1593 std::sort(pbegin, pend);
1594 return pbegin[(pend - pbegin)/2];
1597 int64 GetMedianTime() const
1599 const CBlockIndex* pindex = this;
1600 for (int i = 0; i < nMedianTimeSpan/2; i++)
1603 return GetBlockTime();
1604 pindex = pindex->pnext;
1606 return pindex->GetMedianTimePast();
1610 * Returns true if there are nRequired or more blocks of minVersion or above
1611 * in the last nToCheck blocks, starting at pstart and going backwards.
1613 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1614 unsigned int nRequired, unsigned int nToCheck);
1616 std::string ToString() const
1618 return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
1619 pprev, pnext, nHeight,
1620 hashMerkleRoot.ToString().substr(0,10).c_str(),
1621 BlockHashStr(GetBlockHash()).c_str());
1626 printf("%s\n", ToString().c_str());
1630 struct CBlockIndexWorkComparator
1632 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1633 if (pa->bnChainWork > pb->bnChainWork) return false;
1634 if (pa->bnChainWork < pb->bnChainWork) return true;
1636 if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
1637 if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
1639 return false; // identical blocks
1645 /** Used to marshal pointers into hashes for db storage. */
1646 class CDiskBlockIndex : public CBlockIndex
1655 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1656 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1661 if (!(nType & SER_GETHASH))
1662 READWRITE(VARINT(nVersion));
1664 READWRITE(VARINT(nHeight));
1665 READWRITE(VARINT(nStatus));
1666 READWRITE(VARINT(nTx));
1667 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1668 READWRITE(VARINT(nFile));
1669 if (nStatus & BLOCK_HAVE_DATA)
1670 READWRITE(VARINT(nDataPos));
1671 if (nStatus & BLOCK_HAVE_UNDO)
1672 READWRITE(VARINT(nUndoPos));
1675 READWRITE(this->nVersion);
1676 READWRITE(hashPrev);
1677 READWRITE(hashMerkleRoot);
1683 uint256 GetBlockHash() const
1686 block.nVersion = nVersion;
1687 block.hashPrevBlock = hashPrev;
1688 block.hashMerkleRoot = hashMerkleRoot;
1689 block.nTime = nTime;
1690 block.nBits = nBits;
1691 block.nNonce = nNonce;
1692 return block.GetHash();
1696 std::string ToString() const
1698 std::string str = "CDiskBlockIndex(";
1699 str += CBlockIndex::ToString();
1700 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1701 GetBlockHash().ToString().c_str(),
1702 BlockHashStr(hashPrev).c_str());
1708 printf("%s\n", ToString().c_str());
1719 /** Describes a place in the block chain to another node such that if the
1720 * other node doesn't have the same branch, it can find a recent common trunk.
1721 * The further back it is, the further before the fork it may be.
1726 std::vector<uint256> vHave;
1733 explicit CBlockLocator(const CBlockIndex* pindex)
1738 explicit CBlockLocator(uint256 hashBlock)
1740 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1741 if (mi != mapBlockIndex.end())
1745 CBlockLocator(const std::vector<uint256>& vHaveIn)
1752 if (!(nType & SER_GETHASH))
1753 READWRITE(nVersion);
1764 return vHave.empty();
1767 void Set(const CBlockIndex* pindex)
1773 vHave.push_back(pindex->GetBlockHash());
1775 // Exponentially larger steps back
1776 for (int i = 0; pindex && i < nStep; i++)
1777 pindex = pindex->pprev;
1778 if (vHave.size() > 10)
1781 vHave.push_back(hashGenesisBlock);
1784 int GetDistanceBack()
1786 // Retrace how far back it was in the sender's branch
1789 BOOST_FOREACH(const uint256& hash, vHave)
1791 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1792 if (mi != mapBlockIndex.end())
1794 CBlockIndex* pindex = (*mi).second;
1795 if (pindex->IsInMainChain())
1805 CBlockIndex* GetBlockIndex()
1807 // Find the first block the caller has in the main chain
1808 BOOST_FOREACH(const uint256& hash, vHave)
1810 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1811 if (mi != mapBlockIndex.end())
1813 CBlockIndex* pindex = (*mi).second;
1814 if (pindex->IsInMainChain())
1818 return pindexGenesisBlock;
1821 uint256 GetBlockHash()
1823 // Find the first block the caller has in the main chain
1824 BOOST_FOREACH(const uint256& hash, vHave)
1826 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1827 if (mi != mapBlockIndex.end())
1829 CBlockIndex* pindex = (*mi).second;
1830 if (pindex->IsInMainChain())
1834 return hashGenesisBlock;
1839 CBlockIndex* pindex = GetBlockIndex();
1842 return pindex->nHeight;
1856 mutable CCriticalSection cs;
1857 std::map<uint256, CTransaction> mapTx;
1858 std::map<COutPoint, CInPoint> mapNextTx;
1860 bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1861 bool addUnchecked(const uint256& hash, CTransaction &tx);
1862 bool remove(const CTransaction &tx, bool fRecursive = false);
1863 bool removeConflicts(const CTransaction &tx);
1865 void queryHashes(std::vector<uint256>& vtxid);
1866 void pruneSpent(const uint256& hash, CCoins &coins);
1868 unsigned long size()
1871 return mapTx.size();
1874 bool exists(uint256 hash)
1876 return (mapTx.count(hash) != 0);
1879 CTransaction& lookup(uint256 hash)
1885 extern CTxMemPool mempool;
1890 uint64 nTransactions;
1891 uint64 nTransactionOutputs;
1892 uint64 nSerializedSize;
1894 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
1897 /** Abstract view on the open txout dataset. */
1901 // Retrieve the CCoins (unspent transaction outputs) for a given txid
1902 virtual bool GetCoins(uint256 txid, CCoins &coins);
1904 // Modify the CCoins for a given txid
1905 virtual bool SetCoins(uint256 txid, const CCoins &coins);
1907 // Just check whether we have data for a given txid.
1908 // This may (but cannot always) return true for fully spent transactions
1909 virtual bool HaveCoins(uint256 txid);
1911 // Retrieve the block index whose state this CCoinsView currently represents
1912 virtual CBlockIndex *GetBestBlock();
1914 // Modify the currently active block index
1915 virtual bool SetBestBlock(CBlockIndex *pindex);
1917 // Do a bulk modification (multiple SetCoins + one SetBestBlock)
1918 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1920 // Calculate statistics about the unspent transaction output set
1921 virtual bool GetStats(CCoinsStats &stats);
1923 // As we use CCoinsViews polymorphically, have a virtual destructor
1924 virtual ~CCoinsView() {}
1927 /** CCoinsView backed by another CCoinsView */
1928 class CCoinsViewBacked : public CCoinsView
1934 CCoinsViewBacked(CCoinsView &viewIn);
1935 bool GetCoins(uint256 txid, CCoins &coins);
1936 bool SetCoins(uint256 txid, const CCoins &coins);
1937 bool HaveCoins(uint256 txid);
1938 CBlockIndex *GetBestBlock();
1939 bool SetBestBlock(CBlockIndex *pindex);
1940 void SetBackend(CCoinsView &viewIn);
1941 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1942 bool GetStats(CCoinsStats &stats);
1945 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
1946 class CCoinsViewCache : public CCoinsViewBacked
1949 CBlockIndex *pindexTip;
1950 std::map<uint256,CCoins> cacheCoins;
1953 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
1955 // Standard CCoinsView methods
1956 bool GetCoins(uint256 txid, CCoins &coins);
1957 bool SetCoins(uint256 txid, const CCoins &coins);
1958 bool HaveCoins(uint256 txid);
1959 CBlockIndex *GetBestBlock();
1960 bool SetBestBlock(CBlockIndex *pindex);
1961 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1963 // Return a modifiable reference to a CCoins. Check HaveCoins first.
1964 // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
1966 CCoins &GetCoins(uint256 txid);
1968 // Push the modifications applied to this cache to its base.
1969 // Failure to call this method before destruction will cause the changes to be forgotten.
1972 // Calculate the size of the cache (in number of transactions)
1973 unsigned int GetCacheSize();
1976 std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
1979 /** CCoinsView that brings transactions from a memorypool into view.
1980 It does not check for spendings by memory pool transactions. */
1981 class CCoinsViewMemPool : public CCoinsViewBacked
1984 CTxMemPool &mempool;
1987 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
1988 bool GetCoins(uint256 txid, CCoins &coins);
1989 bool HaveCoins(uint256 txid);
1992 /** Global variable that points to the active CCoinsView (protected by cs_main) */
1993 extern CCoinsViewCache *pcoinsTip;
1995 /** Global variable that points to the active block tree (protected by cs_main) */
1996 extern CBlockTreeDB *pblocktree;