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