Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2014 The Bitcoin developers
0003 // Distributed under the MIT software license, see the accompanying
0004 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
0005 
0006 #ifndef BITCOIN_MAIN_H
0007 #define BITCOIN_MAIN_H
0008 
0009 #if defined(HAVE_CONFIG_H)
0010 #include "config/bitcoin-config.h"
0011 #endif
0012 
0013 #include "amount.h"
0014 #include "chain.h"
0015 #include "chainparams.h"
0016 #include "coins.h"
0017 #include "primitives/block.h"
0018 #include "primitives/transaction.h"
0019 #include "net.h"
0020 #include "pow.h"
0021 #include "script/script.h"
0022 #include "script/sigcache.h"
0023 #include "script/standard.h"
0024 #include "sync.h"
0025 #include "tinyformat.h"
0026 #include "txmempool.h"
0027 #include "uint256.h"
0028 #include "undo.h"
0029 
0030 #include <algorithm>
0031 #include <exception>
0032 #include <map>
0033 #include <set>
0034 #include <stdint.h>
0035 #include <string>
0036 #include <utility>
0037 #include <vector>
0038 
0039 #include <boost/unordered_map.hpp>
0040 
0041 class CBlockIndex;
0042 class CBlockTreeDB;
0043 class CBloomFilter;
0044 class CInv;
0045 class CScriptCheck;
0046 class CValidationInterface;
0047 class CValidationState;
0048 
0049 struct CBlockTemplate;
0050 struct CNodeStateStats;
0051 
0052 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
0053 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
0054 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
0055 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
0056 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
0057 /** The maximum size for transactions we're willing to relay/mine */
0058 static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
0059 /** The maximum allowed number of signature check operations in a block (network rule) */
0060 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
0061 /** Maximum number of signature check operations in an IsStandard() P2SH script */
0062 static const unsigned int MAX_P2SH_SIGOPS = 15;
0063 /** The maximum number of sigops we're willing to relay/mine in a single tx */
0064 static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
0065 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
0066 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
0067 /** The maximum size of a blk?????.dat file (since 0.8) */
0068 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
0069 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
0070 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
0071 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
0072 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
0073 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
0074 static const int COINBASE_MATURITY = 100;
0075 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
0076 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
0077 /** Maximum number of script-checking threads allowed */
0078 static const int MAX_SCRIPTCHECK_THREADS = 16;
0079 /** -par default (number of script-checking threads, 0 = auto) */
0080 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
0081 /** Number of blocks that can be requested at any given time from a single peer. */
0082 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
0083 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
0084 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
0085 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
0086  *  less than this number, we reached their tip. Changing this value is a protocol upgrade. */
0087 static const unsigned int MAX_HEADERS_RESULTS = 2000;
0088 /** Size of the "block download window": how far ahead of our current height do we fetch?
0089  *  Larger windows tolerate larger download speed differences between peer, but increase the potential
0090  *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
0091  *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
0092 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
0093 /** Time to wait (in seconds) between writing blockchain state to disk. */
0094 static const unsigned int DATABASE_WRITE_INTERVAL = 3600;
0095 /** Maximum length of reject messages. */
0096 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
0097 
0098 /** "reject" message codes */
0099 static const unsigned char REJECT_MALFORMED = 0x01;
0100 static const unsigned char REJECT_INVALID = 0x10;
0101 static const unsigned char REJECT_OBSOLETE = 0x11;
0102 static const unsigned char REJECT_DUPLICATE = 0x12;
0103 static const unsigned char REJECT_NONSTANDARD = 0x40;
0104 static const unsigned char REJECT_DUST = 0x41;
0105 static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
0106 static const unsigned char REJECT_CHECKPOINT = 0x43;
0107 
0108 struct BlockHasher
0109 {
0110     size_t operator()(const uint256& hash) const { return hash.GetLow64(); }
0111 };
0112 
0113 extern CScript COINBASE_FLAGS;
0114 extern CCriticalSection cs_main;
0115 extern CTxMemPool mempool;
0116 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
0117 extern BlockMap mapBlockIndex;
0118 extern uint64_t nLastBlockTx;
0119 extern uint64_t nLastBlockSize;
0120 extern const std::string strMessageMagic;
0121 extern int64_t nTimeBestReceived;
0122 extern CWaitableCriticalSection csBestBlock;
0123 extern CConditionVariable cvBlockChange;
0124 extern bool fImporting;
0125 extern bool fReindex;
0126 extern int nScriptCheckThreads;
0127 extern bool fTxIndex;
0128 extern bool fIsBareMultisigStd;
0129 extern unsigned int nCoinCacheSize;
0130 extern CFeeRate minRelayTxFee;
0131 
0132 /** Best header we've seen so far (used for getheaders queries' starting points). */
0133 extern CBlockIndex *pindexBestHeader;
0134 
0135 /** Minimum disk space required - used in CheckDiskSpace() */
0136 static const uint64_t nMinDiskSpace = 52428800;
0137 
0138 /** Register a wallet to receive updates from core */
0139 void RegisterValidationInterface(CValidationInterface* pwalletIn);
0140 /** Unregister a wallet from core */
0141 void UnregisterValidationInterface(CValidationInterface* pwalletIn);
0142 /** Unregister all wallets from core */
0143 void UnregisterAllValidationInterfaces();
0144 /** Push an updated transaction to all registered wallets */
0145 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
0146 
0147 /** Register with a network node to receive its signals */
0148 void RegisterNodeSignals(CNodeSignals& nodeSignals);
0149 /** Unregister a network node */
0150 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
0151 
0152 /** 
0153  * Process an incoming block. This only returns after the best known valid
0154  * block is made active. Note that it does not, however, guarantee that the
0155  * specific block passed to it has been checked for validity!
0156  * 
0157  * @param[out]  state   This may be set to an Error state if any error occurred processing it, including during validation/connection/etc of otherwise unrelated blocks during reorganisation; or it may be set to an Invalid state if pblock is itself invalid (but this is not guaranteed even when the block is checked). If you want to *possibly* get feedback on whether pblock is valid, you must also install a CValidationInterface - this will have its BlockChecked method called whenever *any* block completes validation.
0158  * @param[in]   pfrom   The node which we are receiving the block from; it is added to mapBlockSource and may be penalised if the block is invalid.
0159  * @param[in]   pblock  The block we want to process.
0160  * @param[out]  dbp     If pblock is stored to disk (or already there), this will be set to its location.
0161  * @return True if state.IsValid()
0162  */
0163 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
0164 /** Check whether enough disk space is available for an incoming block */
0165 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
0166 /** Open a block file (blk?????.dat) */
0167 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
0168 /** Open an undo file (rev?????.dat) */
0169 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
0170 /** Translation to a filesystem path */
0171 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
0172 /** Import blocks from an external file */
0173 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
0174 /** Initialize a new block tree database + block data on disk */
0175 bool InitBlockIndex();
0176 /** Load the block tree and coins database from disk */
0177 bool LoadBlockIndex();
0178 /** Unload database information */
0179 void UnloadBlockIndex();
0180 /** Process protocol messages received from a given node */
0181 bool ProcessMessages(CNode* pfrom);
0182 /** Send queued protocol messages to be sent to a give node */
0183 bool SendMessages(CNode* pto, bool fSendTrickle);
0184 /** Run an instance of the script checking thread */
0185 void ThreadScriptCheck();
0186 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
0187 bool IsInitialBlockDownload();
0188 /** Format a string that describes several potential problems detected by the core */
0189 std::string GetWarnings(std::string strFor);
0190 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
0191 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
0192 /** Find the best known block, and make it the tip of the block chain */
0193 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
0194 CAmount GetBlockValue(int nHeight, const CAmount& nFees);
0195 
0196 /** Create a new block index entry for a given block hash */
0197 CBlockIndex * InsertBlockIndex(uint256 hash);
0198 /** Abort with a message */
0199 bool AbortNode(const std::string &msg, const std::string &userMessage="");
0200 /** Get statistics from node state */
0201 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
0202 /** Increase a node's misbehavior score. */
0203 void Misbehaving(NodeId nodeid, int howmuch);
0204 /** Flush all state, indexes and buffers to disk. */
0205 void FlushStateToDisk();
0206 
0207 
0208 /** (try to) add transaction to memory pool **/
0209 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
0210                         bool* pfMissingInputs, bool fRejectInsaneFee=false);
0211 
0212 
0213 struct CNodeStateStats {
0214     int nMisbehavior;
0215     int nSyncHeight;
0216     int nCommonHeight;
0217     std::vector<int> vHeightInFlight;
0218 };
0219 
0220 struct CDiskTxPos : public CDiskBlockPos
0221 {
0222     unsigned int nTxOffset; // after header
0223 
0224     ADD_SERIALIZE_METHODS;
0225 
0226     template <typename Stream, typename Operation>
0227     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
0228         READWRITE(*(CDiskBlockPos*)this);
0229         READWRITE(VARINT(nTxOffset));
0230     }
0231 
0232     CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
0233     }
0234 
0235     CDiskTxPos() {
0236         SetNull();
0237     }
0238 
0239     void SetNull() {
0240         CDiskBlockPos::SetNull();
0241         nTxOffset = 0;
0242     }
0243 };
0244 
0245 
0246 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
0247 
0248 /**
0249  * Check transaction inputs, and make sure any
0250  * pay-to-script-hash transactions are evaluating IsStandard scripts
0251  * 
0252  * Why bother? To avoid denial-of-service attacks; an attacker
0253  * can submit a standard HASH... OP_EQUAL transaction,
0254  * which will get accepted into blocks. The redemption
0255  * script can be anything; an attacker could use a very
0256  * expensive-to-check-upon-redemption script like:
0257  *   DUP CHECKSIG DROP ... repeated 100 times... OP_1
0258  */
0259 
0260 /** 
0261  * Check for standard transaction types
0262  * @param[in] mapInputs    Map of previous transactions that have outputs we're spending
0263  * @return True if all inputs (scriptSigs) use only standard transaction forms
0264  */
0265 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
0266 
0267 /** 
0268  * Count ECDSA signature operations the old-fashioned (pre-0.6) way
0269  * @return number of sigops this transaction's outputs will produce when spent
0270  * @see CTransaction::FetchInputs
0271  */
0272 unsigned int GetLegacySigOpCount(const CTransaction& tx);
0273 
0274 /**
0275  * Count ECDSA signature operations in pay-to-script-hash inputs.
0276  * 
0277  * @param[in] mapInputs Map of previous transactions that have outputs we're spending
0278  * @return maximum number of sigops required to validate this transaction's inputs
0279  * @see CTransaction::FetchInputs
0280  */
0281 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
0282 
0283 
0284 /**
0285  * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
0286  * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
0287  * instead of being performed inline.
0288  */
0289 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
0290                  unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks = NULL);
0291 
0292 /** Apply the effects of this transaction on the UTXO set represented by view */
0293 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight);
0294 
0295 /** Context-independent validity checks */
0296 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
0297 
0298 /** Check for standard transaction types
0299  * @return True if all outputs (scriptPubKeys) use only standard transaction forms
0300  */
0301 bool IsStandardTx(const CTransaction& tx, std::string& reason);
0302 
0303 bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
0304 
0305 /** Undo information for a CBlock */
0306 class CBlockUndo
0307 {
0308 public:
0309     std::vector<CTxUndo> vtxundo; // for all but the coinbase
0310 
0311     ADD_SERIALIZE_METHODS;
0312 
0313     template <typename Stream, typename Operation>
0314     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
0315         READWRITE(vtxundo);
0316     }
0317 
0318     bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock);
0319     bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock);
0320 };
0321 
0322 
0323 /** 
0324  * Closure representing one script verification
0325  * Note that this stores references to the spending transaction 
0326  */
0327 class CScriptCheck
0328 {
0329 private:
0330     CScript scriptPubKey;
0331     const CTransaction *ptxTo;
0332     unsigned int nIn;
0333     unsigned int nFlags;
0334     bool cacheStore;
0335     ScriptError error;
0336 
0337 public:
0338     CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
0339     CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
0340         scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
0341         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { }
0342 
0343     bool operator()();
0344 
0345     void swap(CScriptCheck &check) {
0346         scriptPubKey.swap(check.scriptPubKey);
0347         std::swap(ptxTo, check.ptxTo);
0348         std::swap(nIn, check.nIn);
0349         std::swap(nFlags, check.nFlags);
0350         std::swap(cacheStore, check.cacheStore);
0351         std::swap(error, check.error);
0352     }
0353 
0354     ScriptError GetScriptError() const { return error; }
0355 };
0356 
0357 
0358 /** Functions for disk access for blocks */
0359 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
0360 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
0361 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
0362 
0363 
0364 /** Functions for validating blocks and updating the block tree */
0365 
0366 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
0367  *  In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
0368  *  will be true if no problems were found. Otherwise, the return value will be false in case
0369  *  of problems. Note that in any case, coins may be modified. */
0370 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
0371 
0372 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
0373 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
0374 
0375 /** Context-independent validity checks */
0376 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
0377 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
0378 
0379 /** Context-dependent validity checks */
0380 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
0381 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
0382 
0383 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
0384 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
0385 
0386 /** Store block on disk. If dbp is provided, the file is known to already reside on disk */
0387 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL);
0388 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
0389 
0390 
0391 
0392 class CBlockFileInfo
0393 {
0394 public:
0395     unsigned int nBlocks;      //! number of blocks stored in file
0396     unsigned int nSize;        //! number of used bytes of block file
0397     unsigned int nUndoSize;    //! number of used bytes in the undo file
0398     unsigned int nHeightFirst; //! lowest height of block in file
0399     unsigned int nHeightLast;  //! highest height of block in file
0400     uint64_t nTimeFirst;         //! earliest time of block in file
0401     uint64_t nTimeLast;          //! latest time of block in file
0402 
0403     ADD_SERIALIZE_METHODS;
0404 
0405     template <typename Stream, typename Operation>
0406     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
0407         READWRITE(VARINT(nBlocks));
0408         READWRITE(VARINT(nSize));
0409         READWRITE(VARINT(nUndoSize));
0410         READWRITE(VARINT(nHeightFirst));
0411         READWRITE(VARINT(nHeightLast));
0412         READWRITE(VARINT(nTimeFirst));
0413         READWRITE(VARINT(nTimeLast));
0414     }
0415 
0416      void SetNull() {
0417          nBlocks = 0;
0418          nSize = 0;
0419          nUndoSize = 0;
0420          nHeightFirst = 0;
0421          nHeightLast = 0;
0422          nTimeFirst = 0;
0423          nTimeLast = 0;
0424      }
0425 
0426      CBlockFileInfo() {
0427          SetNull();
0428      }
0429 
0430      std::string ToString() const;
0431 
0432      /** update statistics (does not update nSize) */
0433      void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
0434          if (nBlocks==0 || nHeightFirst > nHeightIn)
0435              nHeightFirst = nHeightIn;
0436          if (nBlocks==0 || nTimeFirst > nTimeIn)
0437              nTimeFirst = nTimeIn;
0438          nBlocks++;
0439          if (nHeightIn > nHeightLast)
0440              nHeightLast = nHeightIn;
0441          if (nTimeIn > nTimeLast)
0442              nTimeLast = nTimeIn;
0443      }
0444 };
0445 
0446 /** Capture information about block/transaction validation */
0447 class CValidationState {
0448 private:
0449     enum mode_state {
0450         MODE_VALID,   //! everything ok
0451         MODE_INVALID, //! network rule violation (DoS value may be set)
0452         MODE_ERROR,   //! run-time error
0453     } mode;
0454     int nDoS;
0455     std::string strRejectReason;
0456     unsigned char chRejectCode;
0457     bool corruptionPossible;
0458 public:
0459     CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
0460     bool DoS(int level, bool ret = false,
0461              unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
0462              bool corruptionIn=false) {
0463         chRejectCode = chRejectCodeIn;
0464         strRejectReason = strRejectReasonIn;
0465         corruptionPossible = corruptionIn;
0466         if (mode == MODE_ERROR)
0467             return ret;
0468         nDoS += level;
0469         mode = MODE_INVALID;
0470         return ret;
0471     }
0472     bool Invalid(bool ret = false,
0473                  unsigned char _chRejectCode=0, std::string _strRejectReason="") {
0474         return DoS(0, ret, _chRejectCode, _strRejectReason);
0475     }
0476     bool Error(std::string strRejectReasonIn="") {
0477         if (mode == MODE_VALID)
0478             strRejectReason = strRejectReasonIn;
0479         mode = MODE_ERROR;
0480         return false;
0481     }
0482     bool Abort(const std::string &msg) {
0483         AbortNode(msg);
0484         return Error(msg);
0485     }
0486     bool IsValid() const {
0487         return mode == MODE_VALID;
0488     }
0489     bool IsInvalid() const {
0490         return mode == MODE_INVALID;
0491     }
0492     bool IsError() const {
0493         return mode == MODE_ERROR;
0494     }
0495     bool IsInvalid(int &nDoSOut) const {
0496         if (IsInvalid()) {
0497             nDoSOut = nDoS;
0498             return true;
0499         }
0500         return false;
0501     }
0502     bool CorruptionPossible() const {
0503         return corruptionPossible;
0504     }
0505     unsigned char GetRejectCode() const { return chRejectCode; }
0506     std::string GetRejectReason() const { return strRejectReason; }
0507 };
0508 
0509 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
0510 class CVerifyDB {
0511 public:
0512     CVerifyDB();
0513     ~CVerifyDB();
0514     bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
0515 };
0516 
0517 /** Find the last common block between the parameter chain and a locator. */
0518 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
0519 
0520 /** Mark a block as invalid. */
0521 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
0522 
0523 /** Remove invalidity status from a block and its descendants. */
0524 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
0525 
0526 /** The currently-connected chain of blocks. */
0527 extern CChain chainActive;
0528 
0529 /** Global variable that points to the active CCoinsView (protected by cs_main) */
0530 extern CCoinsViewCache *pcoinsTip;
0531 
0532 /** Global variable that points to the active block tree (protected by cs_main) */
0533 extern CBlockTreeDB *pblocktree;
0534 
0535 struct CBlockTemplate
0536 {
0537     CBlock block;
0538     std::vector<CAmount> vTxFees;
0539     std::vector<int64_t> vTxSigOps;
0540 };
0541 
0542 
0543 
0544 
0545 
0546 
0547 class CValidationInterface {
0548 protected:
0549     virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) {};
0550     virtual void EraseFromWallet(const uint256 &hash) {};
0551     virtual void SetBestChain(const CBlockLocator &locator) {};
0552     virtual void UpdatedTransaction(const uint256 &hash) {};
0553     virtual void Inventory(const uint256 &hash) {};
0554     virtual void ResendWalletTransactions() {};
0555     virtual void BlockChecked(const CBlock&, const CValidationState&) {};
0556     friend void ::RegisterValidationInterface(CValidationInterface*);
0557     friend void ::UnregisterValidationInterface(CValidationInterface*);
0558     friend void ::UnregisterAllValidationInterfaces();
0559 };
0560 
0561 #endif // BITCOIN_MAIN_H