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