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.
9 #if defined(HAVE_CONFIG_H)
10 #include "config/bitcoin-config.h"
15 #include "chainparams.h"
17 #include "consensus/consensus.h"
18 #include "consensus/upgrades.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
22 #include "script/script.h"
23 #include "script/sigcache.h"
24 #include "script/standard.h"
26 #include "tinyformat.h"
27 #include "txmempool.h"
29 #include "addressindex.h"
30 #include "spentindex.h"
31 #include "timestampindex.h"
42 #include <boost/unordered_map.hpp>
50 class CValidationInterface;
51 class CValidationState;
52 class PrecomputedTransactionData;
54 struct CNodeStateStats;
56 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
57 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = MAX_BLOCK_SIZE;
58 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
59 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
60 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = DEFAULT_BLOCK_MAX_SIZE / 2;
61 /** Default for accepting alerts from the P2P network. */
62 static const bool DEFAULT_ALERTS = true;
63 /** Minimum alert priority for enabling safe mode. */
64 static const int ALERT_PRIORITY_SAFE_MODE = 4000;
65 /** Maximum reorg length we will accept before we shut down and alert the user. */
66 static const unsigned int MAX_REORG_LENGTH = COINBASE_MATURITY - 1;
67 /** Maximum number of signature check operations in an IsStandard() P2SH script */
68 static const unsigned int MAX_P2SH_SIGOPS = 15;
69 /** The maximum number of sigops we're willing to relay/mine in a single tx */
70 static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
71 /** Default for -minrelaytxfee, minimum relay fee for transactions */
72 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 100;
73 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
74 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
75 /** Default for -txexpirydelta, in number of blocks */
76 static const unsigned int DEFAULT_TX_EXPIRY_DELTA = 20;
77 /** The number of blocks within expiry height when a tx is considered to be expiring soon */
78 static constexpr uint32_t TX_EXPIRING_SOON_THRESHOLD = 3;
79 /** The maximum size of a blk?????.dat file (since 0.8) */
80 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
81 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
82 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
83 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
84 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
85 /** Maximum number of script-checking threads allowed */
86 static const int MAX_SCRIPTCHECK_THREADS = 16;
87 /** -par default (number of script-checking threads, 0 = auto) */
88 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
89 /** Number of blocks that can be requested at any given time from a single peer. */
90 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
91 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
92 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
93 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
94 * less than this number, we reached its tip. Changing this value is a protocol upgrade. */
95 static const unsigned int MAX_HEADERS_RESULTS = 160;
96 /** Size of the "block download window": how far ahead of our current height do we fetch?
97 * Larger windows tolerate larger download speed differences between peer, but increase the potential
98 * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
99 * harder). We'll probably want to make this a per-peer adaptive value at some point. */
100 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
101 /** Time to wait (in seconds) between writing blocks/block index to disk. */
102 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
103 /** Time to wait (in seconds) between flushing chainstate to disk. */
104 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
105 /** Maximum length of reject messages. */
106 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
107 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
109 // Sanity check the magic numbers when we change them
110 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE);
111 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE);
113 #define equihash_parameters_acceptable(N, K) \
114 ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \
115 MAX_PROTOCOL_MESSAGE_LENGTH-1000)
119 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
122 extern unsigned int expiryDelta;
123 extern CScript COINBASE_FLAGS;
124 extern CCriticalSection cs_main;
125 extern CTxMemPool mempool;
126 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
127 extern BlockMap mapBlockIndex;
128 extern uint64_t nLastBlockTx;
129 extern uint64_t nLastBlockSize;
130 extern const std::string strMessageMagic;
131 extern CWaitableCriticalSection csBestBlock;
132 extern CConditionVariable cvBlockChange;
133 extern bool fExperimentalMode;
134 extern bool fImporting;
135 extern bool fReindex;
136 extern int nScriptCheckThreads;
137 extern bool fTxIndex;
139 // START insightexplorer
140 extern bool fInsightExplorer;
142 // The following flags enable specific indices (DB tables), but are not exposed as
143 // separate command-line options; instead they are enabled by experimental feature "-insightexplorer"
144 // and are always equal to the overall controlling flag, fInsightExplorer.
146 // Maintain a full address index, used to query for the balance, txids and unspent outputs for addresses
147 extern bool fAddressIndex;
149 // Maintain a full spent index, used to query the spending txid and input index for an outpoint
150 extern bool fSpentIndex;
152 // END insightexplorer
154 extern bool fIsBareMultisigStd;
155 extern bool fCheckBlockIndex;
156 extern bool fCheckpointsEnabled;
157 // TODO: remove this flag by structuring our code such that
158 // it is unneeded for testing
159 extern bool fCoinbaseEnforcedProtectionEnabled;
160 extern size_t nCoinCacheUsage;
161 extern CFeeRate minRelayTxFee;
163 extern int64_t nMaxTipAge;
165 /** Best header we've seen so far (used for getheaders queries' starting points). */
166 extern CBlockIndex *pindexBestHeader;
168 /** Minimum disk space required - used in CheckDiskSpace() */
169 static const uint64_t nMinDiskSpace = 52428800;
171 /** Pruning-related variables and constants */
172 /** True if any block files have ever been pruned. */
173 extern bool fHavePruned;
174 /** True if we're running in -prune mode. */
175 extern bool fPruneMode;
176 /** Number of MiB of block files that we're trying to stay below. */
177 extern uint64_t nPruneTarget;
178 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
179 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
181 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
182 // At 1MB per block, 288 blocks = 288MB.
183 // Add 15% for Undo data = 331MB
184 // Add 20% for Orphan block rate = 397MB
185 // We want the low water mark after pruning to be at least 397 MB and since we prune in
186 // full block file chunks, we need the high water mark which triggers the prune to be
187 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
188 // Setting the target to > than 550MB will make it likely we can respect the target.
189 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
191 /** Register with a network node to receive its signals */
192 void RegisterNodeSignals(CNodeSignals& nodeSignals);
193 /** Unregister a network node */
194 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
197 * Process an incoming block. This only returns after the best known valid
198 * block is made active. Note that it does not, however, guarantee that the
199 * specific block passed to it has been checked for validity!
201 * @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.
202 * @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.
203 * @param[in] pblock The block we want to process.
204 * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
205 * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
206 * @return True if state.IsValid()
208 bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp);
209 /** Check whether enough disk space is available for an incoming block */
210 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
211 /** Open a block file (blk?????.dat) */
212 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
213 /** Open an undo file (rev?????.dat) */
214 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
215 /** Translation to a filesystem path */
216 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
217 /** Import blocks from an external file */
218 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
219 /** Initialize a new block tree database + block data on disk */
220 bool InitBlockIndex();
221 /** Load the block tree and coins database from disk */
222 bool LoadBlockIndex();
223 /** Unload database information */
224 void UnloadBlockIndex();
225 /** Process protocol messages received from a given node */
226 bool ProcessMessages(CNode* pfrom);
228 * Send queued protocol messages to be sent to a give node.
230 * @param[in] pto The node which we are sending messages to.
231 * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
233 bool SendMessages(CNode* pto, bool fSendTrickle);
234 /** Run an instance of the script checking thread */
235 void ThreadScriptCheck();
236 /** Try to detect Partition (network isolation) attacks against us */
237 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
238 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
239 bool IsInitialBlockDownload();
240 /** Format a string that describes several potential problems detected by the core */
241 std::string GetWarnings(const std::string& strFor);
242 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
243 bool GetTransaction(const uint256 &hash, CTransaction &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false);
244 /** Find the best known block, and make it the tip of the block chain */
245 bool ActivateBestChain(CValidationState &state, const CBlock *pblock = NULL);
246 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
249 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
250 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
251 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
252 * (which in this case means the blockchain must be re-downloaded.)
254 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
255 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
256 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
257 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
258 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
259 * A db flag records the fact that at least some block files have been pruned.
261 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
263 void FindFilesToPrune(std::set<int>& setFilesToPrune);
266 * Actually unlink the specified files
268 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
270 /** Create a new block index entry for a given block hash */
271 CBlockIndex * InsertBlockIndex(uint256 hash);
272 /** Get statistics from node state */
273 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
274 /** Increase a node's misbehavior score. */
275 void Misbehaving(NodeId nodeid, int howmuch);
276 /** Flush all state, indexes and buffers to disk. */
277 void FlushStateToDisk();
278 /** Prune block files and flush state to disk. */
279 void PruneAndFlush();
281 /** (try to) add transaction to memory pool **/
282 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
283 bool* pfMissingInputs, bool fRejectAbsurdFee=false);
286 struct CNodeStateStats {
290 std::vector<int> vHeightInFlight;
293 struct CDiskTxPos : public CDiskBlockPos
295 unsigned int nTxOffset; // after header
297 ADD_SERIALIZE_METHODS;
299 template <typename Stream, typename Operation>
300 inline void SerializationOp(Stream& s, Operation ser_action) {
301 READWRITE(*(CDiskBlockPos*)this);
302 READWRITE(VARINT(nTxOffset));
305 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
313 CDiskBlockPos::SetNull();
319 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
322 * Check transaction inputs, and make sure any
323 * pay-to-script-hash transactions are evaluating IsStandard scripts
325 * Why bother? To avoid denial-of-service attacks; an attacker
326 * can submit a standard HASH... OP_EQUAL transaction,
327 * which will get accepted into blocks. The redemption
328 * script can be anything; an attacker could use a very
329 * expensive-to-check-upon-redemption script like:
330 * DUP CHECKSIG DROP ... repeated 100 times... OP_1
334 * Check for standard transaction types
335 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
336 * @return True if all inputs (scriptSigs) use only standard transaction forms
338 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
341 * Count ECDSA signature operations the old-fashioned (pre-0.6) way
342 * @return number of sigops this transaction's outputs will produce when spent
343 * @see CTransaction::FetchInputs
345 unsigned int GetLegacySigOpCount(const CTransaction& tx);
348 * Count ECDSA signature operations in pay-to-script-hash inputs.
350 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
351 * @return maximum number of sigops required to validate this transaction's inputs
352 * @see CTransaction::FetchInputs
354 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
358 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
359 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
360 * instead of being performed inline.
362 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
363 unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata,
364 const Consensus::Params& consensusParams, uint32_t consensusBranchId,
365 std::vector<CScriptCheck> *pvChecks = NULL);
367 /** Check a transaction contextually against a set of consensus rules */
368 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, int nHeight, int dosLevel,
369 bool (*isInitBlockDownload)() = IsInitialBlockDownload);
371 /** Apply the effects of this transaction on the UTXO set represented by view */
372 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
374 /** Transaction validation functions */
376 /** Context-independent validity checks */
377 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
378 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
380 /** Check for standard transaction types
381 * @return True if all outputs (scriptPubKeys) use only standard transaction forms
383 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
385 namespace Consensus {
388 * Check whether all inputs of this transaction are valid (no double spends and amounts)
389 * This does not modify the UTXO set. This does not check scripts and sigs.
390 * Preconditions: tx.IsCoinBase() is false.
392 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
394 } // namespace Consensus
397 * Check if transaction is final and can be included in a block with the
398 * specified height and time. Consensus critical.
400 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
403 * Check if transaction is expired and can be included in a block with the
404 * specified height. Consensus critical.
406 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
409 * Check if transaction is expiring soon. If yes, not propagating the transaction
410 * can help DoS mitigation. This is not consensus critical.
412 bool IsExpiringSoonTx(const CTransaction &tx, int nNextBlockHeight);
415 * Check if transaction will be final in the next block to be created.
417 * Calls IsFinalTx() with current block height and appropriate block time.
419 * See consensus/consensus.h for flag definitions.
421 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
424 * Closure representing one script verification
425 * Note that this stores references to the spending transaction
430 CScript scriptPubKey;
432 const CTransaction *ptxTo;
436 uint32_t consensusBranchId;
438 PrecomputedTransactionData *txdata;
441 CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), consensusBranchId(0), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
442 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, uint32_t consensusBranchIdIn, PrecomputedTransactionData* txdataIn) :
443 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
444 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), consensusBranchId(consensusBranchIdIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
448 void swap(CScriptCheck &check) {
449 scriptPubKey.swap(check.scriptPubKey);
450 std::swap(ptxTo, check.ptxTo);
451 std::swap(amount, check.amount);
452 std::swap(nIn, check.nIn);
453 std::swap(nFlags, check.nFlags);
454 std::swap(cacheStore, check.cacheStore);
455 std::swap(consensusBranchId, check.consensusBranchId);
456 std::swap(error, check.error);
457 std::swap(txdata, check.txdata);
460 ScriptError GetScriptError() const { return error; }
464 /** Functions for disk access for blocks */
465 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
466 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
467 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
469 /** Functions for validating blocks and updating the block tree */
471 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
472 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
474 /** Context-independent validity checks */
475 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
476 bool CheckBlock(const CBlock& block, CValidationState& state,
477 libzcash::ProofVerifier& verifier,
478 bool fCheckPOW = true, bool fCheckMerkleRoot = true);
480 /** Context-dependent validity checks */
481 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
482 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
484 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
485 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
488 * Store block on disk.
489 * JoinSplit proofs are never verified, because:
490 * - AcceptBlock doesn't perform script checks either.
491 * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere.
492 * If dbp is non-NULL, the file is known to already reside on disk
494 bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
498 * When there are blocks in the active chain with missing data (e.g. if the
499 * activation height and branch ID of a particular upgrade have been altered),
500 * rewind the chainstate and remove them from the block index.
502 * clearWitnessCaches is an output parameter that will be set to true iff
503 * witness caches should be cleared in order to handle an intended long rewind.
505 bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches);
510 unsigned int nBlocks; //! number of blocks stored in file
511 unsigned int nSize; //! number of used bytes of block file
512 unsigned int nUndoSize; //! number of used bytes in the undo file
513 unsigned int nHeightFirst; //! lowest height of block in file
514 unsigned int nHeightLast; //! highest height of block in file
515 uint64_t nTimeFirst; //! earliest time of block in file
516 uint64_t nTimeLast; //! latest time of block in file
518 ADD_SERIALIZE_METHODS;
520 template <typename Stream, typename Operation>
521 inline void SerializationOp(Stream& s, Operation ser_action) {
522 READWRITE(VARINT(nBlocks));
523 READWRITE(VARINT(nSize));
524 READWRITE(VARINT(nUndoSize));
525 READWRITE(VARINT(nHeightFirst));
526 READWRITE(VARINT(nHeightLast));
527 READWRITE(VARINT(nTimeFirst));
528 READWRITE(VARINT(nTimeLast));
545 std::string ToString() const;
547 /** update statistics (does not update nSize) */
548 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
549 if (nBlocks==0 || nHeightFirst > nHeightIn)
550 nHeightFirst = nHeightIn;
551 if (nBlocks==0 || nTimeFirst > nTimeIn)
552 nTimeFirst = nTimeIn;
554 if (nHeightIn > nHeightLast)
555 nHeightLast = nHeightIn;
556 if (nTimeIn > nTimeLast)
561 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
566 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
569 /** Find the last common block between the parameter chain and a locator. */
570 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
572 /** Mark a block as invalid. */
573 bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex);
575 /** Remove invalidity status from a block and its descendants. */
576 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
578 /** The currently-connected chain of blocks (protected by cs_main). */
579 extern CChain chainActive;
581 /** Global variable that points to the active CCoinsView (protected by cs_main) */
582 extern CCoinsViewCache *pcoinsTip;
584 /** Global variable that points to the active block tree (protected by cs_main) */
585 extern CBlockTreeDB *pblocktree;
588 * Return the spend height, which is one more than the inputs.GetBestBlock().
589 * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
590 * This is also true for mempool checks.
592 int GetSpendHeight(const CCoinsViewCache& inputs);
594 uint64_t CalculateCurrentUsage();
596 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at nHeight, and the default expiry delta. */
597 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight);
599 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at nHeight, and given expiry delta. */
600 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight, int nExpiryDelta);
602 #endif // BITCOIN_MAIN_H