Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2015 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 "coins.h"
  13. #include "net.h"
  14. #include "script/script_error.h"
  15. #include "sync.h"
  16. #include "versionbits.h"
  17. #include <algorithm>
  18. #include <exception>
  19. #include <map>
  20. #include <set>
  21. #include <stdint.h>
  22. #include <string>
  23. #include <utility>
  24. #include <vector>
  25. #include <boost/unordered_map.hpp>
  26. class CBlockIndex;
  27. class CBlockTreeDB;
  28. class CBloomFilter;
  29. class CChainParams;
  30. class CInv;
  31. class CScriptCheck;
  32. class CTxMemPool;
  33. class CValidationInterface;
  34. class CValidationState;
  35. struct CNodeStateStats;
  36. struct LockPoints;
  37. /** Default for DEFAULT_WHITELISTRELAY. */
  38. static const bool DEFAULT_WHITELISTRELAY = true;
  39. /** Default for DEFAULT_WHITELISTFORCERELAY. */
  40. static const bool DEFAULT_WHITELISTFORCERELAY = true;
  41. /** Default for -minrelaytxfee, minimum relay fee for transactions */
  42. static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
  43. //! -maxtxfee default
  44. static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN;
  45. //! Discourage users to set fees higher than this amount (in satoshis) per kB
  46. static const CAmount HIGH_TX_FEE_PER_KB = 0.01 * COIN;
  47. //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
  48. static const CAmount HIGH_MAX_TX_FEE = 100 * HIGH_TX_FEE_PER_KB;
  49. /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
  50. static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
  51. /** Default for -limitancestorcount, max number of in-mempool ancestors */
  52. static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
  53. /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
  54. static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
  55. /** Default for -limitdescendantcount, max number of in-mempool descendants */
  56. static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
  57. /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
  58. static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
  59. /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
  60. static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 72;
  61. /** The maximum size of a blk?????.dat file (since 0.8) */
  62. static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
  63. /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
  64. static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
  65. /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
  66. static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
  67. /** Maximum number of script-checking threads allowed */
  68. static const int MAX_SCRIPTCHECK_THREADS = 16;
  69. /** -par default (number of script-checking threads, 0 = auto) */
  70. static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
  71. /** Number of blocks that can be requested at any given time from a single peer. */
  72. static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
  73. /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
  74. static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
  75. /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
  76. * less than this number, we reached its tip. Changing this value is a protocol upgrade. */
  77. static const unsigned int MAX_HEADERS_RESULTS = 2000;
  78. /** Size of the "block download window": how far ahead of our current height do we fetch?
  79. * Larger windows tolerate larger download speed differences between peer, but increase the potential
  80. * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
  81. * harder). We'll probably want to make this a per-peer adaptive value at some point. */
  82. static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
  83. /** Time to wait (in seconds) between writing blocks/block index to disk. */
  84. static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
  85. /** Time to wait (in seconds) between flushing chainstate to disk. */
  86. static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
  87. /** Maximum length of reject messages. */
  88. static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
  89. /** Average delay between local address broadcasts in seconds. */
  90. static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 24 * 60;
  91. /** Average delay between peer address broadcasts in seconds. */
  92. static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
  93. /** Average delay between trickled inventory broadcasts in seconds.
  94. * Blocks, whitelisted receivers, and a random 25% of transactions bypass this. */
  95. static const unsigned int AVG_INVENTORY_BROADCAST_INTERVAL = 5;
  96. /** Average delay between feefilter broadcasts in seconds. */
  97. static const unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
  98. /** Maximum feefilter broadcast delay after significant change. */
  99. static const unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
  100. static const unsigned int DEFAULT_LIMITFREERELAY = 15;
  101. static const bool DEFAULT_RELAYPRIORITY = true;
  102. static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
  103. /** Default for -permitbaremultisig */
  104. static const bool DEFAULT_PERMIT_BAREMULTISIG = true;
  105. static const unsigned int DEFAULT_BYTES_PER_SIGOP = 20;
  106. static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
  107. static const bool DEFAULT_TXINDEX = false;
  108. static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
  109. static const bool DEFAULT_TESTSAFEMODE = false;
  110. /** Default for -mempoolreplacement */
  111. static const bool DEFAULT_ENABLE_REPLACEMENT = true;
  112. /** Default for using fee filter */
  113. static const bool DEFAULT_FEEFILTER = true;
  114. /** Maximum number of headers to announce when relaying blocks with headers message.*/
  115. static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
  116. static const bool DEFAULT_PEERBLOOMFILTERS = true;
  117. struct BlockHasher
  118. {
  119. size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
  120. };
  121. extern CScript COINBASE_FLAGS;
  122. extern CCriticalSection cs_main;
  123. extern CTxMemPool mempool;
  124. typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
  125. extern BlockMap mapBlockIndex;
  126. extern uint64_t nLastBlockTx;
  127. extern uint64_t nLastBlockSize;
  128. extern const std::string strMessageMagic;
  129. extern CWaitableCriticalSection csBestBlock;
  130. extern CConditionVariable cvBlockChange;
  131. extern bool fImporting;
  132. extern bool fReindex;
  133. extern int nScriptCheckThreads;
  134. extern bool fTxIndex;
  135. extern bool fIsBareMultisigStd;
  136. extern bool fRequireStandard;
  137. extern unsigned int nBytesPerSigOp;
  138. extern bool fCheckBlockIndex;
  139. extern bool fCheckpointsEnabled;
  140. extern size_t nCoinCacheUsage;
  141. /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */
  142. extern CFeeRate minRelayTxFee;
  143. /** Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendrawtransaction) */
  144. extern CAmount maxTxFee;
  145. /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
  146. extern int64_t nMaxTipAge;
  147. extern bool fEnableReplacement;
  148. /** Best header we've seen so far (used for getheaders queries' starting points). */
  149. extern CBlockIndex *pindexBestHeader;
  150. /** Minimum disk space required - used in CheckDiskSpace() */
  151. static const uint64_t nMinDiskSpace = 52428800;
  152. /** Pruning-related variables and constants */
  153. /** True if any block files have ever been pruned. */
  154. extern bool fHavePruned;
  155. /** True if we're running in -prune mode. */
  156. extern bool fPruneMode;
  157. /** Number of MiB of block files that we're trying to stay below. */
  158. extern uint64_t nPruneTarget;
  159. /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
  160. static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
  161. static const signed int DEFAULT_CHECKBLOCKS = MIN_BLOCKS_TO_KEEP;
  162. static const unsigned int DEFAULT_CHECKLEVEL = 3;
  163. // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
  164. // At 1MB per block, 288 blocks = 288MB.
  165. // Add 15% for Undo data = 331MB
  166. // Add 20% for Orphan block rate = 397MB
  167. // We want the low water mark after pruning to be at least 397 MB and since we prune in
  168. // full block file chunks, we need the high water mark which triggers the prune to be
  169. // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
  170. // Setting the target to > than 550MB will make it likely we can respect the target.
  171. static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
  172. /** Register with a network node to receive its signals */
  173. void RegisterNodeSignals(CNodeSignals& nodeSignals);
  174. /** Unregister a network node */
  175. void UnregisterNodeSignals(CNodeSignals& nodeSignals);
  176. /**
  177. * Process an incoming block. This only returns after the best known valid
  178. * block is made active. Note that it does not, however, guarantee that the
  179. * specific block passed to it has been checked for validity!
  180. *
  181. * @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.
  182. * @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.
  183. * @param[in] pblock The block we want to process.
  184. * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
  185. * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
  186. * @return True if state.IsValid()
  187. */
  188. bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp);
  189. /** Check whether enough disk space is available for an incoming block */
  190. bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
  191. /** Open a block file (blk?????.dat) */
  192. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  193. /** Open an undo file (rev?????.dat) */
  194. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  195. /** Translation to a filesystem path */
  196. boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
  197. /** Import blocks from an external file */
  198. bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp = NULL);
  199. /** Initialize a new block tree database + block data on disk */
  200. bool InitBlockIndex(const CChainParams& chainparams);
  201. /** Load the block tree and coins database from disk */
  202. bool LoadBlockIndex();
  203. /** Unload database information */
  204. void UnloadBlockIndex();
  205. /** Process protocol messages received from a given node */
  206. bool ProcessMessages(CNode* pfrom);
  207. /**
  208. * Send queued protocol messages to be sent to a give node.
  209. *
  210. * @param[in] pto The node which we are sending messages to.
  211. */
  212. bool SendMessages(CNode* pto);
  213. /** Run an instance of the script checking thread */
  214. void ThreadScriptCheck();
  215. /** Try to detect Partition (network isolation) attacks against us */
  216. void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
  217. /** Check whether we are doing an initial block download (synchronizing from disk or network) */
  218. bool IsInitialBlockDownload();
  219. /** Format a string that describes several potential problems detected by the core.
  220. * strFor can have three values:
  221. * - "rpc": get critical warnings, which should put the client in safe mode if non-empty
  222. * - "statusbar": get all warnings
  223. * - "gui": get all warnings, translated (where possible) for GUI
  224. * This function only returns the highest priority warning of the set selected by strFor.
  225. */
  226. std::string GetWarnings(const std::string& strFor);
  227. /** Retrieve a transaction (from memory pool, or from disk, if possible) */
  228. bool GetTransaction(const uint256 &hash, CTransaction &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false);
  229. /** Find the best known block, and make it the tip of the block chain */
  230. bool ActivateBestChain(CValidationState& state, const CChainParams& chainparams, const CBlock* pblock = NULL);
  231. CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
  232. /**
  233. * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
  234. * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
  235. * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
  236. * (which in this case means the blockchain must be re-downloaded.)
  237. *
  238. * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
  239. * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
  240. * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
  241. * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
  242. * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
  243. * A db flag records the fact that at least some block files have been pruned.
  244. *
  245. * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
  246. */
  247. void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
  248. /**
  249. * Actually unlink the specified files
  250. */
  251. void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
  252. /** Create a new block index entry for a given block hash */
  253. CBlockIndex * InsertBlockIndex(uint256 hash);
  254. /** Get statistics from node state */
  255. bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
  256. /** Increase a node's misbehavior score. */
  257. void Misbehaving(NodeId nodeid, int howmuch);
  258. /** Flush all state, indexes and buffers to disk. */
  259. void FlushStateToDisk();
  260. /** Prune block files and flush state to disk. */
  261. void PruneAndFlush();
  262. /** (try to) add transaction to memory pool **/
  263. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
  264. bool* pfMissingInputs, CFeeRate* txFeeRate, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0);
  265. /** Convert CValidationState to a human-readable message for logging */
  266. std::string FormatStateMessage(const CValidationState &state);
  267. /** Get the BIP9 state for a given deployment at the current tip. */
  268. ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos);
  269. struct CNodeStateStats {
  270. int nMisbehavior;
  271. int nSyncHeight;
  272. int nCommonHeight;
  273. std::vector<int> vHeightInFlight;
  274. };
  275. struct CDiskTxPos : public CDiskBlockPos
  276. {
  277. unsigned int nTxOffset; // after header
  278. ADD_SERIALIZE_METHODS;
  279. template <typename Stream, typename Operation>
  280. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  281. READWRITE(*(CDiskBlockPos*)this);
  282. READWRITE(VARINT(nTxOffset));
  283. }
  284. CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
  285. }
  286. CDiskTxPos() {
  287. SetNull();
  288. }
  289. void SetNull() {
  290. CDiskBlockPos::SetNull();
  291. nTxOffset = 0;
  292. }
  293. };
  294. /**
  295. * Count ECDSA signature operations the old-fashioned (pre-0.6) way
  296. * @return number of sigops this transaction's outputs will produce when spent
  297. * @see CTransaction::FetchInputs
  298. */
  299. unsigned int GetLegacySigOpCount(const CTransaction& tx);
  300. /**
  301. * Count ECDSA signature operations in pay-to-script-hash inputs.
  302. *
  303. * @param[in] mapInputs Map of previous transactions that have outputs we're spending
  304. * @return maximum number of sigops required to validate this transaction's inputs
  305. * @see CTransaction::FetchInputs
  306. */
  307. unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
  308. /**
  309. * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
  310. * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
  311. * instead of being performed inline.
  312. */
  313. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
  314. unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks = NULL);
  315. /** Apply the effects of this transaction on the UTXO set represented by view */
  316. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight);
  317. /** Context-independent validity checks */
  318. bool CheckTransaction(const CTransaction& tx, CValidationState& state);
  319. /**
  320. * Check if transaction is final and can be included in a block with the
  321. * specified height and time. Consensus critical.
  322. */
  323. bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
  324. /**
  325. * Check if transaction will be final in the next block to be created.
  326. *
  327. * Calls IsFinalTx() with current block height and appropriate block time.
  328. *
  329. * See consensus/consensus.h for flag definitions.
  330. */
  331. bool CheckFinalTx(const CTransaction &tx, int flags = -1);
  332. /**
  333. * Test whether the LockPoints height and time are still valid on the current chain
  334. */
  335. bool TestLockPointValidity(const LockPoints* lp);
  336. /**
  337. * Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
  338. * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed.
  339. */
  340. bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
  341. /**
  342. * Check if transaction will be BIP 68 final in the next block to be created.
  343. *
  344. * Simulates calling SequenceLocks() with data from the tip of the current active chain.
  345. * Optionally stores in LockPoints the resulting height and time calculated and the hash
  346. * of the block needed for calculation or skips the calculation and uses the LockPoints
  347. * passed in for evaluation.
  348. * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
  349. *
  350. * See consensus/consensus.h for flag definitions.
  351. */
  352. bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = NULL, bool useExistingLockPoints = false);
  353. /**
  354. * Closure representing one script verification
  355. * Note that this stores references to the spending transaction
  356. */
  357. class CScriptCheck
  358. {
  359. private:
  360. CScript scriptPubKey;
  361. const CTransaction *ptxTo;
  362. unsigned int nIn;
  363. unsigned int nFlags;
  364. bool cacheStore;
  365. ScriptError error;
  366. public:
  367. CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
  368. CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
  369. scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
  370. ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { }
  371. bool operator()();
  372. void swap(CScriptCheck &check) {
  373. scriptPubKey.swap(check.scriptPubKey);
  374. std::swap(ptxTo, check.ptxTo);
  375. std::swap(nIn, check.nIn);
  376. std::swap(nFlags, check.nFlags);
  377. std::swap(cacheStore, check.cacheStore);
  378. std::swap(error, check.error);
  379. }
  380. ScriptError GetScriptError() const { return error; }
  381. };
  382. /** Functions for disk access for blocks */
  383. bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
  384. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
  385. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
  386. /** Functions for validating blocks and updating the block tree */
  387. /** Context-independent validity checks */
  388. bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
  389. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
  390. /** Context-dependent validity checks.
  391. * By "context", we mean only the previous block headers, but not the UTXO
  392. * set; UTXO-related validity checks are done in ConnectBlock(). */
  393. bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
  394. bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
  395. /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
  396. * Validity checks that depend on the UTXO set are also done; ConnectBlock()
  397. * can fail if those validity checks fail (among other reasons). */
  398. bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
  399. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
  400. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
  401. * will be true if no problems were found. Otherwise, the return value will be false in case
  402. * of problems. Note that in any case, coins may be modified. */
  403. bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
  404. /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
  405. bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
  406. class CBlockFileInfo
  407. {
  408. public:
  409. unsigned int nBlocks; //!< number of blocks stored in file
  410. unsigned int nSize; //!< number of used bytes of block file
  411. unsigned int nUndoSize; //!< number of used bytes in the undo file
  412. unsigned int nHeightFirst; //!< lowest height of block in file
  413. unsigned int nHeightLast; //!< highest height of block in file
  414. uint64_t nTimeFirst; //!< earliest time of block in file
  415. uint64_t nTimeLast; //!< latest time of block in file
  416. ADD_SERIALIZE_METHODS;
  417. template <typename Stream, typename Operation>
  418. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  419. READWRITE(VARINT(nBlocks));
  420. READWRITE(VARINT(nSize));
  421. READWRITE(VARINT(nUndoSize));
  422. READWRITE(VARINT(nHeightFirst));
  423. READWRITE(VARINT(nHeightLast));
  424. READWRITE(VARINT(nTimeFirst));
  425. READWRITE(VARINT(nTimeLast));
  426. }
  427. void SetNull() {
  428. nBlocks = 0;
  429. nSize = 0;
  430. nUndoSize = 0;
  431. nHeightFirst = 0;
  432. nHeightLast = 0;
  433. nTimeFirst = 0;
  434. nTimeLast = 0;
  435. }
  436. CBlockFileInfo() {
  437. SetNull();
  438. }
  439. std::string ToString() const;
  440. /** update statistics (does not update nSize) */
  441. void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
  442. if (nBlocks==0 || nHeightFirst > nHeightIn)
  443. nHeightFirst = nHeightIn;
  444. if (nBlocks==0 || nTimeFirst > nTimeIn)
  445. nTimeFirst = nTimeIn;
  446. nBlocks++;
  447. if (nHeightIn > nHeightLast)
  448. nHeightLast = nHeightIn;
  449. if (nTimeIn > nTimeLast)
  450. nTimeLast = nTimeIn;
  451. }
  452. };
  453. /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
  454. class CVerifyDB {
  455. public:
  456. CVerifyDB();
  457. ~CVerifyDB();
  458. bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
  459. };
  460. /** Find the last common block between the parameter chain and a locator. */
  461. CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
  462. /** Mark a block as invalid. */
  463. bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex);
  464. /** Remove invalidity status from a block and its descendants. */
  465. bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
  466. /** The currently-connected chain of blocks (protected by cs_main). */
  467. extern CChain chainActive;
  468. /** Global variable that points to the active CCoinsView (protected by cs_main) */
  469. extern CCoinsViewCache *pcoinsTip;
  470. /** Global variable that points to the active block tree (protected by cs_main) */
  471. extern CBlockTreeDB *pblocktree;
  472. /**
  473. * Return the spend height, which is one more than the inputs.GetBestBlock().
  474. * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
  475. * This is also true for mempool checks.
  476. */
  477. int GetSpendHeight(const CCoinsViewCache& inputs);
  478. /**
  479. * Determine what nVersion a new block should use.
  480. */
  481. int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
  482. /** Reject codes greater or equal to this can be returned by AcceptToMemPool
  483. * for transactions, to signal internal conditions. They cannot and should not
  484. * be sent over the P2P network.
  485. */
  486. static const unsigned int REJECT_INTERNAL = 0x100;
  487. /** Too high fee. Can not be triggered by P2P transactions */
  488. static const unsigned int REJECT_HIGHFEE = 0x100;
  489. /** Transaction is already known (either in mempool or blockchain) */
  490. static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
  491. /** Transaction conflicts with a transaction already known */
  492. static const unsigned int REJECT_CONFLICT = 0x102;
  493. #endif // BITCOIN_MAIN_H