Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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