[gitian] Use vm-builder_0.12.4+bzr494 on Debian
[bitcoinplatinum.git] / src / main.h
bloba82e3faa4549c4d330584174a9ab1eb67c932430
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.
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 CInv;
35 class CScriptCheck;
36 class CTxMemPool;
37 class CValidationInterface;
38 class CValidationState;
40 struct CNodeStateStats;
42 /** Default for accepting alerts from the P2P network. */
43 static const bool DEFAULT_ALERTS = true;
44 /** Default for -minrelaytxfee, minimum relay fee for transactions */
45 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
46 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
47 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
48 /** Default for -limitancestorcount, max number of in-mempool ancestors */
49 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 100;
50 /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
51 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 900;
52 /** Default for -limitdescendantcount, max number of in-mempool descendants */
53 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 1000;
54 /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
55 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 2500;
56 /** Default for -maxmempool, maximum megabytes of mempool memory usage */
57 static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE = 300;
58 /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
59 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 72;
60 /** The maximum size of a blk?????.dat file (since 0.8) */
61 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
62 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
63 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
64 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
65 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
66 /** Maximum number of script-checking threads allowed */
67 static const int MAX_SCRIPTCHECK_THREADS = 16;
68 /** -par default (number of script-checking threads, 0 = auto) */
69 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
70 /** Number of blocks that can be requested at any given time from a single peer. */
71 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
72 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
73 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
74 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
75 * less than this number, we reached its tip. Changing this value is a protocol upgrade. */
76 static const unsigned int MAX_HEADERS_RESULTS = 2000;
77 /** Size of the "block download window": how far ahead of our current height do we fetch?
78 * Larger windows tolerate larger download speed differences between peer, but increase the potential
79 * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
80 * harder). We'll probably want to make this a per-peer adaptive value at some point. */
81 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
82 /** Time to wait (in seconds) between writing blocks/block index to disk. */
83 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
84 /** Time to wait (in seconds) between flushing chainstate to disk. */
85 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
86 /** Maximum length of reject messages. */
87 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
89 struct BlockHasher
91 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
94 extern CScript COINBASE_FLAGS;
95 extern CCriticalSection cs_main;
96 extern CTxMemPool mempool;
97 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
98 extern BlockMap mapBlockIndex;
99 extern uint64_t nLastBlockTx;
100 extern uint64_t nLastBlockSize;
101 extern const std::string strMessageMagic;
102 extern CWaitableCriticalSection csBestBlock;
103 extern CConditionVariable cvBlockChange;
104 extern bool fImporting;
105 extern bool fReindex;
106 extern int nScriptCheckThreads;
107 extern bool fTxIndex;
108 extern bool fIsBareMultisigStd;
109 extern bool fRequireStandard;
110 extern bool fCheckBlockIndex;
111 extern bool fCheckpointsEnabled;
112 extern size_t nCoinCacheUsage;
113 extern CFeeRate minRelayTxFee;
114 extern bool fAlerts;
116 /** Best header we've seen so far (used for getheaders queries' starting points). */
117 extern CBlockIndex *pindexBestHeader;
119 /** Minimum disk space required - used in CheckDiskSpace() */
120 static const uint64_t nMinDiskSpace = 52428800;
122 /** Pruning-related variables and constants */
123 /** True if any block files have ever been pruned. */
124 extern bool fHavePruned;
125 /** True if we're running in -prune mode. */
126 extern bool fPruneMode;
127 /** Number of MiB of block files that we're trying to stay below. */
128 extern uint64_t nPruneTarget;
129 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
130 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
132 static const signed int DEFAULT_CHECKBLOCKS = MIN_BLOCKS_TO_KEEP;
133 static const unsigned int DEFAULT_CHECKLEVEL = 3;
135 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
136 // At 1MB per block, 288 blocks = 288MB.
137 // Add 15% for Undo data = 331MB
138 // Add 20% for Orphan block rate = 397MB
139 // We want the low water mark after pruning to be at least 397 MB and since we prune in
140 // full block file chunks, we need the high water mark which triggers the prune to be
141 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
142 // Setting the target to > than 550MB will make it likely we can respect the target.
143 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
145 /** Register with a network node to receive its signals */
146 void RegisterNodeSignals(CNodeSignals& nodeSignals);
147 /** Unregister a network node */
148 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
150 /**
151 * Process an incoming block. This only returns after the best known valid
152 * block is made active. Note that it does not, however, guarantee that the
153 * specific block passed to it has been checked for validity!
155 * @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.
156 * @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.
157 * @param[in] pblock The block we want to process.
158 * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
159 * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
160 * @return True if state.IsValid()
162 bool ProcessNewBlock(CValidationState &state, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp);
163 /** Check whether enough disk space is available for an incoming block */
164 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
165 /** Open a block file (blk?????.dat) */
166 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
167 /** Open an undo file (rev?????.dat) */
168 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
169 /** Translation to a filesystem path */
170 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
171 /** Import blocks from an external file */
172 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
173 /** Initialize a new block tree database + block data on disk */
174 bool InitBlockIndex();
175 /** Load the block tree and coins database from disk */
176 bool LoadBlockIndex();
177 /** Unload database information */
178 void UnloadBlockIndex();
179 /** Process protocol messages received from a given node */
180 bool ProcessMessages(CNode* pfrom);
182 * Send queued protocol messages to be sent to a give node.
184 * @param[in] pto The node which we are sending messages to.
185 * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
187 bool SendMessages(CNode* pto, bool fSendTrickle);
188 /** Run an instance of the script checking thread */
189 void ThreadScriptCheck();
190 /** Try to detect Partition (network isolation) attacks against us */
191 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
192 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
193 bool IsInitialBlockDownload();
194 /** Format a string that describes several potential problems detected by the core */
195 std::string GetWarnings(const std::string& strFor);
196 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
197 bool GetTransaction(const uint256 &hash, CTransaction &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false);
198 /** Find the best known block, and make it the tip of the block chain */
199 bool ActivateBestChain(CValidationState &state, const CBlock *pblock = NULL);
200 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
203 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
204 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
205 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
206 * (which in this case means the blockchain must be re-downloaded.)
208 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
209 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
210 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
211 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
212 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
213 * A db flag records the fact that at least some block files have been pruned.
215 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
217 void FindFilesToPrune(std::set<int>& setFilesToPrune);
220 * Actually unlink the specified files
222 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
224 /** Create a new block index entry for a given block hash */
225 CBlockIndex * InsertBlockIndex(uint256 hash);
226 /** Get statistics from node state */
227 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
228 /** Increase a node's misbehavior score. */
229 void Misbehaving(NodeId nodeid, int howmuch);
230 /** Flush all state, indexes and buffers to disk. */
231 void FlushStateToDisk();
232 /** Prune block files and flush state to disk. */
233 void PruneAndFlush();
235 /** (try to) add transaction to memory pool **/
236 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
237 bool* pfMissingInputs, bool fOverrideMempoolLimit=false, bool fRejectAbsurdFee=false);
240 struct CNodeStateStats {
241 int nMisbehavior;
242 int nSyncHeight;
243 int nCommonHeight;
244 std::vector<int> vHeightInFlight;
247 struct CDiskTxPos : public CDiskBlockPos
249 unsigned int nTxOffset; // after header
251 ADD_SERIALIZE_METHODS;
253 template <typename Stream, typename Operation>
254 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
255 READWRITE(*(CDiskBlockPos*)this);
256 READWRITE(VARINT(nTxOffset));
259 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
262 CDiskTxPos() {
263 SetNull();
266 void SetNull() {
267 CDiskBlockPos::SetNull();
268 nTxOffset = 0;
273 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
275 /**
276 * Count ECDSA signature operations the old-fashioned (pre-0.6) way
277 * @return number of sigops this transaction's outputs will produce when spent
278 * @see CTransaction::FetchInputs
280 unsigned int GetLegacySigOpCount(const CTransaction& tx);
283 * Count ECDSA signature operations in pay-to-script-hash inputs.
285 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
286 * @return maximum number of sigops required to validate this transaction's inputs
287 * @see CTransaction::FetchInputs
289 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
293 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
294 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
295 * instead of being performed inline.
297 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
298 unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks = NULL);
300 /** Apply the effects of this transaction on the UTXO set represented by view */
301 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight);
303 /** Context-independent validity checks */
304 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
307 * Check if transaction is final and can be included in a block with the
308 * specified height and time. Consensus critical.
310 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
313 * Check if transaction will be final in the next block to be created.
315 * Calls IsFinalTx() with current block height and appropriate block time.
317 * See consensus/consensus.h for flag definitions.
319 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
321 /**
322 * Closure representing one script verification
323 * Note that this stores references to the spending transaction
325 class CScriptCheck
327 private:
328 CScript scriptPubKey;
329 const CTransaction *ptxTo;
330 unsigned int nIn;
331 unsigned int nFlags;
332 bool cacheStore;
333 ScriptError error;
335 public:
336 CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
337 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) :
338 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
339 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { }
341 bool operator()();
343 void swap(CScriptCheck &check) {
344 scriptPubKey.swap(check.scriptPubKey);
345 std::swap(ptxTo, check.ptxTo);
346 std::swap(nIn, check.nIn);
347 std::swap(nFlags, check.nFlags);
348 std::swap(cacheStore, check.cacheStore);
349 std::swap(error, check.error);
352 ScriptError GetScriptError() const { return error; }
356 /** Functions for disk access for blocks */
357 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
358 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
359 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
361 /** Functions for validating blocks and updating the block tree */
363 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
364 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
365 * will be true if no problems were found. Otherwise, the return value will be false in case
366 * of problems. Note that in any case, coins may be modified. */
367 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
369 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
370 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
372 /** Context-independent validity checks */
373 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
374 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
376 /** Context-dependent validity checks */
377 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
378 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
380 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
381 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
383 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
384 bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
385 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex **ppindex= NULL);
388 class CBlockFileInfo
390 public:
391 unsigned int nBlocks; //! number of blocks stored in file
392 unsigned int nSize; //! number of used bytes of block file
393 unsigned int nUndoSize; //! number of used bytes in the undo file
394 unsigned int nHeightFirst; //! lowest height of block in file
395 unsigned int nHeightLast; //! highest height of block in file
396 uint64_t nTimeFirst; //! earliest time of block in file
397 uint64_t nTimeLast; //! latest time of block in file
399 ADD_SERIALIZE_METHODS;
401 template <typename Stream, typename Operation>
402 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
403 READWRITE(VARINT(nBlocks));
404 READWRITE(VARINT(nSize));
405 READWRITE(VARINT(nUndoSize));
406 READWRITE(VARINT(nHeightFirst));
407 READWRITE(VARINT(nHeightLast));
408 READWRITE(VARINT(nTimeFirst));
409 READWRITE(VARINT(nTimeLast));
412 void SetNull() {
413 nBlocks = 0;
414 nSize = 0;
415 nUndoSize = 0;
416 nHeightFirst = 0;
417 nHeightLast = 0;
418 nTimeFirst = 0;
419 nTimeLast = 0;
422 CBlockFileInfo() {
423 SetNull();
426 std::string ToString() const;
428 /** update statistics (does not update nSize) */
429 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
430 if (nBlocks==0 || nHeightFirst > nHeightIn)
431 nHeightFirst = nHeightIn;
432 if (nBlocks==0 || nTimeFirst > nTimeIn)
433 nTimeFirst = nTimeIn;
434 nBlocks++;
435 if (nHeightIn > nHeightLast)
436 nHeightLast = nHeightIn;
437 if (nTimeIn > nTimeLast)
438 nTimeLast = nTimeIn;
442 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
443 class CVerifyDB {
444 public:
445 CVerifyDB();
446 ~CVerifyDB();
447 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
450 /** Find the last common block between the parameter chain and a locator. */
451 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
453 /** Mark a block as invalid. */
454 bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex);
456 /** Remove invalidity status from a block and its descendants. */
457 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
459 /** The currently-connected chain of blocks. */
460 extern CChain chainActive;
462 /** Global variable that points to the active CCoinsView (protected by cs_main) */
463 extern CCoinsViewCache *pcoinsTip;
465 /** Global variable that points to the active block tree (protected by cs_main) */
466 extern CBlockTreeDB *pblocktree;
469 * Return the spend height, which is one more than the inputs.GetBestBlock().
470 * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
471 * This is also true for mempool checks.
473 int GetSpendHeight(const CCoinsViewCache& inputs);
475 /** Reject codes greater or equal to this can be returned by AcceptToMemPool
476 * for transactions, to signal internal conditions. They cannot and should not
477 * be sent over the P2P network.
479 static const unsigned int REJECT_INTERNAL = 0x100;
480 /** Too high fee. Can not be triggered by P2P transactions */
481 static const unsigned int REJECT_HIGHFEE = 0x100;
482 /** Transaction is already known (either in mempool or blockchain) */
483 static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
484 /** Transaction conflicts with a transaction already known */
485 static const unsigned int REJECT_CONFLICT = 0x102;
487 #endif // BITCOIN_MAIN_H