You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.h 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_MAIN_H
  6. #define BITCOIN_MAIN_H
  7. #if defined(HAVE_CONFIG_H)
  8. #include "config/bitcoin-config.h"
  9. #endif
  10. #include "amount.h"
  11. #include "chain.h"
  12. #include "chainparams.h"
  13. #include "coins.h"
  14. #include "consensus/consensus.h"
  15. #include "net.h"
  16. #include "primitives/block.h"
  17. #include "primitives/transaction.h"
  18. #include "script/script.h"
  19. #include "script/sigcache.h"
  20. #include "script/standard.h"
  21. #include "sync.h"
  22. #include "tinyformat.h"
  23. #include "txmempool.h"
  24. #include "uint256.h"
  25. #include <algorithm>
  26. #include <exception>
  27. #include <map>
  28. #include <set>
  29. #include <stdint.h>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. #include <boost/unordered_map.hpp>
  34. class CBlockIndex;
  35. class CBlockTreeDB;
  36. class CBloomFilter;
  37. class CInv;
  38. class CScriptCheck;
  39. class CValidationInterface;
  40. class CValidationState;
  41. struct CNodeStateStats;
  42. /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
  43. static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
  44. static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
  45. /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
  46. static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
  47. /** The maximum size for transactions we're willing to relay/mine */
  48. static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
  49. /** Maximum number of signature check operations in an IsStandard() P2SH script */
  50. static const unsigned int MAX_P2SH_SIGOPS = 15;
  51. /** The maximum number of sigops we're willing to relay/mine in a single tx */
  52. static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
  53. /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
  54. static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
  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. /** Maximum number of script-checking threads allowed */
  62. static const int MAX_SCRIPTCHECK_THREADS = 16;
  63. /** -par default (number of script-checking threads, 0 = auto) */
  64. static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
  65. /** Number of blocks that can be requested at any given time from a single peer. */
  66. static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
  67. /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
  68. static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
  69. /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
  70. * less than this number, we reached its tip. Changing this value is a protocol upgrade. */
  71. static const unsigned int MAX_HEADERS_RESULTS = 2000;
  72. /** Size of the "block download window": how far ahead of our current height do we fetch?
  73. * Larger windows tolerate larger download speed differences between peer, but increase the potential
  74. * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
  75. * harder). We'll probably want to make this a per-peer adaptive value at some point. */
  76. static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
  77. /** Time to wait (in seconds) between writing blocks/block index to disk. */
  78. static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
  79. /** Time to wait (in seconds) between flushing chainstate to disk. */
  80. static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
  81. /** Maximum length of reject messages. */
  82. static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
  83. /** "reject" message codes */
  84. static const unsigned char REJECT_MALFORMED = 0x01;
  85. static const unsigned char REJECT_INVALID = 0x10;
  86. static const unsigned char REJECT_OBSOLETE = 0x11;
  87. static const unsigned char REJECT_DUPLICATE = 0x12;
  88. static const unsigned char REJECT_NONSTANDARD = 0x40;
  89. static const unsigned char REJECT_DUST = 0x41;
  90. static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
  91. static const unsigned char REJECT_CHECKPOINT = 0x43;
  92. struct BlockHasher
  93. {
  94. size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
  95. };
  96. extern CScript COINBASE_FLAGS;
  97. extern CCriticalSection cs_main;
  98. extern CTxMemPool mempool;
  99. typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
  100. extern BlockMap mapBlockIndex;
  101. extern uint64_t nLastBlockTx;
  102. extern uint64_t nLastBlockSize;
  103. extern const std::string strMessageMagic;
  104. extern CWaitableCriticalSection csBestBlock;
  105. extern CConditionVariable cvBlockChange;
  106. extern bool fImporting;
  107. extern bool fReindex;
  108. extern int nScriptCheckThreads;
  109. extern bool fTxIndex;
  110. extern bool fIsBareMultisigStd;
  111. extern bool fCheckBlockIndex;
  112. extern bool fCheckpointsEnabled;
  113. extern size_t nCoinCacheUsage;
  114. extern CFeeRate minRelayTxFee;
  115. /** Best header we've seen so far (used for getheaders queries' starting points). */
  116. extern CBlockIndex *pindexBestHeader;
  117. /** Minimum disk space required - used in CheckDiskSpace() */
  118. static const uint64_t nMinDiskSpace = 52428800;
  119. /** Pruning-related variables and constants */
  120. /** True if any block files have ever been pruned. */
  121. extern bool fHavePruned;
  122. /** True if we're running in -prune mode. */
  123. extern bool fPruneMode;
  124. /** Number of MiB of block files that we're trying to stay below. */
  125. extern uint64_t nPruneTarget;
  126. /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
  127. static const signed int MIN_BLOCKS_TO_KEEP = 288;
  128. // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
  129. // At 1MB per block, 288 blocks = 288MB.
  130. // Add 15% for Undo data = 331MB
  131. // Add 20% for Orphan block rate = 397MB
  132. // We want the low water mark after pruning to be at least 397 MB and since we prune in
  133. // full block file chunks, we need the high water mark which triggers the prune to be
  134. // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
  135. // Setting the target to > than 550MB will make it likely we can respect the target.
  136. static const signed int MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
  137. /** Register with a network node to receive its signals */
  138. void RegisterNodeSignals(CNodeSignals& nodeSignals);
  139. /** Unregister a network node */
  140. void UnregisterNodeSignals(CNodeSignals& nodeSignals);
  141. /**
  142. * Process an incoming block. This only returns after the best known valid
  143. * block is made active. Note that it does not, however, guarantee that the
  144. * specific block passed to it has been checked for validity!
  145. *
  146. * @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 (see validationinterface.h) - this will have its BlockChecked method called whenever *any* block completes validation.
  147. * @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.
  148. * @param[in] pblock The block we want to process.
  149. * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
  150. * @return True if state.IsValid()
  151. */
  152. bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
  153. /** Check whether enough disk space is available for an incoming block */
  154. bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
  155. /** Open a block file (blk?????.dat) */
  156. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  157. /** Open an undo file (rev?????.dat) */
  158. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  159. /** Translation to a filesystem path */
  160. boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
  161. /** Import blocks from an external file */
  162. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
  163. /** Initialize a new block tree database + block data on disk */
  164. bool InitBlockIndex();
  165. /** Load the block tree and coins database from disk */
  166. bool LoadBlockIndex();
  167. /** Unload database information */
  168. void UnloadBlockIndex();
  169. /** Process protocol messages received from a given node */
  170. bool ProcessMessages(CNode* pfrom);
  171. /**
  172. * Send queued protocol messages to be sent to a give node.
  173. *
  174. * @param[in] pto The node which we are sending messages to.
  175. * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
  176. */
  177. bool SendMessages(CNode* pto, bool fSendTrickle);
  178. /** Run an instance of the script checking thread */
  179. void ThreadScriptCheck();
  180. /** Check whether we are doing an initial block download (synchronizing from disk or network) */
  181. bool IsInitialBlockDownload();
  182. /** Format a string that describes several potential problems detected by the core */
  183. std::string GetWarnings(std::string strFor);
  184. /** Retrieve a transaction (from memory pool, or from disk, if possible) */
  185. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
  186. /** Find the best known block, and make it the tip of the block chain */
  187. bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
  188. CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
  189. /**
  190. * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
  191. * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
  192. * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
  193. * (which in this case means the blockchain must be re-downloaded.)
  194. *
  195. * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
  196. * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
  197. * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
  198. * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
  199. * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
  200. * A db flag records the fact that at least some block files have been pruned.
  201. *
  202. * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
  203. */
  204. void FindFilesToPrune(std::set<int>& setFilesToPrune);
  205. /**
  206. * Actually unlink the specified files
  207. */
  208. void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
  209. /** Create a new block index entry for a given block hash */
  210. CBlockIndex * InsertBlockIndex(uint256 hash);
  211. /** Abort with a message */
  212. bool AbortNode(const std::string &msg, const std::string &userMessage="");
  213. /** Get statistics from node state */
  214. bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
  215. /** Increase a node's misbehavior score. */
  216. void Misbehaving(NodeId nodeid, int howmuch);
  217. /** Flush all state, indexes and buffers to disk. */
  218. void FlushStateToDisk();
  219. /** Prune block files and flush state to disk. */
  220. void PruneAndFlush();
  221. /** (try to) add transaction to memory pool **/
  222. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
  223. bool* pfMissingInputs, bool fRejectAbsurdFee=false);
  224. struct CNodeStateStats {
  225. int nMisbehavior;
  226. int nSyncHeight;
  227. int nCommonHeight;
  228. std::vector<int> vHeightInFlight;
  229. };
  230. struct CDiskTxPos : public CDiskBlockPos
  231. {
  232. unsigned int nTxOffset; // after header
  233. ADD_SERIALIZE_METHODS;
  234. template <typename Stream, typename Operation>
  235. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  236. READWRITE(*(CDiskBlockPos*)this);
  237. READWRITE(VARINT(nTxOffset));
  238. }
  239. CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
  240. }
  241. CDiskTxPos() {
  242. SetNull();
  243. }
  244. void SetNull() {
  245. CDiskBlockPos::SetNull();
  246. nTxOffset = 0;
  247. }
  248. };
  249. CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
  250. /**
  251. * Check transaction inputs, and make sure any
  252. * pay-to-script-hash transactions are evaluating IsStandard scripts
  253. *
  254. * Why bother? To avoid denial-of-service attacks; an attacker
  255. * can submit a standard HASH... OP_EQUAL transaction,
  256. * which will get accepted into blocks. The redemption
  257. * script can be anything; an attacker could use a very
  258. * expensive-to-check-upon-redemption script like:
  259. * DUP CHECKSIG DROP ... repeated 100 times... OP_1
  260. */
  261. /**
  262. * Check for standard transaction types
  263. * @param[in] mapInputs Map of previous transactions that have outputs we're spending
  264. * @return True if all inputs (scriptSigs) use only standard transaction forms
  265. */
  266. bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
  267. /**
  268. * Count ECDSA signature operations the old-fashioned (pre-0.6) way
  269. * @return number of sigops this transaction's outputs will produce when spent
  270. * @see CTransaction::FetchInputs
  271. */
  272. unsigned int GetLegacySigOpCount(const CTransaction& tx);
  273. /**
  274. * Count ECDSA signature operations in pay-to-script-hash inputs.
  275. *
  276. * @param[in] mapInputs Map of previous transactions that have outputs we're spending
  277. * @return maximum number of sigops required to validate this transaction's inputs
  278. * @see CTransaction::FetchInputs
  279. */
  280. unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
  281. /**
  282. * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
  283. * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
  284. * instead of being performed inline.
  285. */
  286. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
  287. unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks = NULL);
  288. /** Apply the effects of this transaction on the UTXO set represented by view */
  289. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight);
  290. /** Context-independent validity checks */
  291. bool CheckTransaction(const CTransaction& tx, CValidationState& state);
  292. /** Check for standard transaction types
  293. * @return True if all outputs (scriptPubKeys) use only standard transaction forms
  294. */
  295. bool IsStandardTx(const CTransaction& tx, std::string& reason);
  296. bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
  297. /**
  298. * Closure representing one script verification
  299. * Note that this stores references to the spending transaction
  300. */
  301. class CScriptCheck
  302. {
  303. private:
  304. CScript scriptPubKey;
  305. const CTransaction *ptxTo;
  306. unsigned int nIn;
  307. unsigned int nFlags;
  308. bool cacheStore;
  309. ScriptError error;
  310. public:
  311. CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
  312. CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
  313. scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
  314. ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { }
  315. bool operator()();
  316. void swap(CScriptCheck &check) {
  317. scriptPubKey.swap(check.scriptPubKey);
  318. std::swap(ptxTo, check.ptxTo);
  319. std::swap(nIn, check.nIn);
  320. std::swap(nFlags, check.nFlags);
  321. std::swap(cacheStore, check.cacheStore);
  322. std::swap(error, check.error);
  323. }
  324. ScriptError GetScriptError() const { return error; }
  325. };
  326. /** Functions for disk access for blocks */
  327. bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
  328. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
  329. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
  330. /** Functions for validating blocks and updating the block tree */
  331. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
  332. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
  333. * will be true if no problems were found. Otherwise, the return value will be false in case
  334. * of problems. Note that in any case, coins may be modified. */
  335. bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
  336. /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
  337. bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
  338. /** Context-independent validity checks */
  339. bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
  340. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
  341. /** Context-dependent validity checks */
  342. bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
  343. bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
  344. /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
  345. bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
  346. /** Store block on disk. If dbp is provided, the file is known to already reside on disk */
  347. bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL);
  348. bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
  349. class CBlockFileInfo
  350. {
  351. public:
  352. unsigned int nBlocks; //! number of blocks stored in file
  353. unsigned int nSize; //! number of used bytes of block file
  354. unsigned int nUndoSize; //! number of used bytes in the undo file
  355. unsigned int nHeightFirst; //! lowest height of block in file
  356. unsigned int nHeightLast; //! highest height of block in file
  357. uint64_t nTimeFirst; //! earliest time of block in file
  358. uint64_t nTimeLast; //! latest time of block in file
  359. ADD_SERIALIZE_METHODS;
  360. template <typename Stream, typename Operation>
  361. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  362. READWRITE(VARINT(nBlocks));
  363. READWRITE(VARINT(nSize));
  364. READWRITE(VARINT(nUndoSize));
  365. READWRITE(VARINT(nHeightFirst));
  366. READWRITE(VARINT(nHeightLast));
  367. READWRITE(VARINT(nTimeFirst));
  368. READWRITE(VARINT(nTimeLast));
  369. }
  370. void SetNull() {
  371. nBlocks = 0;
  372. nSize = 0;
  373. nUndoSize = 0;
  374. nHeightFirst = 0;
  375. nHeightLast = 0;
  376. nTimeFirst = 0;
  377. nTimeLast = 0;
  378. }
  379. CBlockFileInfo() {
  380. SetNull();
  381. }
  382. std::string ToString() const;
  383. /** update statistics (does not update nSize) */
  384. void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
  385. if (nBlocks==0 || nHeightFirst > nHeightIn)
  386. nHeightFirst = nHeightIn;
  387. if (nBlocks==0 || nTimeFirst > nTimeIn)
  388. nTimeFirst = nTimeIn;
  389. nBlocks++;
  390. if (nHeightIn > nHeightLast)
  391. nHeightLast = nHeightIn;
  392. if (nTimeIn > nTimeLast)
  393. nTimeLast = nTimeIn;
  394. }
  395. };
  396. /** Capture information about block/transaction validation */
  397. class CValidationState {
  398. private:
  399. enum mode_state {
  400. MODE_VALID, //! everything ok
  401. MODE_INVALID, //! network rule violation (DoS value may be set)
  402. MODE_ERROR, //! run-time error
  403. } mode;
  404. int nDoS;
  405. std::string strRejectReason;
  406. unsigned char chRejectCode;
  407. bool corruptionPossible;
  408. public:
  409. CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
  410. bool DoS(int level, bool ret = false,
  411. unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
  412. bool corruptionIn=false) {
  413. chRejectCode = chRejectCodeIn;
  414. strRejectReason = strRejectReasonIn;
  415. corruptionPossible = corruptionIn;
  416. if (mode == MODE_ERROR)
  417. return ret;
  418. nDoS += level;
  419. mode = MODE_INVALID;
  420. return ret;
  421. }
  422. bool Invalid(bool ret = false,
  423. unsigned char _chRejectCode=0, std::string _strRejectReason="") {
  424. return DoS(0, ret, _chRejectCode, _strRejectReason);
  425. }
  426. bool Error(std::string strRejectReasonIn="") {
  427. if (mode == MODE_VALID)
  428. strRejectReason = strRejectReasonIn;
  429. mode = MODE_ERROR;
  430. return false;
  431. }
  432. bool Abort(const std::string &msg) {
  433. AbortNode(msg);
  434. return Error(msg);
  435. }
  436. bool IsValid() const {
  437. return mode == MODE_VALID;
  438. }
  439. bool IsInvalid() const {
  440. return mode == MODE_INVALID;
  441. }
  442. bool IsError() const {
  443. return mode == MODE_ERROR;
  444. }
  445. bool IsInvalid(int &nDoSOut) const {
  446. if (IsInvalid()) {
  447. nDoSOut = nDoS;
  448. return true;
  449. }
  450. return false;
  451. }
  452. bool CorruptionPossible() const {
  453. return corruptionPossible;
  454. }
  455. unsigned char GetRejectCode() const { return chRejectCode; }
  456. std::string GetRejectReason() const { return strRejectReason; }
  457. };
  458. /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
  459. class CVerifyDB {
  460. public:
  461. CVerifyDB();
  462. ~CVerifyDB();
  463. bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
  464. };
  465. /** Find the last common block between the parameter chain and a locator. */
  466. CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
  467. /** Mark a block as invalid. */
  468. bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
  469. /** Remove invalidity status from a block and its descendants. */
  470. bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
  471. /** The currently-connected chain of blocks. */
  472. extern CChain chainActive;
  473. /** Global variable that points to the active CCoinsView (protected by cs_main) */
  474. extern CCoinsViewCache *pcoinsTip;
  475. /** Global variable that points to the active block tree (protected by cs_main) */
  476. extern CBlockTreeDB *pblocktree;
  477. #endif // BITCOIN_MAIN_H