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 "config/bitcoin-config.h"
13 #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 /** Maxiumum number of signature check operations in an IsStandard() P2SH script */
48 static const unsigned int MAX_P2SH_SIGOPS = 15;
49 /** The maximum number of sigops we're willing to relay/mine in a single tx */
50 static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
51 /** The maximum number of orphan transactions kept in memory */
52 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
53 /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */
54 static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
55 /** The maximum size of a blk?????.dat file (since 0.8) */
56 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
57 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
58 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
59 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
60 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
61 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
62 static const int COINBASE_MATURITY = 100;
63 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
64 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
65 /** Maximum number of script-checking threads allowed */
66 static const int MAX_SCRIPTCHECK_THREADS = 16;
67 /** -par default (number of script-checking threads, 0 = auto) */
68 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
69 /** Number of blocks that can be requested at any given time from a single peer. */
70 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
71 /** Timeout in seconds before considering a block download peer unresponsive. */
72 static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
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 CWaitableCriticalSection csBestBlock;
94 extern CConditionVariable cvBlockChange;
95 extern bool fImporting;
97 extern int nScriptCheckThreads;
99 extern bool fIsBareMultisigStd;
100 extern unsigned int nCoinCacheSize;
101 extern CFeeRate minRelayTxFee;
103 // Minimum disk space required - used in CheckDiskSpace()
104 static const uint64_t nMinDiskSpace = 52428800;
108 struct CDiskBlockPos;
111 class CValidationState;
112 class CWalletInterface;
113 struct CNodeStateStats;
115 struct CBlockTemplate;
117 /** Register a wallet to receive updates from core */
118 void RegisterWallet(CWalletInterface* pwalletIn);
119 /** Unregister a wallet from core */
120 void UnregisterWallet(CWalletInterface* pwalletIn);
121 /** Unregister all wallets from core */
122 void UnregisterAllWallets();
123 /** Push an updated transaction to all registered wallets */
124 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
126 /** Register with a network node to receive its signals */
127 void RegisterNodeSignals(CNodeSignals& nodeSignals);
128 /** Unregister a network node */
129 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
131 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
133 /** Process an incoming block */
134 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
135 /** Check whether enough disk space is available for an incoming block */
136 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
137 /** Open a block file (blk?????.dat) */
138 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
139 /** Open an undo file (rev?????.dat) */
140 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
141 /** Import blocks from an external file */
142 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
143 /** Initialize a new block tree database + block data on disk */
144 bool InitBlockIndex();
145 /** Load the block tree and coins database from disk */
146 bool LoadBlockIndex();
147 /** Unload database information */
148 void UnloadBlockIndex();
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 we are doing an initial block download (synchronizing from disk or network) */
158 bool IsInitialBlockDownload();
159 /** Format a string that describes several potential problems detected by the core */
160 std::string GetWarnings(std::string strFor);
161 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
162 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
163 /** Find the best known block, and make it the tip of the block chain */
164 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
165 int64_t GetBlockValue(int nHeight, int64_t nFees);
167 /** Create a new block index entry for a given block hash */
168 CBlockIndex * InsertBlockIndex(uint256 hash);
169 /** Verify a signature */
170 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
171 /** Abort with a message */
172 bool AbortNode(const std::string &msg);
173 /** Get statistics from node state */
174 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
175 /** Increase a node's misbehavior score. */
176 void Misbehaving(NodeId nodeid, int howmuch);
179 /** (try to) add transaction to memory pool **/
180 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
181 bool* pfMissingInputs, bool fRejectInsaneFee=false);
190 struct CNodeStateStats {
200 ADD_SERIALIZE_METHODS;
202 template <typename Stream, typename Operation>
203 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
204 READWRITE(VARINT(nFile));
205 READWRITE(VARINT(nPos));
212 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
217 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
218 return (a.nFile == b.nFile && a.nPos == b.nPos);
221 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
225 void SetNull() { nFile = -1; nPos = 0; }
226 bool IsNull() const { return (nFile == -1); }
229 struct CDiskTxPos : public CDiskBlockPos
231 unsigned int nTxOffset; // after header
233 ADD_SERIALIZE_METHODS;
235 template <typename Stream, typename Operation>
236 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
237 READWRITE(*(CDiskBlockPos*)this);
238 READWRITE(VARINT(nTxOffset));
241 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
249 CDiskBlockPos::SetNull();
255 int64_t GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
258 // Check transaction inputs, and make sure any
259 // pay-to-script-hash transactions are evaluating IsStandard scripts
261 // Why bother? To avoid denial-of-service attacks; an attacker
262 // can submit a standard HASH... OP_EQUAL transaction,
263 // which will get accepted into blocks. The redemption
264 // script can be anything; an attacker could use a very
265 // expensive-to-check-upon-redemption script like:
266 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
269 /** Check for standard transaction types
270 @param[in] mapInputs Map of previous transactions that have outputs we're spending
271 @return True if all inputs (scriptSigs) use only standard transaction forms
273 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
275 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
276 @return number of sigops this transaction's outputs will produce when spent
277 @see CTransaction::FetchInputs
279 unsigned int GetLegacySigOpCount(const CTransaction& tx);
281 /** Count ECDSA signature operations in pay-to-script-hash inputs.
283 @param[in] mapInputs Map of previous transactions that have outputs we're spending
284 @return maximum number of sigops required to validate this transaction's inputs
285 @see CTransaction::FetchInputs
287 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
290 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
291 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
292 // instead of being performed inline.
293 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks = true,
294 unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS,
295 std::vector<CScriptCheck> *pvChecks = NULL);
297 // Apply the effects of this transaction on the UTXO set represented by view
298 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight);
300 // Context-independent validity checks
301 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
303 /** Check for standard transaction types
304 @return True if all outputs (scriptPubKeys) use only standard transaction forms
306 bool IsStandardTx(const CTransaction& tx, std::string& reason);
308 bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
310 /** Undo information for a CBlock */
314 std::vector<CTxUndo> vtxundo; // for all but the coinbase
316 ADD_SERIALIZE_METHODS;
318 template <typename Stream, typename Operation>
319 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
323 bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock);
324 bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock);
328 /** Closure representing one script verification
329 * Note that this stores references to the spending transaction */
333 CScript scriptPubKey;
334 const CTransaction *ptxTo;
340 CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), nHashType(0) {}
341 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
342 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
343 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
345 bool operator()() const;
347 void swap(CScriptCheck &check) {
348 scriptPubKey.swap(check.scriptPubKey);
349 std::swap(ptxTo, check.ptxTo);
350 std::swap(nIn, check.nIn);
351 std::swap(nFlags, check.nFlags);
352 std::swap(nHashType, check.nHashType);
356 /** Data structure that represents a partial merkle tree.
358 * It respresents a subset of the txid's of a known block, in a way that
359 * allows recovery of the list of txid's and the merkle root, in an
362 * The encoding works as follows: we traverse the tree in depth-first order,
363 * storing a bit for each traversed node, signifying whether the node is the
364 * parent of at least one matched leaf txid (or a matched txid itself). In
365 * case we are at the leaf level, or this bit is 0, its merkle node hash is
366 * stored, and its children are not explorer further. Otherwise, no hash is
367 * stored, but we recurse into both (or the only) child branch. During
368 * decoding, the same depth-first traversal is performed, consuming bits and
369 * hashes as they written during encoding.
371 * The serialization is fixed and provides a hard guarantee about the
374 * SIZE <= 10 + ceil(32.25*N)
376 * Where N represents the number of leaf nodes of the partial tree. N itself
379 * N <= total_transactions
380 * N <= 1 + matched_transactions*tree_height
382 * The serialization format:
383 * - uint32 total_transactions (4 bytes)
384 * - varint number of hashes (1-3 bytes)
385 * - uint256[] hashes in depth-first order (<= 32*N bytes)
386 * - varint number of bytes of flag bits (1-3 bytes)
387 * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
388 * The size constraints follow from this.
390 class CPartialMerkleTree
393 // the total number of transactions in the block
394 unsigned int nTransactions;
396 // node-is-parent-of-matched-txid bits
397 std::vector<bool> vBits;
399 // txids and internal hashes
400 std::vector<uint256> vHash;
402 // flag set when encountering invalid data
405 // helper function to efficiently calculate the number of nodes at given height in the merkle tree
406 unsigned int CalcTreeWidth(int height) {
407 return (nTransactions+(1 << height)-1) >> height;
410 // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
411 uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
413 // recursive function that traverses tree nodes, storing the data as bits and hashes
414 void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
416 // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
417 // it returns the hash of the respective node.
418 uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
422 // serialization implementation
423 ADD_SERIALIZE_METHODS;
425 template <typename Stream, typename Operation>
426 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
427 READWRITE(nTransactions);
429 std::vector<unsigned char> vBytes;
430 if (ser_action.ForRead()) {
432 CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
433 us.vBits.resize(vBytes.size() * 8);
434 for (unsigned int p = 0; p < us.vBits.size(); p++)
435 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
438 vBytes.resize((vBits.size()+7)/8);
439 for (unsigned int p = 0; p < vBits.size(); p++)
440 vBytes[p / 8] |= vBits[p] << (p % 8);
445 // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
446 CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
448 CPartialMerkleTree();
450 // extract the matching txid's represented by this partial merkle tree.
451 // returns the merkle root, or 0 in case of failure
452 uint256 ExtractMatches(std::vector<uint256> &vMatch);
457 /** Functions for disk access for blocks */
458 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
459 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
460 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
463 /** Functions for validating blocks and updating the block tree */
465 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
466 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
467 * will be true if no problems were found. Otherwise, the return value will be false in case
468 * of problems. Note that in any case, coins may be modified. */
469 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
471 // Apply the effects of this block (with given index) on the UTXO set represented by coins
472 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
474 // Add this block to the block index, and if necessary, switch the active block chain to this
475 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
477 // Context-independent validity checks
478 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
479 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
481 // Store block on disk
482 // if dbp is provided, the file is known to already reside on disk
483 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL);
484 bool AcceptBlockHeader(CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
491 unsigned int nBlocks; // number of blocks stored in file
492 unsigned int nSize; // number of used bytes of block file
493 unsigned int nUndoSize; // number of used bytes in the undo file
494 unsigned int nHeightFirst; // lowest height of block in file
495 unsigned int nHeightLast; // highest height of block in file
496 uint64_t nTimeFirst; // earliest time of block in file
497 uint64_t nTimeLast; // latest time of block in file
499 ADD_SERIALIZE_METHODS;
501 template <typename Stream, typename Operation>
502 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
503 READWRITE(VARINT(nBlocks));
504 READWRITE(VARINT(nSize));
505 READWRITE(VARINT(nUndoSize));
506 READWRITE(VARINT(nHeightFirst));
507 READWRITE(VARINT(nHeightLast));
508 READWRITE(VARINT(nTimeFirst));
509 READWRITE(VARINT(nTimeLast));
526 std::string ToString() const;
528 // update statistics (does not update nSize)
529 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
530 if (nBlocks==0 || nHeightFirst > nHeightIn)
531 nHeightFirst = nHeightIn;
532 if (nBlocks==0 || nTimeFirst > nTimeIn)
533 nTimeFirst = nTimeIn;
535 if (nHeightIn > nHeightLast)
536 nHeightLast = nHeightIn;
537 if (nTimeIn > nTimeLast)
543 BLOCK_VALID_UNKNOWN = 0,
544 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
545 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
546 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
547 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
548 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
549 BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
550 BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
552 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
553 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
554 BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
556 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
557 BLOCK_FAILED_CHILD = 64, // descends from failed block
558 BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
561 /** The block chain is a tree shaped structure starting with the
562 * genesis block at the root, with each block potentially having multiple
563 * candidates to be the next block. A blockindex may have multiple pprev pointing
564 * to it, but at most one of them can be part of the currently active branch.
569 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
570 const uint256* phashBlock;
572 // pointer to the index of the predecessor of this block
575 // pointer to the index of some further predecessor of this block
578 // height of the entry in the chain. The genesis block has height 0
581 // Which # file this block is stored in (blk?????.dat)
584 // Byte offset within blk?????.dat where this block's data is stored
585 unsigned int nDataPos;
587 // Byte offset within rev?????.dat where this block's undo data is stored
588 unsigned int nUndoPos;
590 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
593 // Number of transactions in this block.
594 // Note: in a potential headers-first mode, this number cannot be relied upon
597 // (memory only) Number of transactions in the chain up to and including this block
598 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
600 // Verification status of this block. See enum BlockStatus
601 unsigned int nStatus;
605 uint256 hashMerkleRoot;
610 // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
611 uint32_t nSequenceId;
640 CBlockIndex(CBlockHeader& block)
644 nVersion = block.nVersion;
645 hashMerkleRoot = block.hashMerkleRoot;
648 nNonce = block.nNonce;
651 CDiskBlockPos GetBlockPos() const {
653 if (nStatus & BLOCK_HAVE_DATA) {
660 CDiskBlockPos GetUndoPos() const {
662 if (nStatus & BLOCK_HAVE_UNDO) {
669 CBlockHeader GetBlockHeader() const
672 block.nVersion = nVersion;
674 block.hashPrevBlock = pprev->GetBlockHash();
675 block.hashMerkleRoot = hashMerkleRoot;
678 block.nNonce = nNonce;
682 uint256 GetBlockHash() const
687 int64_t GetBlockTime() const
689 return (int64_t)nTime;
692 uint256 GetBlockWork() const
694 return GetProofIncrement(nBits);
697 enum { nMedianTimeSpan=11 };
699 int64_t GetMedianTimePast() const
701 int64_t pmedian[nMedianTimeSpan];
702 int64_t* pbegin = &pmedian[nMedianTimeSpan];
703 int64_t* pend = &pmedian[nMedianTimeSpan];
705 const CBlockIndex* pindex = this;
706 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
707 *(--pbegin) = pindex->GetBlockTime();
709 std::sort(pbegin, pend);
710 return pbegin[(pend - pbegin)/2];
714 * Returns true if there are nRequired or more blocks of minVersion or above
715 * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
716 * and going backwards.
718 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
719 unsigned int nRequired);
721 std::string ToString() const
723 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
725 hashMerkleRoot.ToString(),
726 GetBlockHash().ToString());
729 // Check whether this block index entry is valid up to the passed validity level.
730 bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
732 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
733 if (nStatus & BLOCK_FAILED_MASK)
735 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
738 // Raise the validity level of this block index entry.
739 // Returns true if the validity was changed.
740 bool RaiseValidity(enum BlockStatus nUpTo)
742 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
743 if (nStatus & BLOCK_FAILED_MASK)
745 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
746 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
752 // Build the skiplist pointer for this entry.
755 // Efficiently find an ancestor of this block.
756 CBlockIndex* GetAncestor(int height);
757 const CBlockIndex* GetAncestor(int height) const;
760 /** Used to marshal pointers into hashes for db storage. */
761 class CDiskBlockIndex : public CBlockIndex
770 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
771 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
774 ADD_SERIALIZE_METHODS;
776 template <typename Stream, typename Operation>
777 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
778 if (!(nType & SER_GETHASH))
779 READWRITE(VARINT(nVersion));
781 READWRITE(VARINT(nHeight));
782 READWRITE(VARINT(nStatus));
783 READWRITE(VARINT(nTx));
784 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
785 READWRITE(VARINT(nFile));
786 if (nStatus & BLOCK_HAVE_DATA)
787 READWRITE(VARINT(nDataPos));
788 if (nStatus & BLOCK_HAVE_UNDO)
789 READWRITE(VARINT(nUndoPos));
792 READWRITE(this->nVersion);
794 READWRITE(hashMerkleRoot);
800 uint256 GetBlockHash() const
803 block.nVersion = nVersion;
804 block.hashPrevBlock = hashPrev;
805 block.hashMerkleRoot = hashMerkleRoot;
808 block.nNonce = nNonce;
809 return block.GetHash();
813 std::string ToString() const
815 std::string str = "CDiskBlockIndex(";
816 str += CBlockIndex::ToString();
817 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
818 GetBlockHash().ToString(),
819 hashPrev.ToString());
824 /** Capture information about block/transaction validation */
825 class CValidationState {
828 MODE_VALID, // everything ok
829 MODE_INVALID, // network rule violation (DoS value may be set)
830 MODE_ERROR, // run-time error
833 std::string strRejectReason;
834 unsigned char chRejectCode;
835 bool corruptionPossible;
837 CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
838 bool DoS(int level, bool ret = false,
839 unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
840 bool corruptionIn=false) {
841 chRejectCode = chRejectCodeIn;
842 strRejectReason = strRejectReasonIn;
843 corruptionPossible = corruptionIn;
844 if (mode == MODE_ERROR)
850 bool Invalid(bool ret = false,
851 unsigned char _chRejectCode=0, std::string _strRejectReason="") {
852 return DoS(0, ret, _chRejectCode, _strRejectReason);
854 bool Error(std::string strRejectReasonIn="") {
855 if (mode == MODE_VALID)
856 strRejectReason = strRejectReasonIn;
860 bool Abort(const std::string &msg) {
864 bool IsValid() const {
865 return mode == MODE_VALID;
867 bool IsInvalid() const {
868 return mode == MODE_INVALID;
870 bool IsError() const {
871 return mode == MODE_ERROR;
873 bool IsInvalid(int &nDoSOut) const {
880 bool CorruptionPossible() const {
881 return corruptionPossible;
883 unsigned char GetRejectCode() const { return chRejectCode; }
884 std::string GetRejectReason() const { return strRejectReason; }
887 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
892 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
895 /** An in-memory indexed chain of blocks. */
898 std::vector<CBlockIndex*> vChain;
901 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
902 CBlockIndex *Genesis() const {
903 return vChain.size() > 0 ? vChain[0] : NULL;
906 /** Returns the index entry for the tip of this chain, or NULL if none. */
907 CBlockIndex *Tip() const {
908 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
911 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
912 CBlockIndex *operator[](int nHeight) const {
913 if (nHeight < 0 || nHeight >= (int)vChain.size())
915 return vChain[nHeight];
918 /** Compare two chains efficiently. */
919 friend bool operator==(const CChain &a, const CChain &b) {
920 return a.vChain.size() == b.vChain.size() &&
921 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
924 /** Efficiently check whether a block is present in this chain. */
925 bool Contains(const CBlockIndex *pindex) const {
926 return (*this)[pindex->nHeight] == pindex;
929 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
930 CBlockIndex *Next(const CBlockIndex *pindex) const {
931 if (Contains(pindex))
932 return (*this)[pindex->nHeight + 1];
937 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
939 return vChain.size() - 1;
942 /** Set/initialize a chain with a given tip. Returns the forking point. */
943 CBlockIndex *SetTip(CBlockIndex *pindex);
945 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
946 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
948 /** Find the last common block between this chain and a locator. */
949 CBlockIndex *FindFork(const CBlockLocator &locator) const;
951 /** Find the last common block between this chain and a block index entry. */
952 const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
955 /** The currently-connected chain of blocks. */
956 extern CChain chainActive;
958 /** Global variable that points to the active CCoinsView (protected by cs_main) */
959 extern CCoinsViewCache *pcoinsTip;
961 /** Global variable that points to the active block tree (protected by cs_main) */
962 extern CBlockTreeDB *pblocktree;
964 struct CBlockTemplate
967 std::vector<int64_t> vTxFees;
968 std::vector<int64_t> vTxSigOps;
976 /** Used to relay blocks as header + vector<merkle branch>
982 // Public only for unit testing
984 CPartialMerkleTree txn;
987 // Public only for unit testing and relay testing
989 std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
991 // Create from a CBlock, filtering transactions according to filter
992 // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
993 // thus the filter will likely be modified.
994 CMerkleBlock(const CBlock& block, CBloomFilter& filter);
996 ADD_SERIALIZE_METHODS;
998 template <typename Stream, typename Operation>
999 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1006 class CWalletInterface {
1008 virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) =0;
1009 virtual void EraseFromWallet(const uint256 &hash) =0;
1010 virtual void SetBestChain(const CBlockLocator &locator) =0;
1011 virtual void UpdatedTransaction(const uint256 &hash) =0;
1012 virtual void Inventory(const uint256 &hash) =0;
1013 virtual void ResendWalletTransactions() =0;
1014 friend void ::RegisterWallet(CWalletInterface*);
1015 friend void ::UnregisterWallet(CWalletInterface*);
1016 friend void ::UnregisterAllWallets();
1019 #endif // BITCOIN_MAIN_H