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 size for transactions we're willing to relay/mine **/
32 static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
33 /** The maximum allowed number of signature check operations in a block (network rule) */
34 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
35 /** The maximum number of orphan transactions kept in memory */
36 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
37 /** The maximum number of entries in an 'inv' protocol message */
38 static const unsigned int MAX_INV_SZ = 50000;
39 /** The maximum size of a blk?????.dat file (since 0.8) */
40 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
41 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
42 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
43 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
44 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
45 /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
46 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
47 /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
48 static const int64 MIN_TX_FEE = 50000;
49 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
50 static const int64 MIN_RELAY_TX_FEE = 10000;
51 /** No amount larger than this (in satoshi) is valid */
52 static const int64 MAX_MONEY = 21000000 * COIN;
53 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
54 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
55 static const int COINBASE_MATURITY = 100;
56 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
57 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
58 /** Maximum number of script-checking threads allowed */
59 static const int MAX_SCRIPTCHECK_THREADS = 16;
61 static const int fHaveUPnP = true;
63 static const int fHaveUPnP = false;
67 extern CScript COINBASE_FLAGS;
74 extern CCriticalSection cs_main;
75 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
76 extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
77 extern uint256 hashGenesisBlock;
78 extern CBlockIndex* pindexGenesisBlock;
79 extern int nBestHeight;
80 extern CBigNum bnBestChainWork;
81 extern CBigNum bnBestInvalidWork;
82 extern uint256 hashBestChain;
83 extern CBlockIndex* pindexBest;
84 extern unsigned int nTransactionsUpdated;
85 extern uint64 nLastBlockTx;
86 extern uint64 nLastBlockSize;
87 extern const std::string strMessageMagic;
88 extern double dHashesPerSec;
89 extern int64 nHPSTimerStart;
90 extern int64 nTimeBestReceived;
91 extern CCriticalSection cs_setpwalletRegistered;
92 extern std::set<CWallet*> setpwalletRegistered;
93 extern unsigned char pchMessageStart[4];
94 extern bool fImporting;
96 extern bool fBenchmark;
97 extern int nScriptCheckThreads;
99 extern unsigned int nCoinCacheSize;
102 extern int64 nTransactionFee;
104 // Minimum disk space required - used in CheckDiskSpace()
105 static const uint64 nMinDiskSpace = 52428800;
111 struct CDiskBlockPos;
115 class CCoinsViewCache;
117 class CValidationState;
119 struct CBlockTemplate;
122 /** Register a wallet to receive updates from core */
123 void RegisterWallet(CWallet* pwalletIn);
124 /** Unregister a wallet from core */
125 void UnregisterWallet(CWallet* pwalletIn);
126 /** Push an updated transaction to all registered wallets */
127 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
128 /** Process an incoming block */
129 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
130 /** Check whether enough disk space is available for an incoming block */
131 bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
132 /** Open a block file (blk?????.dat) */
133 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
134 /** Open an undo file (rev?????.dat) */
135 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
136 /** Import blocks from an external file */
137 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
138 /** Initialize a new block tree database + block data on disk */
139 bool InitBlockIndex();
140 /** Load the block tree and coins database from disk */
141 bool LoadBlockIndex();
142 /** Unload database information */
143 void UnloadBlockIndex();
144 /** Verify consistency of the block and coin databases */
146 /** Print the loaded block tree */
147 void PrintBlockTree();
148 /** Find a block by height in the currently-connected chain */
149 CBlockIndex* FindBlockByHeight(int nHeight);
150 /** Process protocol messages received from a given node */
151 bool ProcessMessages(CNode* pfrom);
152 /** Send queued protocol messages to be sent to a give node */
153 bool SendMessages(CNode* pto, bool fSendTrickle);
154 /** Run the importer thread, which deals with reindexing, loading bootstrap.dat, and whatever is passed to -loadblock */
155 void ThreadImport(void *parg);
156 /** Run an instance of the script checking thread */
157 void ThreadScriptCheck(void* parg);
158 /** Stop the script checking threads */
159 void ThreadScriptCheckQuit();
160 /** Run the miner threads */
161 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
162 /** Generate a new block, without valid proof-of-work */
163 CBlockTemplate* CreateNewBlock(CReserveKey& reservekey);
164 /** Modify the extranonce in a block */
165 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
166 /** Do mining precalculation */
167 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
168 /** Check mined block */
169 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
170 /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
171 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
172 /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
173 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
174 /** Get the number of active peers */
175 int GetNumBlocksOfPeers();
176 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
177 bool IsInitialBlockDownload();
178 /** Format a string that describes several potential problems detected by the core */
179 std::string GetWarnings(std::string strFor);
180 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
181 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
182 /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
183 bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
184 /** Find the best known block, and make it the tip of the block chain */
185 bool ConnectBestBlock(CValidationState &state);
186 /** Create a new block index entry for a given block hash */
187 CBlockIndex * InsertBlockIndex(uint256 hash);
188 /** Verify a signature */
189 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
190 /** Abort with a message */
191 bool AbortNode(const std::string &msg);
203 static inline std::string BlockHashStr(const uint256& hash)
205 return hash.ToString();
208 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
216 READWRITE(VARINT(nFile));
217 READWRITE(VARINT(nPos));
224 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
229 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
230 return (a.nFile == b.nFile && a.nPos == b.nPos);
233 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
237 void SetNull() { nFile = -1; nPos = 0; }
238 bool IsNull() const { return (nFile == -1); }
241 struct CDiskTxPos : public CDiskBlockPos
243 unsigned int nTxOffset; // after header
246 READWRITE(*(CDiskBlockPos*)this);
247 READWRITE(VARINT(nTxOffset));
250 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
258 CDiskBlockPos::SetNull();
264 /** An inpoint - a combination of a transaction and an index n into its vin */
271 CInPoint() { SetNull(); }
272 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
273 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
274 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
279 /** An outpoint - a combination of a transaction hash and an index n into its vout */
286 COutPoint() { SetNull(); }
287 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
288 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
289 void SetNull() { hash = 0; n = (unsigned int) -1; }
290 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
292 friend bool operator<(const COutPoint& a, const COutPoint& b)
294 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
297 friend bool operator==(const COutPoint& a, const COutPoint& b)
299 return (a.hash == b.hash && a.n == b.n);
302 friend bool operator!=(const COutPoint& a, const COutPoint& b)
307 std::string ToString() const
309 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
314 printf("%s\n", ToString().c_str());
321 /** An input of a transaction. It contains the location of the previous
322 * transaction's output that it claims and a signature that matches the
323 * output's public key.
330 unsigned int nSequence;
334 nSequence = std::numeric_limits<unsigned int>::max();
337 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
340 scriptSig = scriptSigIn;
341 nSequence = nSequenceIn;
344 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
346 prevout = COutPoint(hashPrevTx, nOut);
347 scriptSig = scriptSigIn;
348 nSequence = nSequenceIn;
354 READWRITE(scriptSig);
355 READWRITE(nSequence);
360 return (nSequence == std::numeric_limits<unsigned int>::max());
363 friend bool operator==(const CTxIn& a, const CTxIn& b)
365 return (a.prevout == b.prevout &&
366 a.scriptSig == b.scriptSig &&
367 a.nSequence == b.nSequence);
370 friend bool operator!=(const CTxIn& a, const CTxIn& b)
375 std::string ToString() const
379 str += prevout.ToString();
380 if (prevout.IsNull())
381 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
383 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
384 if (nSequence != std::numeric_limits<unsigned int>::max())
385 str += strprintf(", nSequence=%u", nSequence);
392 printf("%s\n", ToString().c_str());
399 /** An output of a transaction. It contains the public key that the next input
400 * must be able to sign with to claim it.
406 CScript scriptPubKey;
413 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
416 scriptPubKey = scriptPubKeyIn;
422 READWRITE(scriptPubKey);
428 scriptPubKey.clear();
433 return (nValue == -1);
436 uint256 GetHash() const
438 return SerializeHash(*this);
441 friend bool operator==(const CTxOut& a, const CTxOut& b)
443 return (a.nValue == b.nValue &&
444 a.scriptPubKey == b.scriptPubKey);
447 friend bool operator!=(const CTxOut& a, const CTxOut& b)
452 std::string ToString() const
454 if (scriptPubKey.size() < 6)
455 return "CTxOut(error)";
456 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
461 printf("%s\n", ToString().c_str());
474 /** The basic transaction that is broadcasted on the network and contained in
475 * blocks. A transaction can contain multiple inputs and outputs.
480 static const int CURRENT_VERSION=1;
482 std::vector<CTxIn> vin;
483 std::vector<CTxOut> vout;
484 unsigned int nLockTime;
493 READWRITE(this->nVersion);
494 nVersion = this->nVersion;
497 READWRITE(nLockTime);
502 nVersion = CTransaction::CURRENT_VERSION;
510 return (vin.empty() && vout.empty());
513 uint256 GetHash() const
515 return SerializeHash(*this);
518 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
520 // Time based nLockTime implemented in 0.1.6
523 if (nBlockHeight == 0)
524 nBlockHeight = nBestHeight;
526 nBlockTime = GetAdjustedTime();
527 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
529 BOOST_FOREACH(const CTxIn& txin, vin)
535 bool IsNewerThan(const CTransaction& old) const
537 if (vin.size() != old.vin.size())
539 for (unsigned int i = 0; i < vin.size(); i++)
540 if (vin[i].prevout != old.vin[i].prevout)
544 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
545 for (unsigned int i = 0; i < vin.size(); i++)
547 if (vin[i].nSequence != old.vin[i].nSequence)
549 if (vin[i].nSequence <= nLowest)
552 nLowest = vin[i].nSequence;
554 if (old.vin[i].nSequence < nLowest)
557 nLowest = old.vin[i].nSequence;
564 bool IsCoinBase() const
566 return (vin.size() == 1 && vin[0].prevout.IsNull());
569 /** Check for standard transaction types
570 @return True if all outputs (scriptPubKeys) use only standard transaction forms
572 bool IsStandard() const;
574 /** Check for standard transaction types
575 @param[in] mapInputs Map of previous transactions that have outputs we're spending
576 @return True if all inputs (scriptSigs) use only standard transaction forms
578 bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
580 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
581 @return number of sigops this transaction's outputs will produce when spent
583 unsigned int GetLegacySigOpCount() const;
585 /** Count ECDSA signature operations in pay-to-script-hash inputs.
587 @param[in] mapInputs Map of previous transactions that have outputs we're spending
588 @return maximum number of sigops required to validate this transaction's inputs
590 unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
592 /** Amount of bitcoins spent by this transaction.
593 @return sum of all outputs (note: does not include fees)
595 int64 GetValueOut() const
598 BOOST_FOREACH(const CTxOut& txout, vout)
600 nValueOut += txout.nValue;
601 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
602 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
607 /** Amount of bitcoins coming in to this transaction
608 Note that lightweight clients may not know anything besides the hash of previous transactions,
609 so may not be able to calculate this.
611 @param[in] mapInputs Map of previous transactions that have outputs we're spending
612 @return Sum of value of all inputs (scriptSigs)
614 int64 GetValueIn(CCoinsViewCache& mapInputs) const;
616 static bool AllowFree(double dPriority)
618 // Large (in bytes) low-priority (new, small-coin) transactions
620 return dPriority > COIN * 144 / 250;
623 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
625 friend bool operator==(const CTransaction& a, const CTransaction& b)
627 return (a.nVersion == b.nVersion &&
630 a.nLockTime == b.nLockTime);
633 friend bool operator!=(const CTransaction& a, const CTransaction& b)
639 std::string ToString() const
642 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
643 GetHash().ToString().substr(0,10).c_str(),
648 for (unsigned int i = 0; i < vin.size(); i++)
649 str += " " + vin[i].ToString() + "\n";
650 for (unsigned int i = 0; i < vout.size(); i++)
651 str += " " + vout[i].ToString() + "\n";
657 printf("%s", ToString().c_str());
661 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
662 bool HaveInputs(CCoinsViewCache &view) const;
664 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
665 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
666 // instead of being performed inline.
667 bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
668 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
669 std::vector<CScriptCheck> *pvChecks = NULL) const;
671 // Apply the effects of this transaction on the UTXO set represented by view
672 bool UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
674 // Context-independent validity checks
675 bool CheckTransaction(CValidationState &state) const;
677 // Try to accept this transaction into the memory pool
678 bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL);
681 static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
684 /** wrapper for CTxOut that provides a more compact serialization */
685 class CTxOutCompressor
691 static uint64 CompressAmount(uint64 nAmount);
692 static uint64 DecompressAmount(uint64 nAmount);
694 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
696 IMPLEMENT_SERIALIZE(({
698 uint64 nVal = CompressAmount(txout.nValue);
699 READWRITE(VARINT(nVal));
702 READWRITE(VARINT(nVal));
703 txout.nValue = DecompressAmount(nVal);
705 CScriptCompressor cscript(REF(txout.scriptPubKey));
710 /** Undo information for a CTxIn
712 * Contains the prevout's CTxOut being spent, and if this was the
713 * last output of the affected transaction, its metadata as well
714 * (coinbase or not, height, transaction version)
719 CTxOut txout; // the txout data before being spent
720 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
721 unsigned int nHeight; // if the outpoint was the last unspent: its height
722 int nVersion; // if the outpoint was the last unspent: its version
724 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
725 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
727 unsigned int GetSerializeSize(int nType, int nVersion) const {
728 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
729 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
730 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
733 template<typename Stream>
734 void Serialize(Stream &s, int nType, int nVersion) const {
735 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
737 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
738 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
741 template<typename Stream>
742 void Unserialize(Stream &s, int nType, int nVersion) {
743 unsigned int nCode = 0;
744 ::Unserialize(s, VARINT(nCode), nType, nVersion);
746 fCoinBase = nCode & 1;
748 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
749 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
753 /** Undo information for a CTransaction */
757 // undo information for all txins
758 std::vector<CTxInUndo> vprevout;
765 /** Undo information for a CBlock */
769 std::vector<CTxUndo> vtxundo; // for all but the coinbase
775 bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
777 // Open history file to append
778 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
780 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
782 // Write index header
783 unsigned int nSize = fileout.GetSerializeSize(*this);
784 fileout << FLATDATA(pchMessageStart) << nSize;
787 long fileOutPos = ftell(fileout);
789 return error("CBlockUndo::WriteToDisk() : ftell failed");
790 pos.nPos = (unsigned int)fileOutPos;
793 // calculate & write checksum
794 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
797 fileout << hasher.GetHash();
799 // Flush stdio buffers and commit to disk before returning
801 if (!IsInitialBlockDownload())
807 bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
809 // Open history file to read
810 CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
812 return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
815 uint256 hashChecksum;
818 filein >> hashChecksum;
820 catch (std::exception &e) {
821 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
825 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
828 if (hashChecksum != hasher.GetHash())
829 return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
835 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
840 * - unspentness bitvector, for vout[2] and further; least significant byte first
841 * - the non-spent CTxOuts (via CTxOutCompressor)
844 * The nCode value consists of:
845 * - bit 1: IsCoinBase()
846 * - bit 2: vout[0] is not spent
847 * - bit 4: vout[1] is not spent
848 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
849 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
850 * least one non-spent output).
852 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
853 * <><><--------------------------------------------><---->
855 * version code vout[1] height
858 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
859 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
860 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
861 * * 8358: compact amount representation for 60000000000 (600 BTC)
862 * * 00: special txout type pay-to-pubkey-hash
863 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
867 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
868 * <><><--><--------------------------------------------------><----------------------------------------------><---->
870 * version code unspentness vout[4] vout[16] height
873 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
874 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
875 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
876 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
877 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
878 * * 00: special txout type pay-to-pubkey-hash
879 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
880 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
881 * * bbd123: compact amount representation for 110397 (0.001 BTC)
882 * * 00: special txout type pay-to-pubkey-hash
883 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
889 // whether transaction is a coinbase
892 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
893 std::vector<CTxOut> vout;
895 // at which height this transaction was included in the active block chain
898 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
899 // as new tx version will probably only be introduced at certain heights
902 // construct a CCoins from a CTransaction, at a given height
903 CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
906 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
908 // remove spent outputs at the end of vout
910 while (vout.size() > 0 && vout.back().IsNull())
915 friend bool operator==(const CCoins &a, const CCoins &b) {
916 return a.fCoinBase == b.fCoinBase &&
917 a.nHeight == b.nHeight &&
918 a.nVersion == b.nVersion &&
921 friend bool operator!=(const CCoins &a, const CCoins &b) {
925 // calculate number of bytes for the bitmask, and its number of non-zero bytes
926 // each bit in the bitmask represents the availability of one output, but the
927 // availabilities of the first two outputs are encoded separately
928 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
929 unsigned int nLastUsedByte = 0;
930 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
932 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
933 if (!vout[2+b*8+i].IsNull()) {
939 nLastUsedByte = b + 1;
943 nBytes += nLastUsedByte;
946 bool IsCoinBase() const {
950 unsigned int GetSerializeSize(int nType, int nVersion) const {
951 unsigned int nSize = 0;
952 unsigned int nMaskSize = 0, nMaskCode = 0;
953 CalcMaskSize(nMaskSize, nMaskCode);
954 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
955 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
956 assert(fFirst || fSecond || nMaskCode);
957 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
959 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
960 // size of header code
961 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
965 for (unsigned int i = 0; i < vout.size(); i++)
966 if (!vout[i].IsNull())
967 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
969 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
973 template<typename Stream>
974 void Serialize(Stream &s, int nType, int nVersion) const {
975 unsigned int nMaskSize = 0, nMaskCode = 0;
976 CalcMaskSize(nMaskSize, nMaskCode);
977 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
978 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
979 assert(fFirst || fSecond || nMaskCode);
980 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
982 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
984 ::Serialize(s, VARINT(nCode), nType, nVersion);
986 for (unsigned int b = 0; b<nMaskSize; b++) {
987 unsigned char chAvail = 0;
988 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
989 if (!vout[2+b*8+i].IsNull())
991 ::Serialize(s, chAvail, nType, nVersion);
994 for (unsigned int i = 0; i < vout.size(); i++) {
995 if (!vout[i].IsNull())
996 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
999 ::Serialize(s, VARINT(nHeight), nType, nVersion);
1002 template<typename Stream>
1003 void Unserialize(Stream &s, int nType, int nVersion) {
1004 unsigned int nCode = 0;
1006 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
1008 ::Unserialize(s, VARINT(nCode), nType, nVersion);
1009 fCoinBase = nCode & 1;
1010 std::vector<bool> vAvail(2, false);
1011 vAvail[0] = nCode & 2;
1012 vAvail[1] = nCode & 4;
1013 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
1014 // spentness bitmask
1015 while (nMaskCode > 0) {
1016 unsigned char chAvail = 0;
1017 ::Unserialize(s, chAvail, nType, nVersion);
1018 for (unsigned int p = 0; p < 8; p++) {
1019 bool f = (chAvail & (1 << p)) != 0;
1020 vAvail.push_back(f);
1026 vout.assign(vAvail.size(), CTxOut());
1027 for (unsigned int i = 0; i < vAvail.size(); i++) {
1029 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1032 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1036 // mark an outpoint spent, and construct undo information
1037 bool Spend(const COutPoint &out, CTxInUndo &undo) {
1038 if (out.n >= vout.size())
1040 if (vout[out.n].IsNull())
1042 undo = CTxInUndo(vout[out.n]);
1043 vout[out.n].SetNull();
1045 if (vout.size() == 0) {
1046 undo.nHeight = nHeight;
1047 undo.fCoinBase = fCoinBase;
1048 undo.nVersion = this->nVersion;
1053 // mark a vout spent
1054 bool Spend(int nPos) {
1056 COutPoint out(0, nPos);
1057 return Spend(out, undo);
1060 // check whether a particular output is still available
1061 bool IsAvailable(unsigned int nPos) const {
1062 return (nPos < vout.size() && !vout[nPos].IsNull());
1065 // check whether the entire CCoins is spent
1066 // note that only !IsPruned() CCoins can be serialized
1067 bool IsPruned() const {
1068 BOOST_FOREACH(const CTxOut &out, vout)
1075 /** Closure representing one script verification
1076 * Note that this stores references to the spending transaction */
1080 CScript scriptPubKey;
1081 const CTransaction *ptxTo;
1083 unsigned int nFlags;
1088 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
1089 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
1090 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
1092 bool operator()() const;
1094 void swap(CScriptCheck &check) {
1095 scriptPubKey.swap(check.scriptPubKey);
1096 std::swap(ptxTo, check.ptxTo);
1097 std::swap(nIn, check.nIn);
1098 std::swap(nFlags, check.nFlags);
1099 std::swap(nHashType, check.nHashType);
1103 /** A transaction with a merkle branch linking it to the block chain. */
1104 class CMerkleTx : public CTransaction
1108 std::vector<uint256> vMerkleBranch;
1112 mutable bool fMerkleVerified;
1120 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1129 fMerkleVerified = false;
1135 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1136 nVersion = this->nVersion;
1137 READWRITE(hashBlock);
1138 READWRITE(vMerkleBranch);
1143 int SetMerkleBranch(const CBlock* pblock=NULL);
1144 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1145 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1146 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1147 int GetBlocksToMaturity() const;
1148 bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
1155 /** Data structure that represents a partial merkle tree.
1157 * It respresents a subset of the txid's of a known block, in a way that
1158 * allows recovery of the list of txid's and the merkle root, in an
1159 * authenticated way.
1161 * The encoding works as follows: we traverse the tree in depth-first order,
1162 * storing a bit for each traversed node, signifying whether the node is the
1163 * parent of at least one matched leaf txid (or a matched txid itself). In
1164 * case we are at the leaf level, or this bit is 0, its merkle node hash is
1165 * stored, and its children are not explorer further. Otherwise, no hash is
1166 * stored, but we recurse into both (or the only) child branch. During
1167 * decoding, the same depth-first traversal is performed, consuming bits and
1168 * hashes as they written during encoding.
1170 * The serialization is fixed and provides a hard guarantee about the
1173 * SIZE <= 10 + ceil(32.25*N)
1175 * Where N represents the number of leaf nodes of the partial tree. N itself
1178 * N <= total_transactions
1179 * N <= 1 + matched_transactions*tree_height
1181 * The serialization format:
1182 * - uint32 total_transactions (4 bytes)
1183 * - varint number of hashes (1-3 bytes)
1184 * - uint256[] hashes in depth-first order (<= 32*N bytes)
1185 * - varint number of bytes of flag bits (1-3 bytes)
1186 * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
1187 * The size constraints follow from this.
1189 class CPartialMerkleTree
1192 // the total number of transactions in the block
1193 unsigned int nTransactions;
1195 // node-is-parent-of-matched-txid bits
1196 std::vector<bool> vBits;
1198 // txids and internal hashes
1199 std::vector<uint256> vHash;
1201 // flag set when encountering invalid data
1204 // helper function to efficiently calculate the number of nodes at given height in the merkle tree
1205 unsigned int CalcTreeWidth(int height) {
1206 return (nTransactions+(1 << height)-1) >> height;
1209 // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
1210 uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
1212 // recursive function that traverses tree nodes, storing the data as bits and hashes
1213 void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
1215 // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
1216 // it returns the hash of the respective node.
1217 uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
1221 // serialization implementation
1222 IMPLEMENT_SERIALIZE(
1223 READWRITE(nTransactions);
1225 std::vector<unsigned char> vBytes;
1228 CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
1229 us.vBits.resize(vBytes.size() * 8);
1230 for (unsigned int p = 0; p < us.vBits.size(); p++)
1231 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
1234 vBytes.resize((vBits.size()+7)/8);
1235 for (unsigned int p = 0; p < vBits.size(); p++)
1236 vBytes[p / 8] |= vBits[p] << (p % 8);
1241 // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
1242 CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
1244 CPartialMerkleTree();
1246 // extract the matching txid's represented by this partial merkle tree.
1247 // returns the merkle root, or 0 in case of failure
1248 uint256 ExtractMatches(std::vector<uint256> &vMatch);
1252 /** Nodes collect new transactions into a block, hash them into a hash tree,
1253 * and scan through nonce values to make the block's hash satisfy proof-of-work
1254 * requirements. When they solve the proof-of-work, they broadcast the block
1255 * to everyone and the block is added to the block chain. The first transaction
1256 * in the block is a special one that creates a new coin owned by the creator
1263 static const int CURRENT_VERSION=2;
1265 uint256 hashPrevBlock;
1266 uint256 hashMerkleRoot;
1269 unsigned int nNonce;
1278 READWRITE(this->nVersion);
1279 nVersion = this->nVersion;
1280 READWRITE(hashPrevBlock);
1281 READWRITE(hashMerkleRoot);
1289 nVersion = CBlockHeader::CURRENT_VERSION;
1299 return (nBits == 0);
1302 uint256 GetHash() const
1304 return Hash(BEGIN(nVersion), END(nNonce));
1307 int64 GetBlockTime() const
1309 return (int64)nTime;
1312 void UpdateTime(const CBlockIndex* pindexPrev);
1315 class CBlock : public CBlockHeader
1319 std::vector<CTransaction> vtx;
1322 mutable std::vector<uint256> vMerkleTree;
1329 CBlock(const CBlockHeader &header)
1332 *((CBlockHeader*)this) = header;
1337 READWRITE(*(CBlockHeader*)this);
1343 CBlockHeader::SetNull();
1345 vMerkleTree.clear();
1348 CBlockHeader GetBlockHeader() const
1351 block.nVersion = nVersion;
1352 block.hashPrevBlock = hashPrevBlock;
1353 block.hashMerkleRoot = hashMerkleRoot;
1354 block.nTime = nTime;
1355 block.nBits = nBits;
1356 block.nNonce = nNonce;
1360 uint256 BuildMerkleTree() const
1362 vMerkleTree.clear();
1363 BOOST_FOREACH(const CTransaction& tx, vtx)
1364 vMerkleTree.push_back(tx.GetHash());
1366 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1368 for (int i = 0; i < nSize; i += 2)
1370 int i2 = std::min(i+1, nSize-1);
1371 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1372 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1376 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1379 const uint256 &GetTxHash(unsigned int nIndex) const {
1380 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1381 assert(nIndex < vtx.size());
1382 return vMerkleTree[nIndex];
1385 std::vector<uint256> GetMerkleBranch(int nIndex) const
1387 if (vMerkleTree.empty())
1389 std::vector<uint256> vMerkleBranch;
1391 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1393 int i = std::min(nIndex^1, nSize-1);
1394 vMerkleBranch.push_back(vMerkleTree[j+i]);
1398 return vMerkleBranch;
1401 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1405 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1408 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1410 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1416 bool WriteToDisk(CDiskBlockPos &pos)
1418 // Open history file to append
1419 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1421 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1423 // Write index header
1424 unsigned int nSize = fileout.GetSerializeSize(*this);
1425 fileout << FLATDATA(pchMessageStart) << nSize;
1428 long fileOutPos = ftell(fileout);
1430 return error("CBlock::WriteToDisk() : ftell failed");
1431 pos.nPos = (unsigned int)fileOutPos;
1434 // Flush stdio buffers and commit to disk before returning
1436 if (!IsInitialBlockDownload())
1437 FileCommit(fileout);
1442 bool ReadFromDisk(const CDiskBlockPos &pos)
1446 // Open history file to read
1447 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1449 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1455 catch (std::exception &e) {
1456 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1460 if (!CheckProofOfWork(GetHash(), nBits))
1461 return error("CBlock::ReadFromDisk() : errors in block header");
1470 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
1471 BlockHashStr(GetHash()).c_str(),
1473 BlockHashStr(hashPrevBlock).c_str(),
1474 hashMerkleRoot.ToString().substr(0,10).c_str(),
1475 nTime, nBits, nNonce,
1477 for (unsigned int i = 0; i < vtx.size(); i++)
1482 printf(" vMerkleTree: ");
1483 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1484 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1489 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1490 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
1491 * will be true if no problems were found. Otherwise, the return value will be false in case
1492 * of problems. Note that in any case, coins may be modified. */
1493 bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
1495 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1496 bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1498 // Read a block from disk
1499 bool ReadFromDisk(const CBlockIndex* pindex);
1501 // Add this block to the block index, and if necessary, switch the active block chain to this
1502 bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
1504 // Context-independent validity checks
1505 bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
1507 // Store block on disk
1508 // if dbp is provided, the file is known to already reside on disk
1509 bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
1516 class CBlockFileInfo
1519 unsigned int nBlocks; // number of blocks stored in file
1520 unsigned int nSize; // number of used bytes of block file
1521 unsigned int nUndoSize; // number of used bytes in the undo file
1522 unsigned int nHeightFirst; // lowest height of block in file
1523 unsigned int nHeightLast; // highest height of block in file
1524 uint64 nTimeFirst; // earliest time of block in file
1525 uint64 nTimeLast; // latest time of block in file
1527 IMPLEMENT_SERIALIZE(
1528 READWRITE(VARINT(nBlocks));
1529 READWRITE(VARINT(nSize));
1530 READWRITE(VARINT(nUndoSize));
1531 READWRITE(VARINT(nHeightFirst));
1532 READWRITE(VARINT(nHeightLast));
1533 READWRITE(VARINT(nTimeFirst));
1534 READWRITE(VARINT(nTimeLast));
1551 std::string ToString() const {
1552 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());
1555 // update statistics (does not update nSize)
1556 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1557 if (nBlocks==0 || nHeightFirst > nHeightIn)
1558 nHeightFirst = nHeightIn;
1559 if (nBlocks==0 || nTimeFirst > nTimeIn)
1560 nTimeFirst = nTimeIn;
1562 if (nHeightIn > nHeightFirst)
1563 nHeightLast = nHeightIn;
1564 if (nTimeIn > nTimeLast)
1565 nTimeLast = nTimeIn;
1569 extern CCriticalSection cs_LastBlockFile;
1570 extern CBlockFileInfo infoLastBlockFile;
1571 extern int nLastBlockFile;
1574 BLOCK_VALID_UNKNOWN = 0,
1575 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1576 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1577 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1578 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1579 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
1580 BLOCK_VALID_MASK = 7,
1582 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
1583 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
1584 BLOCK_HAVE_MASK = 24,
1586 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
1587 BLOCK_FAILED_CHILD = 64, // descends from failed block
1588 BLOCK_FAILED_MASK = 96
1591 /** The block chain is a tree shaped structure starting with the
1592 * genesis block at the root, with each block potentially having multiple
1593 * candidates to be the next block. pprev and pnext link a path through the
1594 * main/longest chain. A blockindex may have multiple pprev pointing back
1595 * to it, but pnext will only point forward to the longest branch, or will
1596 * be null if the block is not part of the longest chain.
1601 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1602 const uint256* phashBlock;
1604 // pointer to the index of the predecessor of this block
1607 // (memory only) pointer to the index of the *active* successor of this block
1610 // height of the entry in the chain. The genesis block has height 0
1613 // Which # file this block is stored in (blk?????.dat)
1616 // Byte offset within blk?????.dat where this block's data is stored
1617 unsigned int nDataPos;
1619 // Byte offset within rev?????.dat where this block's undo data is stored
1620 unsigned int nUndoPos;
1622 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
1623 CBigNum bnChainWork;
1625 // Number of transactions in this block.
1626 // Note: in a potential headers-first mode, this number cannot be relied upon
1629 // (memory only) Number of transactions in the chain up to and including this block
1630 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
1632 // Verification status of this block. See enum BlockStatus
1633 unsigned int nStatus;
1637 uint256 hashMerkleRoot;
1640 unsigned int nNonce;
1664 CBlockIndex(CBlockHeader& block)
1678 nVersion = block.nVersion;
1679 hashMerkleRoot = block.hashMerkleRoot;
1680 nTime = block.nTime;
1681 nBits = block.nBits;
1682 nNonce = block.nNonce;
1685 CDiskBlockPos GetBlockPos() const {
1687 if (nStatus & BLOCK_HAVE_DATA) {
1689 ret.nPos = nDataPos;
1694 CDiskBlockPos GetUndoPos() const {
1696 if (nStatus & BLOCK_HAVE_UNDO) {
1698 ret.nPos = nUndoPos;
1703 CBlockHeader GetBlockHeader() const
1706 block.nVersion = nVersion;
1708 block.hashPrevBlock = pprev->GetBlockHash();
1709 block.hashMerkleRoot = hashMerkleRoot;
1710 block.nTime = nTime;
1711 block.nBits = nBits;
1712 block.nNonce = nNonce;
1716 uint256 GetBlockHash() const
1721 int64 GetBlockTime() const
1723 return (int64)nTime;
1726 CBigNum GetBlockWork() const
1729 bnTarget.SetCompact(nBits);
1732 return (CBigNum(1)<<256) / (bnTarget+1);
1735 bool IsInMainChain() const
1737 return (pnext || this == pindexBest);
1740 bool CheckIndex() const
1742 return CheckProofOfWork(GetBlockHash(), nBits);
1745 enum { nMedianTimeSpan=11 };
1747 int64 GetMedianTimePast() const
1749 int64 pmedian[nMedianTimeSpan];
1750 int64* pbegin = &pmedian[nMedianTimeSpan];
1751 int64* pend = &pmedian[nMedianTimeSpan];
1753 const CBlockIndex* pindex = this;
1754 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1755 *(--pbegin) = pindex->GetBlockTime();
1757 std::sort(pbegin, pend);
1758 return pbegin[(pend - pbegin)/2];
1761 int64 GetMedianTime() const
1763 const CBlockIndex* pindex = this;
1764 for (int i = 0; i < nMedianTimeSpan/2; i++)
1767 return GetBlockTime();
1768 pindex = pindex->pnext;
1770 return pindex->GetMedianTimePast();
1774 * Returns true if there are nRequired or more blocks of minVersion or above
1775 * in the last nToCheck blocks, starting at pstart and going backwards.
1777 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1778 unsigned int nRequired, unsigned int nToCheck);
1780 std::string ToString() const
1782 return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
1783 pprev, pnext, nHeight,
1784 hashMerkleRoot.ToString().substr(0,10).c_str(),
1785 BlockHashStr(GetBlockHash()).c_str());
1790 printf("%s\n", ToString().c_str());
1794 struct CBlockIndexWorkComparator
1796 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1797 if (pa->bnChainWork > pb->bnChainWork) return false;
1798 if (pa->bnChainWork < pb->bnChainWork) return true;
1800 if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
1801 if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
1803 return false; // identical blocks
1809 /** Used to marshal pointers into hashes for db storage. */
1810 class CDiskBlockIndex : public CBlockIndex
1819 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1820 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1825 if (!(nType & SER_GETHASH))
1826 READWRITE(VARINT(nVersion));
1828 READWRITE(VARINT(nHeight));
1829 READWRITE(VARINT(nStatus));
1830 READWRITE(VARINT(nTx));
1831 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1832 READWRITE(VARINT(nFile));
1833 if (nStatus & BLOCK_HAVE_DATA)
1834 READWRITE(VARINT(nDataPos));
1835 if (nStatus & BLOCK_HAVE_UNDO)
1836 READWRITE(VARINT(nUndoPos));
1839 READWRITE(this->nVersion);
1840 READWRITE(hashPrev);
1841 READWRITE(hashMerkleRoot);
1847 uint256 GetBlockHash() const
1850 block.nVersion = nVersion;
1851 block.hashPrevBlock = hashPrev;
1852 block.hashMerkleRoot = hashMerkleRoot;
1853 block.nTime = nTime;
1854 block.nBits = nBits;
1855 block.nNonce = nNonce;
1856 return block.GetHash();
1860 std::string ToString() const
1862 std::string str = "CDiskBlockIndex(";
1863 str += CBlockIndex::ToString();
1864 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1865 GetBlockHash().ToString().c_str(),
1866 BlockHashStr(hashPrev).c_str());
1872 printf("%s\n", ToString().c_str());
1876 /** Capture information about block/transaction validation */
1877 class CValidationState {
1880 MODE_VALID, // everything ok
1881 MODE_INVALID, // network rule violation (DoS value may be set)
1882 MODE_ERROR, // run-time error
1886 CValidationState() : mode(MODE_VALID), nDoS(0) {}
1887 bool DoS(int level, bool ret = false) {
1888 if (mode == MODE_ERROR)
1891 mode = MODE_INVALID;
1894 bool Invalid(bool ret = false) {
1901 bool Abort(const std::string &msg) {
1906 return mode == MODE_VALID;
1909 return mode == MODE_INVALID;
1912 return mode == MODE_ERROR;
1914 bool IsInvalid(int &nDoSOut) {
1929 /** Describes a place in the block chain to another node such that if the
1930 * other node doesn't have the same branch, it can find a recent common trunk.
1931 * The further back it is, the further before the fork it may be.
1936 std::vector<uint256> vHave;
1943 explicit CBlockLocator(const CBlockIndex* pindex)
1948 explicit CBlockLocator(uint256 hashBlock)
1950 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1951 if (mi != mapBlockIndex.end())
1955 CBlockLocator(const std::vector<uint256>& vHaveIn)
1962 if (!(nType & SER_GETHASH))
1963 READWRITE(nVersion);
1974 return vHave.empty();
1977 void Set(const CBlockIndex* pindex)
1983 vHave.push_back(pindex->GetBlockHash());
1985 // Exponentially larger steps back
1986 for (int i = 0; pindex && i < nStep; i++)
1987 pindex = pindex->pprev;
1988 if (vHave.size() > 10)
1991 vHave.push_back(hashGenesisBlock);
1994 int GetDistanceBack()
1996 // Retrace how far back it was in the sender's branch
1999 BOOST_FOREACH(const uint256& hash, vHave)
2001 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2002 if (mi != mapBlockIndex.end())
2004 CBlockIndex* pindex = (*mi).second;
2005 if (pindex->IsInMainChain())
2015 CBlockIndex* GetBlockIndex()
2017 // Find the first block the caller has in the main chain
2018 BOOST_FOREACH(const uint256& hash, vHave)
2020 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2021 if (mi != mapBlockIndex.end())
2023 CBlockIndex* pindex = (*mi).second;
2024 if (pindex->IsInMainChain())
2028 return pindexGenesisBlock;
2031 uint256 GetBlockHash()
2033 // Find the first block the caller has in the main chain
2034 BOOST_FOREACH(const uint256& hash, vHave)
2036 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2037 if (mi != mapBlockIndex.end())
2039 CBlockIndex* pindex = (*mi).second;
2040 if (pindex->IsInMainChain())
2044 return hashGenesisBlock;
2049 CBlockIndex* pindex = GetBlockIndex();
2052 return pindex->nHeight;
2066 mutable CCriticalSection cs;
2067 std::map<uint256, CTransaction> mapTx;
2068 std::map<COutPoint, CInPoint> mapNextTx;
2070 bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs);
2071 bool addUnchecked(const uint256& hash, CTransaction &tx);
2072 bool remove(const CTransaction &tx, bool fRecursive = false);
2073 bool removeConflicts(const CTransaction &tx);
2075 void queryHashes(std::vector<uint256>& vtxid);
2076 void pruneSpent(const uint256& hash, CCoins &coins);
2078 unsigned long size()
2081 return mapTx.size();
2084 bool exists(uint256 hash)
2086 return (mapTx.count(hash) != 0);
2089 CTransaction& lookup(uint256 hash)
2095 extern CTxMemPool mempool;
2100 uint64 nTransactions;
2101 uint64 nTransactionOutputs;
2102 uint64 nSerializedSize;
2104 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
2107 /** Abstract view on the open txout dataset. */
2111 // Retrieve the CCoins (unspent transaction outputs) for a given txid
2112 virtual bool GetCoins(uint256 txid, CCoins &coins);
2114 // Modify the CCoins for a given txid
2115 virtual bool SetCoins(uint256 txid, const CCoins &coins);
2117 // Just check whether we have data for a given txid.
2118 // This may (but cannot always) return true for fully spent transactions
2119 virtual bool HaveCoins(uint256 txid);
2121 // Retrieve the block index whose state this CCoinsView currently represents
2122 virtual CBlockIndex *GetBestBlock();
2124 // Modify the currently active block index
2125 virtual bool SetBestBlock(CBlockIndex *pindex);
2127 // Do a bulk modification (multiple SetCoins + one SetBestBlock)
2128 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2130 // Calculate statistics about the unspent transaction output set
2131 virtual bool GetStats(CCoinsStats &stats);
2133 // As we use CCoinsViews polymorphically, have a virtual destructor
2134 virtual ~CCoinsView() {}
2137 /** CCoinsView backed by another CCoinsView */
2138 class CCoinsViewBacked : public CCoinsView
2144 CCoinsViewBacked(CCoinsView &viewIn);
2145 bool GetCoins(uint256 txid, CCoins &coins);
2146 bool SetCoins(uint256 txid, const CCoins &coins);
2147 bool HaveCoins(uint256 txid);
2148 CBlockIndex *GetBestBlock();
2149 bool SetBestBlock(CBlockIndex *pindex);
2150 void SetBackend(CCoinsView &viewIn);
2151 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2152 bool GetStats(CCoinsStats &stats);
2155 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2156 class CCoinsViewCache : public CCoinsViewBacked
2159 CBlockIndex *pindexTip;
2160 std::map<uint256,CCoins> cacheCoins;
2163 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2165 // Standard CCoinsView methods
2166 bool GetCoins(uint256 txid, CCoins &coins);
2167 bool SetCoins(uint256 txid, const CCoins &coins);
2168 bool HaveCoins(uint256 txid);
2169 CBlockIndex *GetBestBlock();
2170 bool SetBestBlock(CBlockIndex *pindex);
2171 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2173 // Return a modifiable reference to a CCoins. Check HaveCoins first.
2174 // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
2176 CCoins &GetCoins(uint256 txid);
2178 // Push the modifications applied to this cache to its base.
2179 // Failure to call this method before destruction will cause the changes to be forgotten.
2182 // Calculate the size of the cache (in number of transactions)
2183 unsigned int GetCacheSize();
2186 std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
2189 /** CCoinsView that brings transactions from a memorypool into view.
2190 It does not check for spendings by memory pool transactions. */
2191 class CCoinsViewMemPool : public CCoinsViewBacked
2194 CTxMemPool &mempool;
2197 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2198 bool GetCoins(uint256 txid, CCoins &coins);
2199 bool HaveCoins(uint256 txid);
2202 /** Global variable that points to the active CCoinsView (protected by cs_main) */
2203 extern CCoinsViewCache *pcoinsTip;
2205 /** Global variable that points to the active block tree (protected by cs_main) */
2206 extern CBlockTreeDB *pblocktree;
2208 struct CBlockTemplate
2211 std::vector<int64_t> vTxFees;
2212 std::vector<int64_t> vTxSigOps;
2220 /** Used to relay blocks as header + vector<merkle branch>
2221 * to filtered nodes.
2226 // Public only for unit testing
2227 CBlockHeader header;
2228 CPartialMerkleTree txn;
2231 // Public only for unit testing and relay testing
2233 std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
2235 // Create from a CBlock, filtering transactions according to filter
2236 // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
2237 // thus the filter will likely be modified.
2238 CMerkleBlock(const CBlock& block, CBloomFilter& filter);