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
56 /** Maximum number of script-checking threads allowed */
57 static const int MAX_SCRIPTCHECK_THREADS = 16;
59 static const int fHaveUPnP = true;
61 static const int fHaveUPnP = false;
65 extern CScript COINBASE_FLAGS;
72 extern CCriticalSection cs_main;
73 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
74 extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
75 extern uint256 hashGenesisBlock;
76 extern CBlockIndex* pindexGenesisBlock;
77 extern int nBestHeight;
78 extern CBigNum bnBestChainWork;
79 extern CBigNum bnBestInvalidWork;
80 extern uint256 hashBestChain;
81 extern CBlockIndex* pindexBest;
82 extern unsigned int nTransactionsUpdated;
83 extern uint64 nLastBlockTx;
84 extern uint64 nLastBlockSize;
85 extern const std::string strMessageMagic;
86 extern double dHashesPerSec;
87 extern int64 nHPSTimerStart;
88 extern int64 nTimeBestReceived;
89 extern CCriticalSection cs_setpwalletRegistered;
90 extern std::set<CWallet*> setpwalletRegistered;
91 extern unsigned char pchMessageStart[4];
92 extern bool fImporting;
94 extern bool fBenchmark;
95 extern int nScriptCheckThreads;
96 extern unsigned int nCoinCacheSize;
99 extern int64 nTransactionFee;
101 // Minimum disk space required - used in CheckDiskSpace()
102 static const uint64 nMinDiskSpace = 52428800;
112 class CCoinsViewCache;
115 /** Register a wallet to receive updates from core */
116 void RegisterWallet(CWallet* pwalletIn);
117 /** Unregister a wallet from core */
118 void UnregisterWallet(CWallet* pwalletIn);
119 /** Push an updated transaction to all registered wallets */
120 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
121 /** Process an incoming block */
122 bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
123 /** Check whether enough disk space is available for an incoming block */
124 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
125 /** Open a block file (blk?????.dat) */
126 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
127 /** Open an undo file (rev?????.dat) */
128 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
129 /** Import blocks from an external file */
130 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
131 /** Load the block tree and coins database from disk */
132 bool LoadBlockIndex();
133 /** Print the loaded block tree */
134 void PrintBlockTree();
135 /** Find a block by height in the currently-connected chain */
136 CBlockIndex* FindBlockByHeight(int nHeight);
137 /** Process protocol messages received from a given node */
138 bool ProcessMessages(CNode* pfrom);
139 /** Send queued protocol messages to be sent to a give node */
140 bool SendMessages(CNode* pto, bool fSendTrickle);
141 /** Run the importer thread, which deals with reindexing, loading bootstrap.dat, and whatever is passed to -loadblock */
142 void ThreadImport(void *parg);
143 /** Run an instance of the script checking thread */
144 void ThreadScriptCheck(void* parg);
145 /** Stop the script checking threads */
146 void ThreadScriptCheckQuit();
147 /** Run the miner threads */
148 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
149 /** Generate a new block, without valid proof-of-work */
150 CBlock* CreateNewBlock(CReserveKey& reservekey);
151 /** Modify the extranonce in a block */
152 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
153 /** Do mining precalculation */
154 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
155 /** Check mined block */
156 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
157 /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
158 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
159 /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
160 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
161 /** Get the number of active peers */
162 int GetNumBlocksOfPeers();
163 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
164 bool IsInitialBlockDownload();
165 /** Format a string that describes several potential problems detected by the core */
166 std::string GetWarnings(std::string strFor);
167 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
168 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
169 /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
170 bool SetBestChain(CBlockIndex* pindexNew);
171 /** Find the best known block, and make it the tip of the block chain */
172 bool ConnectBestBlock();
173 /** Create a new block index entry for a given block hash */
174 CBlockIndex * InsertBlockIndex(uint256 hash);
175 /** Verify a signature */
176 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
188 static inline std::string BlockHashStr(const uint256& hash)
190 return hash.ToString();
193 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
202 READWRITE(VARINT(nFile));
203 READWRITE(VARINT(nPos));
210 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
215 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
216 return (a.nFile == b.nFile && a.nPos == b.nPos);
219 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
223 void SetNull() { nFile = -1; nPos = 0; }
224 bool IsNull() const { return (nFile == -1); }
230 /** An inpoint - a combination of a transaction and an index n into its vin */
237 CInPoint() { SetNull(); }
238 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
239 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
240 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
245 /** An outpoint - a combination of a transaction hash and an index n into its vout */
252 COutPoint() { SetNull(); }
253 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
254 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
255 void SetNull() { hash = 0; n = (unsigned int) -1; }
256 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
258 friend bool operator<(const COutPoint& a, const COutPoint& b)
260 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
263 friend bool operator==(const COutPoint& a, const COutPoint& b)
265 return (a.hash == b.hash && a.n == b.n);
268 friend bool operator!=(const COutPoint& a, const COutPoint& b)
273 std::string ToString() const
275 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
280 printf("%s\n", ToString().c_str());
287 /** An input of a transaction. It contains the location of the previous
288 * transaction's output that it claims and a signature that matches the
289 * output's public key.
296 unsigned int nSequence;
300 nSequence = std::numeric_limits<unsigned int>::max();
303 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
306 scriptSig = scriptSigIn;
307 nSequence = nSequenceIn;
310 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
312 prevout = COutPoint(hashPrevTx, nOut);
313 scriptSig = scriptSigIn;
314 nSequence = nSequenceIn;
320 READWRITE(scriptSig);
321 READWRITE(nSequence);
326 return (nSequence == std::numeric_limits<unsigned int>::max());
329 friend bool operator==(const CTxIn& a, const CTxIn& b)
331 return (a.prevout == b.prevout &&
332 a.scriptSig == b.scriptSig &&
333 a.nSequence == b.nSequence);
336 friend bool operator!=(const CTxIn& a, const CTxIn& b)
341 std::string ToString() const
345 str += prevout.ToString();
346 if (prevout.IsNull())
347 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
349 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
350 if (nSequence != std::numeric_limits<unsigned int>::max())
351 str += strprintf(", nSequence=%u", nSequence);
358 printf("%s\n", ToString().c_str());
365 /** An output of a transaction. It contains the public key that the next input
366 * must be able to sign with to claim it.
372 CScript scriptPubKey;
379 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
382 scriptPubKey = scriptPubKeyIn;
388 READWRITE(scriptPubKey);
394 scriptPubKey.clear();
399 return (nValue == -1);
402 uint256 GetHash() const
404 return SerializeHash(*this);
407 friend bool operator==(const CTxOut& a, const CTxOut& b)
409 return (a.nValue == b.nValue &&
410 a.scriptPubKey == b.scriptPubKey);
413 friend bool operator!=(const CTxOut& a, const CTxOut& b)
418 std::string ToString() const
420 if (scriptPubKey.size() < 6)
421 return "CTxOut(error)";
422 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
427 printf("%s\n", ToString().c_str());
441 /** The basic transaction that is broadcasted on the network and contained in
442 * blocks. A transaction can contain multiple inputs and outputs.
447 static const int CURRENT_VERSION=1;
449 std::vector<CTxIn> vin;
450 std::vector<CTxOut> vout;
451 unsigned int nLockTime;
453 // Denial-of-service detection:
455 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
464 READWRITE(this->nVersion);
465 nVersion = this->nVersion;
468 READWRITE(nLockTime);
473 nVersion = CTransaction::CURRENT_VERSION;
477 nDoS = 0; // Denial-of-service prevention
482 return (vin.empty() && vout.empty());
485 uint256 GetHash() const
487 return SerializeHash(*this);
490 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
492 // Time based nLockTime implemented in 0.1.6
495 if (nBlockHeight == 0)
496 nBlockHeight = nBestHeight;
498 nBlockTime = GetAdjustedTime();
499 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
501 BOOST_FOREACH(const CTxIn& txin, vin)
507 bool IsNewerThan(const CTransaction& old) const
509 if (vin.size() != old.vin.size())
511 for (unsigned int i = 0; i < vin.size(); i++)
512 if (vin[i].prevout != old.vin[i].prevout)
516 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
517 for (unsigned int i = 0; i < vin.size(); i++)
519 if (vin[i].nSequence != old.vin[i].nSequence)
521 if (vin[i].nSequence <= nLowest)
524 nLowest = vin[i].nSequence;
526 if (old.vin[i].nSequence < nLowest)
529 nLowest = old.vin[i].nSequence;
536 bool IsCoinBase() const
538 return (vin.size() == 1 && vin[0].prevout.IsNull());
541 /** Check for standard transaction types
542 @return True if all outputs (scriptPubKeys) use only standard transaction forms
544 bool IsStandard() const;
546 /** Check for standard transaction types
547 @param[in] mapInputs Map of previous transactions that have outputs we're spending
548 @return True if all inputs (scriptSigs) use only standard transaction forms
549 @see CTransaction::FetchInputs
551 bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
553 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
554 @return number of sigops this transaction's outputs will produce when spent
555 @see CTransaction::FetchInputs
557 unsigned int GetLegacySigOpCount() const;
559 /** Count ECDSA signature operations in pay-to-script-hash inputs.
561 @param[in] mapInputs Map of previous transactions that have outputs we're spending
562 @return maximum number of sigops required to validate this transaction's inputs
563 @see CTransaction::FetchInputs
565 unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
567 /** Amount of bitcoins spent by this transaction.
568 @return sum of all outputs (note: does not include fees)
570 int64 GetValueOut() const
573 BOOST_FOREACH(const CTxOut& txout, vout)
575 nValueOut += txout.nValue;
576 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
577 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
582 /** Amount of bitcoins coming in to this transaction
583 Note that lightweight clients may not know anything besides the hash of previous transactions,
584 so may not be able to calculate this.
586 @param[in] mapInputs Map of previous transactions that have outputs we're spending
587 @return Sum of value of all inputs (scriptSigs)
588 @see CTransaction::FetchInputs
590 int64 GetValueIn(CCoinsViewCache& mapInputs) const;
592 static bool AllowFree(double dPriority)
594 // Large (in bytes) low-priority (new, small-coin) transactions
596 return dPriority > COIN * 144 / 250;
599 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
601 friend bool operator==(const CTransaction& a, const CTransaction& b)
603 return (a.nVersion == b.nVersion &&
606 a.nLockTime == b.nLockTime);
609 friend bool operator!=(const CTransaction& a, const CTransaction& b)
615 std::string ToString() const
618 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
619 GetHash().ToString().substr(0,10).c_str(),
624 for (unsigned int i = 0; i < vin.size(); i++)
625 str += " " + vin[i].ToString() + "\n";
626 for (unsigned int i = 0; i < vout.size(); i++)
627 str += " " + vout[i].ToString() + "\n";
633 printf("%s", ToString().c_str());
637 // Do all possible client-mode checks
638 bool ClientCheckInputs() const;
640 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
641 bool HaveInputs(CCoinsViewCache &view) const;
643 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
644 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
645 // instead of being performed inline.
646 bool CheckInputs(CCoinsViewCache &view, bool fScriptChecks = true,
647 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
648 std::vector<CScriptCheck> *pvChecks = NULL) const;
650 // Apply the effects of this transaction on the UTXO set represented by view
651 bool UpdateCoins(CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
653 // Context-independent validity checks
654 bool CheckTransaction() const;
656 // Try to accept this transaction into the memory pool
657 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
660 static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
663 /** wrapper for CTxOut that provides a more compact serialization */
664 class CTxOutCompressor
670 static uint64 CompressAmount(uint64 nAmount);
671 static uint64 DecompressAmount(uint64 nAmount);
673 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
675 IMPLEMENT_SERIALIZE(({
677 uint64 nVal = CompressAmount(txout.nValue);
678 READWRITE(VARINT(nVal));
681 READWRITE(VARINT(nVal));
682 txout.nValue = DecompressAmount(nVal);
684 CScriptCompressor cscript(REF(txout.scriptPubKey));
689 /** Undo information for a CTxIn
691 * Contains the prevout's CTxOut being spent, and if this was the
692 * last output of the affected transaction, its metadata as well
693 * (coinbase or not, height, transaction version)
698 CTxOut txout; // the txout data before being spent
699 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
700 unsigned int nHeight; // if the outpoint was the last unspent: its height
701 int nVersion; // if the outpoint was the last unspent: its version
703 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
704 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
706 unsigned int GetSerializeSize(int nType, int nVersion) const {
707 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
708 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
709 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
712 template<typename Stream>
713 void Serialize(Stream &s, int nType, int nVersion) const {
714 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
716 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
717 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
720 template<typename Stream>
721 void Unserialize(Stream &s, int nType, int nVersion) {
722 unsigned int nCode = 0;
723 ::Unserialize(s, VARINT(nCode), nType, nVersion);
725 fCoinBase = nCode & 1;
727 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
728 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
732 /** Undo information for a CTransaction */
736 // undo information for all txins
737 std::vector<CTxInUndo> vprevout;
744 /** Undo information for a CBlock */
748 std::vector<CTxUndo> vtxundo; // for all but the coinbase
754 bool WriteToDisk(CDiskBlockPos &pos)
756 // Open history file to append
757 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
759 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
761 // Write index header
762 unsigned int nSize = fileout.GetSerializeSize(*this);
763 fileout << FLATDATA(pchMessageStart) << nSize;
766 long fileOutPos = ftell(fileout);
768 return error("CBlockUndo::WriteToDisk() : ftell failed");
769 pos.nPos = (unsigned int)fileOutPos;
772 // Flush stdio buffers and commit to disk before returning
774 if (!IsInitialBlockDownload())
781 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
786 * - unspentness bitvector, for vout[2] and further; least significant byte first
787 * - the non-spent CTxOuts (via CTxOutCompressor)
790 * The nCode value consists of:
791 * - bit 1: IsCoinBase()
792 * - bit 2: vout[0] is not spent
793 * - bit 4: vout[1] is not spent
794 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
795 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
796 * least one non-spent output).
798 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
799 * <><><--------------------------------------------><---->
801 * version code vout[1] height
804 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
805 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
806 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
807 * * 8358: compact amount representation for 60000000000 (600 BTC)
808 * * 00: special txout type pay-to-pubkey-hash
809 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
813 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
814 * <><><--><--------------------------------------------------><----------------------------------------------><---->
816 * version code unspentness vout[4] vout[16] height
819 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
820 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
821 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
822 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
823 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
824 * * 00: special txout type pay-to-pubkey-hash
825 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
826 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
827 * * bbd123: compact amount representation for 110397 (0.001 BTC)
828 * * 00: special txout type pay-to-pubkey-hash
829 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
835 // whether transaction is a coinbase
838 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
839 std::vector<CTxOut> vout;
841 // at which height this transaction was included in the active block chain
844 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
845 // as new tx version will probably only be introduced at certain heights
848 // construct a CCoins from a CTransaction, at a given height
849 CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
852 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
854 // remove spent outputs at the end of vout
856 while (vout.size() > 0 && vout.back().IsNull())
861 friend bool operator==(const CCoins &a, const CCoins &b) {
862 return a.fCoinBase == b.fCoinBase &&
863 a.nHeight == b.nHeight &&
864 a.nVersion == b.nVersion &&
867 friend bool operator!=(const CCoins &a, const CCoins &b) {
871 // calculate number of bytes for the bitmask, and its number of non-zero bytes
872 // each bit in the bitmask represents the availability of one output, but the
873 // availabilities of the first two outputs are encoded separately
874 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
875 unsigned int nLastUsedByte = 0;
876 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
878 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
879 if (!vout[2+b*8+i].IsNull()) {
885 nLastUsedByte = b + 1;
889 nBytes += nLastUsedByte;
892 bool IsCoinBase() const {
896 unsigned int GetSerializeSize(int nType, int nVersion) const {
897 unsigned int nSize = 0;
898 unsigned int nMaskSize = 0, nMaskCode = 0;
899 CalcMaskSize(nMaskSize, nMaskCode);
900 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
901 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
902 assert(fFirst || fSecond || nMaskCode);
903 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
905 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
906 // size of header code
907 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
911 for (unsigned int i = 0; i < vout.size(); i++)
912 if (!vout[i].IsNull())
913 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
915 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
919 template<typename Stream>
920 void Serialize(Stream &s, int nType, int nVersion) const {
921 unsigned int nMaskSize = 0, nMaskCode = 0;
922 CalcMaskSize(nMaskSize, nMaskCode);
923 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
924 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
925 assert(fFirst || fSecond || nMaskCode);
926 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
928 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
930 ::Serialize(s, VARINT(nCode), nType, nVersion);
932 for (unsigned int b = 0; b<nMaskSize; b++) {
933 unsigned char chAvail = 0;
934 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
935 if (!vout[2+b*8+i].IsNull())
937 ::Serialize(s, chAvail, nType, nVersion);
940 for (unsigned int i = 0; i < vout.size(); i++) {
941 if (!vout[i].IsNull())
942 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
945 ::Serialize(s, VARINT(nHeight), nType, nVersion);
948 template<typename Stream>
949 void Unserialize(Stream &s, int nType, int nVersion) {
950 unsigned int nCode = 0;
952 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
954 ::Unserialize(s, VARINT(nCode), nType, nVersion);
955 fCoinBase = nCode & 1;
956 std::vector<bool> vAvail(2, false);
957 vAvail[0] = nCode & 2;
958 vAvail[1] = nCode & 4;
959 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
961 while (nMaskCode > 0) {
962 unsigned char chAvail = 0;
963 ::Unserialize(s, chAvail, nType, nVersion);
964 for (unsigned int p = 0; p < 8; p++) {
965 bool f = (chAvail & (1 << p)) != 0;
972 vout.assign(vAvail.size(), CTxOut());
973 for (unsigned int i = 0; i < vAvail.size(); i++) {
975 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
978 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
982 // mark an outpoint spent, and construct undo information
983 bool Spend(const COutPoint &out, CTxInUndo &undo) {
984 if (out.n >= vout.size())
986 if (vout[out.n].IsNull())
988 undo = CTxInUndo(vout[out.n]);
989 vout[out.n].SetNull();
991 if (vout.size() == 0) {
992 undo.nHeight = nHeight;
993 undo.fCoinBase = fCoinBase;
994 undo.nVersion = this->nVersion;
1000 bool Spend(int nPos) {
1002 COutPoint out(0, nPos);
1003 return Spend(out, undo);
1006 // check whether a particular output is still available
1007 bool IsAvailable(unsigned int nPos) const {
1008 return (nPos < vout.size() && !vout[nPos].IsNull());
1011 // check whether the entire CCoins is spent
1012 // note that only !IsPruned() CCoins can be serialized
1013 bool IsPruned() const {
1014 BOOST_FOREACH(const CTxOut &out, vout)
1021 /** Closure representing one script verification
1022 * Note that this stores references to the spending transaction */
1026 CScript scriptPubKey;
1027 const CTransaction *ptxTo;
1029 unsigned int nFlags;
1034 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
1035 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
1036 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
1038 bool operator()() const;
1040 void swap(CScriptCheck &check) {
1041 scriptPubKey.swap(check.scriptPubKey);
1042 std::swap(ptxTo, check.ptxTo);
1043 std::swap(nIn, check.nIn);
1044 std::swap(nFlags, check.nFlags);
1045 std::swap(nHashType, check.nHashType);
1049 /** A transaction with a merkle branch linking it to the block chain. */
1050 class CMerkleTx : public CTransaction
1054 std::vector<uint256> vMerkleBranch;
1058 mutable bool fMerkleVerified;
1066 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1075 fMerkleVerified = false;
1081 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1082 nVersion = this->nVersion;
1083 READWRITE(hashBlock);
1084 READWRITE(vMerkleBranch);
1089 int SetMerkleBranch(const CBlock* pblock=NULL);
1090 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1091 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1092 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1093 int GetBlocksToMaturity() const;
1094 bool AcceptToMemoryPool(bool fCheckInputs=true);
1108 /** Nodes collect new transactions into a block, hash them into a hash tree,
1109 * and scan through nonce values to make the block's hash satisfy proof-of-work
1110 * requirements. When they solve the proof-of-work, they broadcast the block
1111 * to everyone and the block is added to the block chain. The first transaction
1112 * in the block is a special one that creates a new coin owned by the creator
1119 static const int CURRENT_VERSION=2;
1121 uint256 hashPrevBlock;
1122 uint256 hashMerkleRoot;
1125 unsigned int nNonce;
1134 READWRITE(this->nVersion);
1135 nVersion = this->nVersion;
1136 READWRITE(hashPrevBlock);
1137 READWRITE(hashMerkleRoot);
1145 nVersion = CBlockHeader::CURRENT_VERSION;
1155 return (nBits == 0);
1158 uint256 GetHash() const
1160 return Hash(BEGIN(nVersion), END(nNonce));
1163 int64 GetBlockTime() const
1165 return (int64)nTime;
1168 void UpdateTime(const CBlockIndex* pindexPrev);
1171 class CBlock : public CBlockHeader
1175 std::vector<CTransaction> vtx;
1178 mutable std::vector<uint256> vMerkleTree;
1180 // Denial-of-service detection:
1182 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1189 CBlock(const CBlockHeader &header)
1192 *((CBlockHeader*)this) = header;
1197 READWRITE(*(CBlockHeader*)this);
1203 CBlockHeader::SetNull();
1205 vMerkleTree.clear();
1209 uint256 BuildMerkleTree() const
1211 vMerkleTree.clear();
1212 BOOST_FOREACH(const CTransaction& tx, vtx)
1213 vMerkleTree.push_back(tx.GetHash());
1215 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1217 for (int i = 0; i < nSize; i += 2)
1219 int i2 = std::min(i+1, nSize-1);
1220 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1221 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1225 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1228 const uint256 &GetTxHash(unsigned int nIndex) const {
1229 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1230 assert(nIndex < vtx.size());
1231 return vMerkleTree[nIndex];
1234 std::vector<uint256> GetMerkleBranch(int nIndex) const
1236 if (vMerkleTree.empty())
1238 std::vector<uint256> vMerkleBranch;
1240 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1242 int i = std::min(nIndex^1, nSize-1);
1243 vMerkleBranch.push_back(vMerkleTree[j+i]);
1247 return vMerkleBranch;
1250 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1254 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1257 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1259 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1266 bool WriteToDisk(CDiskBlockPos &pos)
1268 // Open history file to append
1269 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1271 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1273 // Write index header
1274 unsigned int nSize = fileout.GetSerializeSize(*this);
1275 fileout << FLATDATA(pchMessageStart) << nSize;
1278 long fileOutPos = ftell(fileout);
1280 return error("CBlock::WriteToDisk() : ftell failed");
1281 pos.nPos = (unsigned int)fileOutPos;
1284 // Flush stdio buffers and commit to disk before returning
1286 if (!IsInitialBlockDownload())
1287 FileCommit(fileout);
1292 bool ReadFromDisk(const CDiskBlockPos &pos)
1296 // Open history file to read
1297 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1299 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1305 catch (std::exception &e) {
1306 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1310 if (!CheckProofOfWork(GetHash(), nBits))
1311 return error("CBlock::ReadFromDisk() : errors in block header");
1320 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
1321 BlockHashStr(GetHash()).c_str(),
1323 BlockHashStr(hashPrevBlock).c_str(),
1324 hashMerkleRoot.ToString().substr(0,10).c_str(),
1325 nTime, nBits, nNonce,
1327 for (unsigned int i = 0; i < vtx.size(); i++)
1332 printf(" vMerkleTree: ");
1333 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1334 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1339 // Undo the effects of this block (with given index) on the UTXO set represented by coins
1340 bool DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins);
1342 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1343 bool ConnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1345 // Read a block from disk
1346 bool ReadFromDisk(const CBlockIndex* pindex);
1348 // Add this block to the block index, and if necessary, switch the active block chain to this
1349 bool AddToBlockIndex(const CDiskBlockPos &pos);
1351 // Context-independent validity checks
1352 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
1354 // Store block on disk
1355 // if dbp is provided, the file is known to already reside on disk
1356 bool AcceptBlock(CDiskBlockPos *dbp = NULL);
1363 class CBlockFileInfo
1366 unsigned int nBlocks; // number of blocks stored in file
1367 unsigned int nSize; // number of used bytes of block file
1368 unsigned int nUndoSize; // number of used bytes in the undo file
1369 unsigned int nHeightFirst; // lowest height of block in file
1370 unsigned int nHeightLast; // highest height of block in file
1371 uint64 nTimeFirst; // earliest time of block in file
1372 uint64 nTimeLast; // latest time of block in file
1374 IMPLEMENT_SERIALIZE(
1375 READWRITE(VARINT(nBlocks));
1376 READWRITE(VARINT(nSize));
1377 READWRITE(VARINT(nUndoSize));
1378 READWRITE(VARINT(nHeightFirst));
1379 READWRITE(VARINT(nHeightLast));
1380 READWRITE(VARINT(nTimeFirst));
1381 READWRITE(VARINT(nTimeLast));
1398 std::string ToString() const {
1399 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());
1402 // update statistics (does not update nSize)
1403 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1404 if (nBlocks==0 || nHeightFirst > nHeightIn)
1405 nHeightFirst = nHeightIn;
1406 if (nBlocks==0 || nTimeFirst > nTimeIn)
1407 nTimeFirst = nTimeIn;
1409 if (nHeightIn > nHeightFirst)
1410 nHeightLast = nHeightIn;
1411 if (nTimeIn > nTimeLast)
1412 nTimeLast = nTimeIn;
1416 extern CCriticalSection cs_LastBlockFile;
1417 extern CBlockFileInfo infoLastBlockFile;
1418 extern int nLastBlockFile;
1421 BLOCK_VALID_UNKNOWN = 0,
1422 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1423 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1424 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1425 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1426 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
1427 BLOCK_VALID_MASK = 7,
1429 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
1430 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
1431 BLOCK_HAVE_MASK = 24,
1433 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
1434 BLOCK_FAILED_CHILD = 64, // descends from failed block
1435 BLOCK_FAILED_MASK = 96
1438 /** The block chain is a tree shaped structure starting with the
1439 * genesis block at the root, with each block potentially having multiple
1440 * candidates to be the next block. pprev and pnext link a path through the
1441 * main/longest chain. A blockindex may have multiple pprev pointing back
1442 * to it, but pnext will only point forward to the longest branch, or will
1443 * be null if the block is not part of the longest chain.
1448 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1449 const uint256* phashBlock;
1451 // pointer to the index of the predecessor of this block
1454 // (memory only) pointer to the index of the *active* successor of this block
1457 // height of the entry in the chain. The genesis block has height 0
1460 // Which # file this block is stored in (blk?????.dat)
1463 // Byte offset within blk?????.dat where this block's data is stored
1464 unsigned int nDataPos;
1466 // Byte offset within rev?????.dat where this block's undo data is stored
1467 unsigned int nUndoPos;
1469 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
1470 CBigNum bnChainWork;
1472 // Number of transactions in this block.
1473 // Note: in a potential headers-first mode, this number cannot be relied upon
1476 // (memory only) Number of transactions in the chain up to and including this block
1477 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
1479 // Verification status of this block. See enum BlockStatus
1480 unsigned int nStatus;
1484 uint256 hashMerkleRoot;
1487 unsigned int nNonce;
1511 CBlockIndex(CBlockHeader& block)
1525 nVersion = block.nVersion;
1526 hashMerkleRoot = block.hashMerkleRoot;
1527 nTime = block.nTime;
1528 nBits = block.nBits;
1529 nNonce = block.nNonce;
1532 CDiskBlockPos GetBlockPos() const {
1534 if (nStatus & BLOCK_HAVE_DATA) {
1536 ret.nPos = nDataPos;
1541 CDiskBlockPos GetUndoPos() const {
1543 if (nStatus & BLOCK_HAVE_UNDO) {
1545 ret.nPos = nUndoPos;
1550 CBlockHeader GetBlockHeader() const
1553 block.nVersion = nVersion;
1555 block.hashPrevBlock = pprev->GetBlockHash();
1556 block.hashMerkleRoot = hashMerkleRoot;
1557 block.nTime = nTime;
1558 block.nBits = nBits;
1559 block.nNonce = nNonce;
1563 uint256 GetBlockHash() const
1568 int64 GetBlockTime() const
1570 return (int64)nTime;
1573 CBigNum GetBlockWork() const
1576 bnTarget.SetCompact(nBits);
1579 return (CBigNum(1)<<256) / (bnTarget+1);
1582 bool IsInMainChain() const
1584 return (pnext || this == pindexBest);
1587 bool CheckIndex() const
1589 return CheckProofOfWork(GetBlockHash(), nBits);
1592 enum { nMedianTimeSpan=11 };
1594 int64 GetMedianTimePast() const
1596 int64 pmedian[nMedianTimeSpan];
1597 int64* pbegin = &pmedian[nMedianTimeSpan];
1598 int64* pend = &pmedian[nMedianTimeSpan];
1600 const CBlockIndex* pindex = this;
1601 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1602 *(--pbegin) = pindex->GetBlockTime();
1604 std::sort(pbegin, pend);
1605 return pbegin[(pend - pbegin)/2];
1608 int64 GetMedianTime() const
1610 const CBlockIndex* pindex = this;
1611 for (int i = 0; i < nMedianTimeSpan/2; i++)
1614 return GetBlockTime();
1615 pindex = pindex->pnext;
1617 return pindex->GetMedianTimePast();
1621 * Returns true if there are nRequired or more blocks of minVersion or above
1622 * in the last nToCheck blocks, starting at pstart and going backwards.
1624 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1625 unsigned int nRequired, unsigned int nToCheck);
1627 std::string ToString() const
1629 return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
1630 pprev, pnext, nHeight,
1631 hashMerkleRoot.ToString().substr(0,10).c_str(),
1632 BlockHashStr(GetBlockHash()).c_str());
1637 printf("%s\n", ToString().c_str());
1641 struct CBlockIndexWorkComparator
1643 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1644 if (pa->bnChainWork > pb->bnChainWork) return false;
1645 if (pa->bnChainWork < pb->bnChainWork) return true;
1647 if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
1648 if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
1650 return false; // identical blocks
1656 /** Used to marshal pointers into hashes for db storage. */
1657 class CDiskBlockIndex : public CBlockIndex
1666 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1667 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1672 if (!(nType & SER_GETHASH))
1673 READWRITE(VARINT(nVersion));
1675 READWRITE(VARINT(nHeight));
1676 READWRITE(VARINT(nStatus));
1677 READWRITE(VARINT(nTx));
1678 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1679 READWRITE(VARINT(nFile));
1680 if (nStatus & BLOCK_HAVE_DATA)
1681 READWRITE(VARINT(nDataPos));
1682 if (nStatus & BLOCK_HAVE_UNDO)
1683 READWRITE(VARINT(nUndoPos));
1686 READWRITE(this->nVersion);
1687 READWRITE(hashPrev);
1688 READWRITE(hashMerkleRoot);
1694 uint256 GetBlockHash() const
1697 block.nVersion = nVersion;
1698 block.hashPrevBlock = hashPrev;
1699 block.hashMerkleRoot = hashMerkleRoot;
1700 block.nTime = nTime;
1701 block.nBits = nBits;
1702 block.nNonce = nNonce;
1703 return block.GetHash();
1707 std::string ToString() const
1709 std::string str = "CDiskBlockIndex(";
1710 str += CBlockIndex::ToString();
1711 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1712 GetBlockHash().ToString().c_str(),
1713 BlockHashStr(hashPrev).c_str());
1719 printf("%s\n", ToString().c_str());
1730 /** Describes a place in the block chain to another node such that if the
1731 * other node doesn't have the same branch, it can find a recent common trunk.
1732 * The further back it is, the further before the fork it may be.
1737 std::vector<uint256> vHave;
1744 explicit CBlockLocator(const CBlockIndex* pindex)
1749 explicit CBlockLocator(uint256 hashBlock)
1751 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1752 if (mi != mapBlockIndex.end())
1756 CBlockLocator(const std::vector<uint256>& vHaveIn)
1763 if (!(nType & SER_GETHASH))
1764 READWRITE(nVersion);
1775 return vHave.empty();
1778 void Set(const CBlockIndex* pindex)
1784 vHave.push_back(pindex->GetBlockHash());
1786 // Exponentially larger steps back
1787 for (int i = 0; pindex && i < nStep; i++)
1788 pindex = pindex->pprev;
1789 if (vHave.size() > 10)
1792 vHave.push_back(hashGenesisBlock);
1795 int GetDistanceBack()
1797 // Retrace how far back it was in the sender's branch
1800 BOOST_FOREACH(const uint256& hash, vHave)
1802 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1803 if (mi != mapBlockIndex.end())
1805 CBlockIndex* pindex = (*mi).second;
1806 if (pindex->IsInMainChain())
1816 CBlockIndex* GetBlockIndex()
1818 // Find the first block the caller has in the main chain
1819 BOOST_FOREACH(const uint256& hash, vHave)
1821 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1822 if (mi != mapBlockIndex.end())
1824 CBlockIndex* pindex = (*mi).second;
1825 if (pindex->IsInMainChain())
1829 return pindexGenesisBlock;
1832 uint256 GetBlockHash()
1834 // Find the first block the caller has in the main chain
1835 BOOST_FOREACH(const uint256& hash, vHave)
1837 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1838 if (mi != mapBlockIndex.end())
1840 CBlockIndex* pindex = (*mi).second;
1841 if (pindex->IsInMainChain())
1845 return hashGenesisBlock;
1850 CBlockIndex* pindex = GetBlockIndex();
1853 return pindex->nHeight;
1867 mutable CCriticalSection cs;
1868 std::map<uint256, CTransaction> mapTx;
1869 std::map<COutPoint, CInPoint> mapNextTx;
1871 bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1872 bool addUnchecked(const uint256& hash, CTransaction &tx);
1873 bool remove(const CTransaction &tx, bool fRecursive = false);
1874 bool removeConflicts(const CTransaction &tx);
1876 void queryHashes(std::vector<uint256>& vtxid);
1877 void pruneSpent(const uint256& hash, CCoins &coins);
1879 unsigned long size()
1882 return mapTx.size();
1885 bool exists(uint256 hash)
1887 return (mapTx.count(hash) != 0);
1890 CTransaction& lookup(uint256 hash)
1896 extern CTxMemPool mempool;
1901 uint64 nTransactions;
1902 uint64 nTransactionOutputs;
1903 uint64 nSerializedSize;
1905 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
1908 /** Abstract view on the open txout dataset. */
1912 // Retrieve the CCoins (unspent transaction outputs) for a given txid
1913 virtual bool GetCoins(uint256 txid, CCoins &coins);
1915 // Modify the CCoins for a given txid
1916 virtual bool SetCoins(uint256 txid, const CCoins &coins);
1918 // Just check whether we have data for a given txid.
1919 // This may (but cannot always) return true for fully spent transactions
1920 virtual bool HaveCoins(uint256 txid);
1922 // Retrieve the block index whose state this CCoinsView currently represents
1923 virtual CBlockIndex *GetBestBlock();
1925 // Modify the currently active block index
1926 virtual bool SetBestBlock(CBlockIndex *pindex);
1928 // Do a bulk modification (multiple SetCoins + one SetBestBlock)
1929 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1931 // Calculate statistics about the unspent transaction output set
1932 virtual bool GetStats(CCoinsStats &stats);
1934 // As we use CCoinsViews polymorphically, have a virtual destructor
1935 virtual ~CCoinsView() {}
1938 /** CCoinsView backed by another CCoinsView */
1939 class CCoinsViewBacked : public CCoinsView
1945 CCoinsViewBacked(CCoinsView &viewIn);
1946 bool GetCoins(uint256 txid, CCoins &coins);
1947 bool SetCoins(uint256 txid, const CCoins &coins);
1948 bool HaveCoins(uint256 txid);
1949 CBlockIndex *GetBestBlock();
1950 bool SetBestBlock(CBlockIndex *pindex);
1951 void SetBackend(CCoinsView &viewIn);
1952 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1953 bool GetStats(CCoinsStats &stats);
1956 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
1957 class CCoinsViewCache : public CCoinsViewBacked
1960 CBlockIndex *pindexTip;
1961 std::map<uint256,CCoins> cacheCoins;
1964 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
1966 // Standard CCoinsView methods
1967 bool GetCoins(uint256 txid, CCoins &coins);
1968 bool SetCoins(uint256 txid, const CCoins &coins);
1969 bool HaveCoins(uint256 txid);
1970 CBlockIndex *GetBestBlock();
1971 bool SetBestBlock(CBlockIndex *pindex);
1972 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1974 // Return a modifiable reference to a CCoins. Check HaveCoins first.
1975 // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
1977 CCoins &GetCoins(uint256 txid);
1979 // Push the modifications applied to this cache to its base.
1980 // Failure to call this method before destruction will cause the changes to be forgotten.
1983 // Calculate the size of the cache (in number of transactions)
1984 unsigned int GetCacheSize();
1987 std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
1990 /** CCoinsView that brings transactions from a memorypool into view.
1991 It does not check for spendings by memory pool transactions. */
1992 class CCoinsViewMemPool : public CCoinsViewBacked
1995 CTxMemPool &mempool;
1998 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
1999 bool GetCoins(uint256 txid, CCoins &coins);
2000 bool HaveCoins(uint256 txid);
2003 /** Global variable that points to the active CCoinsView (protected by cs_main) */
2004 extern CCoinsViewCache *pcoinsTip;
2006 /** Global variable that points to the active block tree (protected by cs_main) */
2007 extern CBlockTreeDB *pblocktree;