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