1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
9 #if defined(HAVE_CONFIG_H)
10 #include "bitcoin-config.h"
14 #include "chainparams.h"
20 #include "txmempool.h"
36 /** The maximum allowed size for a serialized block, in bytes (network rule) */
37 static const unsigned int MAX_BLOCK_SIZE = 1000000;
38 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
39 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
40 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
41 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
42 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
43 /** The maximum size for transactions we're willing to relay/mine */
44 static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
45 /** The maximum allowed number of signature check operations in a block (network rule) */
46 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
47 /** The maximum number of orphan transactions kept in memory */
48 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
49 /** The maximum number of orphan blocks kept in memory */
50 static const unsigned int MAX_ORPHAN_BLOCKS = 750;
51 /** The maximum size of a blk?????.dat file (since 0.8) */
52 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
53 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
54 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
55 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
56 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
57 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
58 static const int COINBASE_MATURITY = 100;
59 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
60 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
61 /** Maximum number of script-checking threads allowed */
62 static const int MAX_SCRIPTCHECK_THREADS = 16;
63 /** Number of blocks that can be requested at any given time from a single peer. */
64 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
65 /** Timeout in seconds before considering a block download peer unresponsive. */
66 static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
69 static const int fHaveUPnP = true;
71 static const int fHaveUPnP = false;
74 /** "reject" message codes **/
75 static const unsigned char REJECT_MALFORMED = 0x01;
76 static const unsigned char REJECT_INVALID = 0x10;
77 static const unsigned char REJECT_OBSOLETE = 0x11;
78 static const unsigned char REJECT_DUPLICATE = 0x12;
79 static const unsigned char REJECT_NONSTANDARD = 0x40;
80 static const unsigned char REJECT_DUST = 0x41;
81 static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
82 static const unsigned char REJECT_CHECKPOINT = 0x43;
85 extern CScript COINBASE_FLAGS;
86 extern CCriticalSection cs_main;
87 extern CTxMemPool mempool;
88 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
89 extern uint64_t nLastBlockTx;
90 extern uint64_t nLastBlockSize;
91 extern const std::string strMessageMagic;
92 extern int64_t nTimeBestReceived;
93 extern bool fImporting;
95 extern bool fBenchmark;
96 extern int nScriptCheckThreads;
98 extern unsigned int nCoinCacheSize;
100 // Minimum disk space required - used in CheckDiskSpace()
101 static const uint64_t nMinDiskSpace = 52428800;
106 struct CDiskBlockPos;
109 class CValidationState;
110 class CWalletInterface;
111 struct CNodeStateStats;
113 struct CBlockTemplate;
115 /** Register a wallet to receive updates from core */
116 void RegisterWallet(CWalletInterface* pwalletIn);
117 /** Unregister a wallet from core */
118 void UnregisterWallet(CWalletInterface* pwalletIn);
119 /** Unregister all wallets from core */
120 void UnregisterAllWallets();
121 /** Push an updated transaction to all registered wallets */
122 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL);
124 /** Register with a network node to receive its signals */
125 void RegisterNodeSignals(CNodeSignals& nodeSignals);
126 /** Unregister a network node */
127 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
129 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
131 /** Process an incoming block */
132 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
133 /** Check whether enough disk space is available for an incoming block */
134 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
135 /** Open a block file (blk?????.dat) */
136 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
137 /** Open an undo file (rev?????.dat) */
138 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
139 /** Import blocks from an external file */
140 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
141 /** Initialize a new block tree database + block data on disk */
142 bool InitBlockIndex();
143 /** Load the block tree and coins database from disk */
144 bool LoadBlockIndex();
145 /** Unload database information */
146 void UnloadBlockIndex();
147 /** Verify consistency of the block and coin databases */
148 bool VerifyDB(int nCheckLevel, int nCheckDepth);
149 /** Print the loaded block tree */
150 void PrintBlockTree();
151 /** Process protocol messages received from a given node */
152 bool ProcessMessages(CNode* pfrom);
153 /** Send queued protocol messages to be sent to a give node */
154 bool SendMessages(CNode* pto, bool fSendTrickle);
155 /** Run an instance of the script checking thread */
156 void ThreadScriptCheck();
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_t 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 /** Find the best known block, and make it the tip of the block chain */
170 bool ActivateBestChain(CValidationState &state);
171 int64_t GetBlockValue(int nHeight, int64_t nFees);
172 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock);
174 void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev);
176 /** Create a new block index entry for a given block hash */
177 CBlockIndex * InsertBlockIndex(uint256 hash);
178 /** Verify a signature */
179 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
180 /** Abort with a message */
181 bool AbortNode(const std::string &msg);
182 /** Get statistics from node state */
183 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
184 /** Increase a node's misbehavior score. */
185 void Misbehaving(NodeId nodeid, int howmuch);
188 /** (try to) add transaction to memory pool **/
189 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
190 bool* pfMissingInputs, bool fRejectInsaneFee=false);
199 struct CNodeStateStats {
209 READWRITE(VARINT(nFile));
210 READWRITE(VARINT(nPos));
217 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
222 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
223 return (a.nFile == b.nFile && a.nPos == b.nPos);
226 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
230 void SetNull() { nFile = -1; nPos = 0; }
231 bool IsNull() const { return (nFile == -1); }
234 struct CDiskTxPos : public CDiskBlockPos
236 unsigned int nTxOffset; // after header
239 READWRITE(*(CDiskBlockPos*)this);
240 READWRITE(VARINT(nTxOffset));
243 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
251 CDiskBlockPos::SetNull();
264 int64_t GetMinFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode);
267 // Check transaction inputs, and make sure any
268 // pay-to-script-hash transactions are evaluating IsStandard scripts
270 // Why bother? To avoid denial-of-service attacks; an attacker
271 // can submit a standard HASH... OP_EQUAL transaction,
272 // which will get accepted into blocks. The redemption
273 // script can be anything; an attacker could use a very
274 // expensive-to-check-upon-redemption script like:
275 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
278 /** Check for standard transaction types
279 @param[in] mapInputs Map of previous transactions that have outputs we're spending
280 @return True if all inputs (scriptSigs) use only standard transaction forms
282 bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs);
284 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
285 @return number of sigops this transaction's outputs will produce when spent
286 @see CTransaction::FetchInputs
288 unsigned int GetLegacySigOpCount(const CTransaction& tx);
290 /** Count ECDSA signature operations in pay-to-script-hash inputs.
292 @param[in] mapInputs Map of previous transactions that have outputs we're spending
293 @return maximum number of sigops required to validate this transaction's inputs
294 @see CTransaction::FetchInputs
296 unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& mapInputs);
299 inline bool AllowFree(double dPriority)
301 // Large (in bytes) low-priority (new, small-coin) transactions
303 return dPriority > COIN * 144 / 250;
306 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
307 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
308 // instead of being performed inline.
309 bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
310 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
311 std::vector<CScriptCheck> *pvChecks = NULL);
313 // Apply the effects of this transaction on the UTXO set represented by view
314 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
316 // Context-independent validity checks
317 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
319 /** Check for standard transaction types
320 @return True if all outputs (scriptPubKeys) use only standard transaction forms
322 bool IsStandardTx(const CTransaction& tx, std::string& reason);
324 bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
326 /** Undo information for a CBlock */
330 std::vector<CTxUndo> vtxundo; // for all but the coinbase
336 bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
338 // Open history file to append
339 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
341 return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
343 // Write index header
344 unsigned int nSize = fileout.GetSerializeSize(*this);
345 fileout << FLATDATA(Params().MessageStart()) << nSize;
348 long fileOutPos = ftell(fileout);
350 return error("CBlockUndo::WriteToDisk : ftell failed");
351 pos.nPos = (unsigned int)fileOutPos;
354 // calculate & write checksum
355 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
358 fileout << hasher.GetHash();
360 // Flush stdio buffers and commit to disk before returning
362 if (!IsInitialBlockDownload())
368 bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
370 // Open history file to read
371 CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
373 return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
376 uint256 hashChecksum;
379 filein >> hashChecksum;
381 catch (std::exception &e) {
382 return error("%s : Deserialize or I/O error - %s", __PRETTY_FUNCTION__, e.what());
386 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
389 if (hashChecksum != hasher.GetHash())
390 return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
397 /** Closure representing one script verification
398 * Note that this stores references to the spending transaction */
402 CScript scriptPubKey;
403 const CTransaction *ptxTo;
410 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
411 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
412 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
414 bool operator()() const;
416 void swap(CScriptCheck &check) {
417 scriptPubKey.swap(check.scriptPubKey);
418 std::swap(ptxTo, check.ptxTo);
419 std::swap(nIn, check.nIn);
420 std::swap(nFlags, check.nFlags);
421 std::swap(nHashType, check.nHashType);
425 /** A transaction with a merkle branch linking it to the block chain. */
426 class CMerkleTx : public CTransaction
429 int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
433 std::vector<uint256> vMerkleBranch;
437 mutable bool fMerkleVerified;
445 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
454 fMerkleVerified = false;
460 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
461 nVersion = this->nVersion;
462 READWRITE(hashBlock);
463 READWRITE(vMerkleBranch);
468 int SetMerkleBranch(const CBlock* pblock=NULL);
470 // Return depth of transaction in blockchain:
471 // -1 : not in blockchain, and not in memory pool (conflicted transaction)
472 // 0 : in memory pool, waiting to be included in a block
473 // >=1 : this many blocks deep in the main chain
474 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
475 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
476 bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
477 int GetBlocksToMaturity() const;
478 bool AcceptToMemoryPool(bool fLimitFree=true);
485 /** Data structure that represents a partial merkle tree.
487 * It respresents a subset of the txid's of a known block, in a way that
488 * allows recovery of the list of txid's and the merkle root, in an
491 * The encoding works as follows: we traverse the tree in depth-first order,
492 * storing a bit for each traversed node, signifying whether the node is the
493 * parent of at least one matched leaf txid (or a matched txid itself). In
494 * case we are at the leaf level, or this bit is 0, its merkle node hash is
495 * stored, and its children are not explorer further. Otherwise, no hash is
496 * stored, but we recurse into both (or the only) child branch. During
497 * decoding, the same depth-first traversal is performed, consuming bits and
498 * hashes as they written during encoding.
500 * The serialization is fixed and provides a hard guarantee about the
503 * SIZE <= 10 + ceil(32.25*N)
505 * Where N represents the number of leaf nodes of the partial tree. N itself
508 * N <= total_transactions
509 * N <= 1 + matched_transactions*tree_height
511 * The serialization format:
512 * - uint32 total_transactions (4 bytes)
513 * - varint number of hashes (1-3 bytes)
514 * - uint256[] hashes in depth-first order (<= 32*N bytes)
515 * - varint number of bytes of flag bits (1-3 bytes)
516 * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
517 * The size constraints follow from this.
519 class CPartialMerkleTree
522 // the total number of transactions in the block
523 unsigned int nTransactions;
525 // node-is-parent-of-matched-txid bits
526 std::vector<bool> vBits;
528 // txids and internal hashes
529 std::vector<uint256> vHash;
531 // flag set when encountering invalid data
534 // helper function to efficiently calculate the number of nodes at given height in the merkle tree
535 unsigned int CalcTreeWidth(int height) {
536 return (nTransactions+(1 << height)-1) >> height;
539 // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
540 uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
542 // recursive function that traverses tree nodes, storing the data as bits and hashes
543 void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
545 // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
546 // it returns the hash of the respective node.
547 uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
551 // serialization implementation
553 READWRITE(nTransactions);
555 std::vector<unsigned char> vBytes;
558 CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
559 us.vBits.resize(vBytes.size() * 8);
560 for (unsigned int p = 0; p < us.vBits.size(); p++)
561 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
564 vBytes.resize((vBits.size()+7)/8);
565 for (unsigned int p = 0; p < vBits.size(); p++)
566 vBytes[p / 8] |= vBits[p] << (p % 8);
571 // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
572 CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
574 CPartialMerkleTree();
576 // extract the matching txid's represented by this partial merkle tree.
577 // returns the merkle root, or 0 in case of failure
578 uint256 ExtractMatches(std::vector<uint256> &vMatch);
583 /** Functions for disk access for blocks */
584 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
585 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
586 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
589 /** Functions for validating blocks and updating the block tree */
591 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
592 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
593 * will be true if no problems were found. Otherwise, the return value will be false in case
594 * of problems. Note that in any case, coins may be modified. */
595 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
597 // Apply the effects of this block (with given index) on the UTXO set represented by coins
598 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
600 // Add this block to the block index, and if necessary, switch the active block chain to this
601 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
603 // Context-independent validity checks
604 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
606 // Store block on disk
607 // if dbp is provided, the file is known to already reside on disk
608 bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp = NULL);
615 unsigned int nBlocks; // number of blocks stored in file
616 unsigned int nSize; // number of used bytes of block file
617 unsigned int nUndoSize; // number of used bytes in the undo file
618 unsigned int nHeightFirst; // lowest height of block in file
619 unsigned int nHeightLast; // highest height of block in file
620 uint64_t nTimeFirst; // earliest time of block in file
621 uint64_t nTimeLast; // latest time of block in file
624 READWRITE(VARINT(nBlocks));
625 READWRITE(VARINT(nSize));
626 READWRITE(VARINT(nUndoSize));
627 READWRITE(VARINT(nHeightFirst));
628 READWRITE(VARINT(nHeightLast));
629 READWRITE(VARINT(nTimeFirst));
630 READWRITE(VARINT(nTimeLast));
647 std::string ToString() const {
648 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());
651 // update statistics (does not update nSize)
652 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
653 if (nBlocks==0 || nHeightFirst > nHeightIn)
654 nHeightFirst = nHeightIn;
655 if (nBlocks==0 || nTimeFirst > nTimeIn)
656 nTimeFirst = nTimeIn;
658 if (nHeightIn > nHeightLast)
659 nHeightLast = nHeightIn;
660 if (nTimeIn > nTimeLast)
666 BLOCK_VALID_UNKNOWN = 0,
667 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
668 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
669 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
670 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
671 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
672 BLOCK_VALID_MASK = 7,
674 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
675 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
676 BLOCK_HAVE_MASK = 24,
678 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
679 BLOCK_FAILED_CHILD = 64, // descends from failed block
680 BLOCK_FAILED_MASK = 96
683 /** The block chain is a tree shaped structure starting with the
684 * genesis block at the root, with each block potentially having multiple
685 * candidates to be the next block. A blockindex may have multiple pprev pointing
686 * to it, but at most one of them can be part of the currently active branch.
691 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
692 const uint256* phashBlock;
694 // pointer to the index of the predecessor of this block
697 // height of the entry in the chain. The genesis block has height 0
700 // Which # file this block is stored in (blk?????.dat)
703 // Byte offset within blk?????.dat where this block's data is stored
704 unsigned int nDataPos;
706 // Byte offset within rev?????.dat where this block's undo data is stored
707 unsigned int nUndoPos;
709 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
712 // Number of transactions in this block.
713 // Note: in a potential headers-first mode, this number cannot be relied upon
716 // (memory only) Number of transactions in the chain up to and including this block
717 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
719 // Verification status of this block. See enum BlockStatus
720 unsigned int nStatus;
724 uint256 hashMerkleRoot;
729 // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
730 uint32_t nSequenceId;
753 CBlockIndex(CBlockHeader& block)
767 nVersion = block.nVersion;
768 hashMerkleRoot = block.hashMerkleRoot;
771 nNonce = block.nNonce;
774 CDiskBlockPos GetBlockPos() const {
776 if (nStatus & BLOCK_HAVE_DATA) {
783 CDiskBlockPos GetUndoPos() const {
785 if (nStatus & BLOCK_HAVE_UNDO) {
792 CBlockHeader GetBlockHeader() const
795 block.nVersion = nVersion;
797 block.hashPrevBlock = pprev->GetBlockHash();
798 block.hashMerkleRoot = hashMerkleRoot;
801 block.nNonce = nNonce;
805 uint256 GetBlockHash() const
810 int64_t GetBlockTime() const
812 return (int64_t)nTime;
815 CBigNum GetBlockWork() const
818 bnTarget.SetCompact(nBits);
821 return (CBigNum(1)<<256) / (bnTarget+1);
824 bool CheckIndex() const
826 return CheckProofOfWork(GetBlockHash(), nBits);
829 enum { nMedianTimeSpan=11 };
831 int64_t GetMedianTimePast() const
833 int64_t pmedian[nMedianTimeSpan];
834 int64_t* pbegin = &pmedian[nMedianTimeSpan];
835 int64_t* pend = &pmedian[nMedianTimeSpan];
837 const CBlockIndex* pindex = this;
838 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
839 *(--pbegin) = pindex->GetBlockTime();
841 std::sort(pbegin, pend);
842 return pbegin[(pend - pbegin)/2];
845 int64_t GetMedianTime() const;
848 * Returns true if there are nRequired or more blocks of minVersion or above
849 * in the last nToCheck blocks, starting at pstart and going backwards.
851 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
852 unsigned int nRequired, unsigned int nToCheck);
854 std::string ToString() const
856 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
858 hashMerkleRoot.ToString().c_str(),
859 GetBlockHash().ToString().c_str());
864 LogPrintf("%s\n", ToString().c_str());
870 /** Used to marshal pointers into hashes for db storage. */
871 class CDiskBlockIndex : public CBlockIndex
880 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
881 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
886 if (!(nType & SER_GETHASH))
887 READWRITE(VARINT(nVersion));
889 READWRITE(VARINT(nHeight));
890 READWRITE(VARINT(nStatus));
891 READWRITE(VARINT(nTx));
892 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
893 READWRITE(VARINT(nFile));
894 if (nStatus & BLOCK_HAVE_DATA)
895 READWRITE(VARINT(nDataPos));
896 if (nStatus & BLOCK_HAVE_UNDO)
897 READWRITE(VARINT(nUndoPos));
900 READWRITE(this->nVersion);
902 READWRITE(hashMerkleRoot);
908 uint256 GetBlockHash() const
911 block.nVersion = nVersion;
912 block.hashPrevBlock = hashPrev;
913 block.hashMerkleRoot = hashMerkleRoot;
916 block.nNonce = nNonce;
917 return block.GetHash();
921 std::string ToString() const
923 std::string str = "CDiskBlockIndex(";
924 str += CBlockIndex::ToString();
925 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
926 GetBlockHash().ToString().c_str(),
927 hashPrev.ToString().c_str());
933 LogPrintf("%s\n", ToString().c_str());
937 /** Capture information about block/transaction validation */
938 class CValidationState {
941 MODE_VALID, // everything ok
942 MODE_INVALID, // network rule violation (DoS value may be set)
943 MODE_ERROR, // run-time error
946 std::string strRejectReason;
947 unsigned char chRejectCode;
948 bool corruptionPossible;
950 CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
951 bool DoS(int level, bool ret = false,
952 unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
953 bool corruptionIn=false) {
954 chRejectCode = chRejectCodeIn;
955 strRejectReason = strRejectReasonIn;
956 corruptionPossible = corruptionIn;
957 if (mode == MODE_ERROR)
963 bool Invalid(bool ret = false,
964 unsigned char _chRejectCode=0, std::string _strRejectReason="") {
965 return DoS(0, ret, _chRejectCode, _strRejectReason);
967 bool Error(std::string strRejectReasonIn="") {
968 if (mode == MODE_VALID)
969 strRejectReason = strRejectReasonIn;
973 bool Abort(const std::string &msg) {
977 bool IsValid() const {
978 return mode == MODE_VALID;
980 bool IsInvalid() const {
981 return mode == MODE_INVALID;
983 bool IsError() const {
984 return mode == MODE_ERROR;
986 bool IsInvalid(int &nDoSOut) const {
993 bool CorruptionPossible() const {
994 return corruptionPossible;
996 unsigned char GetRejectCode() const { return chRejectCode; }
997 std::string GetRejectReason() const { return strRejectReason; }
1000 /** An in-memory indexed chain of blocks. */
1003 std::vector<CBlockIndex*> vChain;
1006 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
1007 CBlockIndex *Genesis() const {
1008 return vChain.size() > 0 ? vChain[0] : NULL;
1011 /** Returns the index entry for the tip of this chain, or NULL if none. */
1012 CBlockIndex *Tip() const {
1013 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
1016 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
1017 CBlockIndex *operator[](int nHeight) const {
1018 if (nHeight < 0 || nHeight >= (int)vChain.size())
1020 return vChain[nHeight];
1023 /** Compare two chains efficiently. */
1024 friend bool operator==(const CChain &a, const CChain &b) {
1025 return a.vChain.size() == b.vChain.size() &&
1026 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
1029 /** Efficiently check whether a block is present in this chain. */
1030 bool Contains(const CBlockIndex *pindex) const {
1031 return (*this)[pindex->nHeight] == pindex;
1034 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
1035 CBlockIndex *Next(const CBlockIndex *pindex) const {
1036 if (Contains(pindex))
1037 return (*this)[pindex->nHeight + 1];
1042 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
1043 int Height() const {
1044 return vChain.size() - 1;
1047 /** Set/initialize a chain with a given tip. Returns the forking point. */
1048 CBlockIndex *SetTip(CBlockIndex *pindex);
1050 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
1051 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
1053 /** Find the last common block between this chain and a locator. */
1054 CBlockIndex *FindFork(const CBlockLocator &locator) const;
1057 /** The currently-connected chain of blocks. */
1058 extern CChain chainActive;
1060 /** The currently best known chain of headers (some of which may be invalid). */
1061 extern CChain chainMostWork;
1063 /** Global variable that points to the active CCoinsView (protected by cs_main) */
1064 extern CCoinsViewCache *pcoinsTip;
1066 /** Global variable that points to the active block tree (protected by cs_main) */
1067 extern CBlockTreeDB *pblocktree;
1069 struct CBlockTemplate
1072 std::vector<int64_t> vTxFees;
1073 std::vector<int64_t> vTxSigOps;
1081 /** Used to relay blocks as header + vector<merkle branch>
1082 * to filtered nodes.
1087 // Public only for unit testing
1088 CBlockHeader header;
1089 CPartialMerkleTree txn;
1092 // Public only for unit testing and relay testing
1094 std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
1096 // Create from a CBlock, filtering transactions according to filter
1097 // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
1098 // thus the filter will likely be modified.
1099 CMerkleBlock(const CBlock& block, CBloomFilter& filter);
1109 class CWalletInterface {
1111 virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) =0;
1112 virtual void EraseFromWallet(const uint256 &hash) =0;
1113 virtual void SetBestChain(const CBlockLocator &locator) =0;
1114 virtual void UpdatedTransaction(const uint256 &hash) =0;
1115 virtual void Inventory(const uint256 &hash) =0;
1116 virtual void ResendWalletTransactions() =0;
1117 friend void ::RegisterWallet(CWalletInterface*);
1118 friend void ::UnregisterWallet(CWalletInterface*);
1119 friend void ::UnregisterAllWallets();