Add DumpMempool and LoadMempool
[bitcoinplatinum.git] / src / main.h
blob4c6af9514206c89af50d19bb590afa2ba21f6009
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 "validationinterface.h"
20 #include "versionbits.h"
22 #include <algorithm>
23 #include <exception>
24 #include <map>
25 #include <set>
26 #include <stdint.h>
27 #include <string>
28 #include <utility>
29 #include <vector>
31 #include <boost/unordered_map.hpp>
33 class CBlockIndex;
34 class CBlockTreeDB;
35 class CBloomFilter;
36 class CChainParams;
37 class CInv;
38 class CConnman;
39 class CScriptCheck;
40 class CTxMemPool;
41 class CValidationInterface;
42 class CValidationState;
44 struct PrecomputedTransactionData;
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 /** Maximum depth of blocks we're willing to serve as compact blocks to peers
94 * when requested. For older blocks, a regular BLOCK response will be sent. */
95 static const int MAX_CMPCTBLOCK_DEPTH = 5;
96 /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
97 static const int MAX_BLOCKTXN_DEPTH = 10;
98 /** Size of the "block download window": how far ahead of our current height do we fetch?
99 * Larger windows tolerate larger download speed differences between peer, but increase the potential
100 * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
101 * harder). We'll probably want to make this a per-peer adaptive value at some point. */
102 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
103 /** Time to wait (in seconds) between writing blocks/block index to disk. */
104 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
105 /** Time to wait (in seconds) between flushing chainstate to disk. */
106 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
107 /** Maximum length of reject messages. */
108 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
109 /** Average delay between local address broadcasts in seconds. */
110 static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 24 * 60;
111 /** Average delay between peer address broadcasts in seconds. */
112 static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
113 /** Average delay between trickled inventory transmissions in seconds.
114 * Blocks and whitelisted receivers bypass this, outbound peers get half this delay. */
115 static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5;
116 /** Maximum number of inventory items to send per transmission.
117 * Limits the impact of low-fee transaction floods. */
118 static const unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_INTERVAL;
119 /** Average delay between feefilter broadcasts in seconds. */
120 static const unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
121 /** Maximum feefilter broadcast delay after significant change. */
122 static const unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
123 /** Block download timeout base, expressed in millionths of the block interval (i.e. 10 min) */
124 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
125 /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
126 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
128 static const unsigned int DEFAULT_LIMITFREERELAY = 15;
129 static const bool DEFAULT_RELAYPRIORITY = true;
130 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
132 /** Default for -permitbaremultisig */
133 static const bool DEFAULT_PERMIT_BAREMULTISIG = true;
134 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
135 static const bool DEFAULT_TXINDEX = false;
136 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
138 static const bool DEFAULT_TESTSAFEMODE = false;
139 /** Default for -mempoolreplacement */
140 static const bool DEFAULT_ENABLE_REPLACEMENT = true;
141 /** Default for using fee filter */
142 static const bool DEFAULT_FEEFILTER = true;
144 /** Maximum number of headers to announce when relaying blocks with headers message.*/
145 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
147 /** Maximum number of unconnecting headers announcements before DoS score */
148 static const int MAX_UNCONNECTING_HEADERS = 10;
150 static const bool DEFAULT_PEERBLOOMFILTERS = true;
152 struct BlockHasher
154 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
157 extern CScript COINBASE_FLAGS;
158 extern CCriticalSection cs_main;
159 extern CTxMemPool mempool;
160 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
161 extern BlockMap mapBlockIndex;
162 extern uint64_t nLastBlockTx;
163 extern uint64_t nLastBlockSize;
164 extern uint64_t nLastBlockWeight;
165 extern const std::string strMessageMagic;
166 extern CWaitableCriticalSection csBestBlock;
167 extern CConditionVariable cvBlockChange;
168 extern bool fImporting;
169 extern bool fReindex;
170 extern int nScriptCheckThreads;
171 extern bool fTxIndex;
172 extern bool fIsBareMultisigStd;
173 extern bool fRequireStandard;
174 extern bool fCheckBlockIndex;
175 extern bool fCheckpointsEnabled;
176 extern size_t nCoinCacheUsage;
177 /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */
178 extern CFeeRate minRelayTxFee;
179 /** Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendrawtransaction) */
180 extern CAmount maxTxFee;
181 /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
182 extern int64_t nMaxTipAge;
183 extern bool fEnableReplacement;
185 /** Best header we've seen so far (used for getheaders queries' starting points). */
186 extern CBlockIndex *pindexBestHeader;
188 /** Minimum disk space required - used in CheckDiskSpace() */
189 static const uint64_t nMinDiskSpace = 52428800;
191 /** Pruning-related variables and constants */
192 /** True if any block files have ever been pruned. */
193 extern bool fHavePruned;
194 /** True if we're running in -prune mode. */
195 extern bool fPruneMode;
196 /** Number of MiB of block files that we're trying to stay below. */
197 extern uint64_t nPruneTarget;
198 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
199 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
201 static const signed int DEFAULT_CHECKBLOCKS = 6;
202 static const unsigned int DEFAULT_CHECKLEVEL = 3;
204 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
205 // At 1MB per block, 288 blocks = 288MB.
206 // Add 15% for Undo data = 331MB
207 // Add 20% for Orphan block rate = 397MB
208 // We want the low water mark after pruning to be at least 397 MB and since we prune in
209 // full block file chunks, we need the high water mark which triggers the prune to be
210 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
211 // Setting the target to > than 550MB will make it likely we can respect the target.
212 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
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);
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 /** Run an instance of the script checking thread */
244 void ThreadScriptCheck();
245 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
246 bool IsInitialBlockDownload();
247 /** Format a string that describes several potential problems detected by the core.
248 * strFor can have three values:
249 * - "rpc": get critical warnings, which should put the client in safe mode if non-empty
250 * - "statusbar": get all warnings
251 * - "gui": get all warnings, translated (where possible) for GUI
252 * This function only returns the highest priority warning of the set selected by strFor.
254 std::string GetWarnings(const std::string& strFor);
255 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
256 bool GetTransaction(const uint256 &hash, CTransaction &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false);
257 /** Find the best known block, and make it the tip of the block chain */
258 bool ActivateBestChain(CValidationState& state, const CChainParams& chainparams, const CBlock* pblock = NULL);
259 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
262 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
263 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
264 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
265 * (which in this case means the blockchain must be re-downloaded.)
267 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
268 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
269 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
270 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
271 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
272 * A db flag records the fact that at least some block files have been pruned.
274 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
276 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
279 * Actually unlink the specified files
281 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
283 /** Create a new block index entry for a given block hash */
284 CBlockIndex * InsertBlockIndex(uint256 hash);
285 /** Flush all state, indexes and buffers to disk. */
286 void FlushStateToDisk();
287 /** Prune block files and flush state to disk. */
288 void PruneAndFlush();
290 /** (try to) add transaction to memory pool **/
291 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
292 bool* pfMissingInputs, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0);
294 /** (try to) add transaction to memory pool with a specified acceptance time **/
295 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
296 bool* pfMissingInputs, int64_t nAcceptTime, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0);
298 /** Convert CValidationState to a human-readable message for logging */
299 std::string FormatStateMessage(const CValidationState &state);
301 /** Get the BIP9 state for a given deployment at the current tip. */
302 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos);
304 /** Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip. */
305 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos);
307 /**
308 * Count ECDSA signature operations the old-fashioned (pre-0.6) way
309 * @return number of sigops this transaction's outputs will produce when spent
310 * @see CTransaction::FetchInputs
312 unsigned int GetLegacySigOpCount(const CTransaction& tx);
315 * Count ECDSA signature operations in pay-to-script-hash inputs.
317 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
318 * @return maximum number of sigops required to validate this transaction's inputs
319 * @see CTransaction::FetchInputs
321 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
324 * Compute total signature operation cost of a transaction.
325 * @param[in] tx Transaction for which we are computing the cost
326 * @param[in] inputs Map of previous transactions that have outputs we're spending
327 * @param[out] flags Script verification flags
328 * @return Total signature operation cost of tx
330 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags);
333 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
334 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
335 * instead of being performed inline.
337 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
338 unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = NULL);
340 /** Apply the effects of this transaction on the UTXO set represented by view */
341 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
343 /** Transaction validation functions */
345 /** Context-independent validity checks */
346 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
348 namespace Consensus {
351 * Check whether all inputs of this transaction are valid (no double spends and amounts)
352 * This does not modify the UTXO set. This does not check scripts and sigs.
353 * Preconditions: tx.IsCoinBase() is false.
355 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight);
357 } // namespace Consensus
360 * Check if transaction is final and can be included in a block with the
361 * specified height and time. Consensus critical.
363 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
366 * Check if transaction will be final in the next block to be created.
368 * Calls IsFinalTx() with current block height and appropriate block time.
370 * See consensus/consensus.h for flag definitions.
372 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
375 * Test whether the LockPoints height and time are still valid on the current chain
377 bool TestLockPointValidity(const LockPoints* lp);
380 * Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
381 * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed.
383 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
386 * Check if transaction will be BIP 68 final in the next block to be created.
388 * Simulates calling SequenceLocks() with data from the tip of the current active chain.
389 * Optionally stores in LockPoints the resulting height and time calculated and the hash
390 * of the block needed for calculation or skips the calculation and uses the LockPoints
391 * passed in for evaluation.
392 * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
394 * See consensus/consensus.h for flag definitions.
396 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = NULL, bool useExistingLockPoints = false);
399 * Closure representing one script verification
400 * Note that this stores references to the spending transaction
402 class CScriptCheck
404 private:
405 CScript scriptPubKey;
406 CAmount amount;
407 const CTransaction *ptxTo;
408 unsigned int nIn;
409 unsigned int nFlags;
410 bool cacheStore;
411 ScriptError error;
412 PrecomputedTransactionData *txdata;
414 public:
415 CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
416 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
417 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
418 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
420 bool operator()();
422 void swap(CScriptCheck &check) {
423 scriptPubKey.swap(check.scriptPubKey);
424 std::swap(ptxTo, check.ptxTo);
425 std::swap(amount, check.amount);
426 std::swap(nIn, check.nIn);
427 std::swap(nFlags, check.nFlags);
428 std::swap(cacheStore, check.cacheStore);
429 std::swap(error, check.error);
430 std::swap(txdata, check.txdata);
433 ScriptError GetScriptError() const { return error; }
437 /** Functions for disk access for blocks */
438 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
439 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
440 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
442 /** Functions for validating blocks and updating the block tree */
444 /** Context-independent validity checks */
445 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true);
446 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
448 /** Context-dependent validity checks.
449 * By "context", we mean only the previous block headers, but not the UTXO
450 * set; UTXO-related validity checks are done in ConnectBlock(). */
451 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime);
452 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);
454 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
455 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
456 * can fail if those validity checks fail (among other reasons). */
457 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins,
458 const CChainParams& chainparams, bool fJustCheck = false);
460 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
461 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
462 * will be true if no problems were found. Otherwise, the return value will be false in case
463 * of problems. Note that in any case, coins may be modified. */
464 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
466 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
467 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
469 /** Check whether witness commitments are required for block. */
470 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
472 /** When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index */
473 bool RewindBlockIndex(const CChainParams& params);
475 /** Update uncommitted block structures (currently: only the witness nonce). This is safe for submitted blocks. */
476 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
478 /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
479 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
481 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
482 class CVerifyDB {
483 public:
484 CVerifyDB();
485 ~CVerifyDB();
486 bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
489 /** Find the last common block between the parameter chain and a locator. */
490 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
492 /** Mark a block as precious and reorganize. */
493 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex);
495 /** Mark a block as invalid. */
496 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex);
498 /** Remove invalidity status from a block and its descendants. */
499 bool ResetBlockFailureFlags(CBlockIndex *pindex);
501 /** The currently-connected chain of blocks (protected by cs_main). */
502 extern CChain chainActive;
504 /** Global variable that points to the active CCoinsView (protected by cs_main) */
505 extern CCoinsViewCache *pcoinsTip;
507 /** Global variable that points to the active block tree (protected by cs_main) */
508 extern CBlockTreeDB *pblocktree;
511 * Return the spend height, which is one more than the inputs.GetBestBlock().
512 * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
513 * This is also true for mempool checks.
515 int GetSpendHeight(const CCoinsViewCache& inputs);
517 extern VersionBitsCache versionbitscache;
520 * Determine what nVersion a new block should use.
522 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
524 /** Reject codes greater or equal to this can be returned by AcceptToMemPool
525 * for transactions, to signal internal conditions. They cannot and should not
526 * be sent over the P2P network.
528 static const unsigned int REJECT_INTERNAL = 0x100;
529 /** Too high fee. Can not be triggered by P2P transactions */
530 static const unsigned int REJECT_HIGHFEE = 0x100;
531 /** Transaction is already known (either in mempool or blockchain) */
532 static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
533 /** Transaction conflicts with a transaction already known */
534 static const unsigned int REJECT_CONFLICT = 0x102;
536 /** Dump the mempool to disk. */
537 void DumpMempool();
539 /** Load the mempool from disk. */
540 bool LoadMempool();
542 // The following things handle network-processing logic
543 // (and should be moved to a separate file)
545 /** Register with a network node to receive its signals */
546 void RegisterNodeSignals(CNodeSignals& nodeSignals);
547 /** Unregister a network node */
548 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
550 class PeerLogicValidation : public CValidationInterface {
551 private:
552 CConnman* connman;
554 public:
555 PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {}
557 virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload);
558 virtual void BlockChecked(const CBlock& block, const CValidationState& state);
561 struct CNodeStateStats {
562 int nMisbehavior;
563 int nSyncHeight;
564 int nCommonHeight;
565 std::vector<int> vHeightInFlight;
568 /** Get statistics from node state */
569 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
570 /** Increase a node's misbehavior score. */
571 void Misbehaving(NodeId nodeid, int howmuch);
573 /** Process protocol messages received from a given node */
574 bool ProcessMessages(CNode* pfrom, CConnman& connman);
576 * Send queued protocol messages to be sent to a give node.
578 * @param[in] pto The node which we are sending messages to.
579 * @param[in] connman The connection manager for that node.
581 bool SendMessages(CNode* pto, CConnman& connman);
583 #endif // BITCOIN_MAIN_H