]> Git Repo - VerusCoin.git/blob - src/main.h
Merge pull request #5 from jl777/dev
[VerusCoin.git] / src / main.h
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.
5
6 #ifndef BITCOIN_MAIN_H
7 #define BITCOIN_MAIN_H
8
9 #if defined(HAVE_CONFIG_H)
10 #include "config/bitcoin-config.h"
11 #endif
12
13 #include "amount.h"
14 #include "chain.h"
15 #include "chainparams.h"
16 #include "coins.h"
17 #include "consensus/consensus.h"
18 #include "consensus/upgrades.h"
19 #include "net.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
22 #include "script/script.h"
23 #include "script/sigcache.h"
24 #include "script/standard.h"
25 #include "sync.h"
26 #include "tinyformat.h"
27 #include "txmempool.h"
28 #include "uint256.h"
29
30 #include <algorithm>
31 #include <exception>
32 #include <map>
33 #include <set>
34 #include <stdint.h>
35 #include <string>
36 #include <utility>
37 #include <vector>
38
39 #include <boost/unordered_map.hpp>
40
41 class CBlockIndex;
42 class CBlockTreeDB;
43 class CBloomFilter;
44 class CInv;
45 class CScriptCheck;
46 class CValidationInterface;
47 class CValidationState;
48 class PrecomputedTransactionData;
49
50 struct CNodeStateStats;
51 #define DEFAULT_MEMPOOL_EXPIRY 1
52 #define _COINBASE_MATURITY 100
53
54 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
55 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = MAX_BLOCK_SIZE;
56 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
57 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
58 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = DEFAULT_BLOCK_MAX_SIZE / 2;
59 /** Default for accepting alerts from the P2P network. */
60 static const bool DEFAULT_ALERTS = true;
61 /** Minimum alert priority for enabling safe mode. */
62 static const int ALERT_PRIORITY_SAFE_MODE = 4000;
63 /** Maximum reorg length we will accept before we shut down and alert the user. */
64 static const unsigned int MAX_REORG_LENGTH = _COINBASE_MATURITY - 1;
65 /** Maximum number of signature check operations in an IsStandard() P2SH script */
66 static const unsigned int MAX_P2SH_SIGOPS = 15;
67 /** The maximum number of sigops we're willing to relay/mine in a single tx */
68 static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
69 /** Default for -minrelaytxfee, minimum relay fee for transactions */
70 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 100;
71 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
72 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
73 /** Default for -txexpirydelta, in number of blocks */
74 static const unsigned int DEFAULT_TX_EXPIRY_DELTA = 20;
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
81 /** Maximum number of script-checking threads allowed */
82 static const int MAX_SCRIPTCHECK_THREADS = 16;
83 /** -par default (number of script-checking threads, 0 = auto) */
84 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
85 /** Number of blocks that can be requested at any given time from a single peer. */
86 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
87 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
88 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
89 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
90  *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
91 static const unsigned int MAX_HEADERS_RESULTS = 160;
92 /** Size of the "block download window": how far ahead of our current height do we fetch?
93  *  Larger windows tolerate larger download speed differences between peer, but increase the potential
94  *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
95  *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
96 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
97 /** Time to wait (in seconds) between writing blocks/block index to disk. */
98 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
99 /** Time to wait (in seconds) between flushing chainstate to disk. */
100 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
101 /** Maximum length of reject messages. */
102 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
103
104 // Sanity check the magic numbers when we change them
105 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE);
106 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE);
107
108 #define equihash_parameters_acceptable(N, K) \
109     ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \
110      MAX_PROTOCOL_MESSAGE_LENGTH-1000)
111
112 struct BlockHasher
113 {
114     size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
115 };
116
117 extern unsigned int expiryDelta;
118 extern CScript COINBASE_FLAGS;
119 extern CCriticalSection cs_main;
120 extern CTxMemPool mempool;
121 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
122 extern BlockMap mapBlockIndex;
123 extern uint64_t nLastBlockTx;
124 extern uint64_t nLastBlockSize;
125 extern const std::string strMessageMagic;
126 extern CWaitableCriticalSection csBestBlock;
127 extern CConditionVariable cvBlockChange;
128 extern bool fExperimentalMode;
129 extern bool fImporting;
130 extern bool fReindex;
131 extern int nScriptCheckThreads;
132 extern bool fTxIndex;
133 extern bool fIsBareMultisigStd;
134 extern bool fCheckBlockIndex;
135 extern bool fCheckpointsEnabled;
136 // TODO: remove this flag by structuring our code such that
137 // it is unneeded for testing
138 extern bool fCoinbaseEnforcedProtectionEnabled;
139 extern size_t nCoinCacheUsage;
140 extern CFeeRate minRelayTxFee;
141 extern bool fAlerts;
142
143 /** Best header we've seen so far (used for getheaders queries' starting points). */
144 extern CBlockIndex *pindexBestHeader;
145
146 /** Minimum disk space required - used in CheckDiskSpace() */
147 static const uint64_t nMinDiskSpace = 52428800;
148
149 /** Pruning-related variables and constants */
150 /** True if any block files have ever been pruned. */
151 extern bool fHavePruned;
152 /** True if we're running in -prune mode. */
153 extern bool fPruneMode;
154 /** Number of MiB of block files that we're trying to stay below. */
155 extern uint64_t nPruneTarget;
156 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
157 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
158
159 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
160 // At 1MB per block, 288 blocks = 288MB.
161 // Add 15% for Undo data = 331MB
162 // Add 20% for Orphan block rate = 397MB
163 // We want the low water mark after pruning to be at least 397 MB and since we prune in
164 // full block file chunks, we need the high water mark which triggers the prune to be
165 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
166 // Setting the target to > than 550MB will make it likely we can respect the target.
167 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
168
169 /** Register with a network node to receive its signals */
170 void RegisterNodeSignals(CNodeSignals& nodeSignals);
171 /** Unregister a network node */
172 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
173
174 /** 
175  * Process an incoming block. This only returns after the best known valid
176  * block is made active. Note that it does not, however, guarantee that the
177  * specific block passed to it has been checked for validity!
178  * 
179  * @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.
180  * @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.
181  * @param[in]   pblock  The block we want to process.
182  * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
183  * @param[out]  dbp     If pblock is stored to disk (or already there), this will be set to its location.
184  * @return True if state.IsValid()
185  */
186 bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp);
187 /** Check whether enough disk space is available for an incoming block */
188 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
189 /** Open a block file (blk?????.dat) */
190 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
191 /** Open an undo file (rev?????.dat) */
192 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
193 /** Translation to a filesystem path */
194 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
195 /** Import blocks from an external file */
196 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
197 /** Initialize a new block tree database + block data on disk */
198 bool InitBlockIndex();
199 /** Load the block tree and coins database from disk */
200 bool LoadBlockIndex();
201 /** Unload database information */
202 void UnloadBlockIndex();
203 /** Process protocol messages received from a given node */
204 bool ProcessMessages(CNode* pfrom);
205 /**
206  * Send queued protocol messages to be sent to a give node.
207  *
208  * @param[in]   pto             The node which we are sending messages to.
209  * @param[in]   fSendTrickle    When true send the trickled data, otherwise trickle the data until true.
210  */
211 bool SendMessages(CNode* pto, bool fSendTrickle);
212 /** Run an instance of the script checking thread */
213 void ThreadScriptCheck();
214 /** Try to detect Partition (network isolation) attacks against us */
215 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
216 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
217 bool IsInitialBlockDownload();
218 /** Format a string that describes several potential problems detected by the core */
219 std::string GetWarnings(const std::string& strFor);
220 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
221 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
222 /** Find the best known block, and make it the tip of the block chain */
223 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
224 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
225
226 /**
227  * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
228  * The user sets the target (in MB) on the command line or in config file.  This will be run on startup and whenever new
229  * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
230  * (which in this case means the blockchain must be re-downloaded.)
231  *
232  * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
233  * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
234  * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
235  * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
236  * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
237  * A db flag records the fact that at least some block files have been pruned.
238  *
239  * @param[out]   setFilesToPrune   The set of file indices that can be unlinked will be returned
240  */
241 void FindFilesToPrune(std::set<int>& setFilesToPrune);
242
243 /**
244  *  Actually unlink the specified files
245  */
246 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
247
248 /** Create a new block index entry for a given block hash */
249 CBlockIndex * InsertBlockIndex(uint256 hash);
250 /** Get statistics from node state */
251 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
252 /** Increase a node's misbehavior score. */
253 void Misbehaving(NodeId nodeid, int howmuch);
254 /** Flush all state, indexes and buffers to disk. */
255 void FlushStateToDisk();
256 /** Prune block files and flush state to disk. */
257 void PruneAndFlush();
258
259 /** (try to) add transaction to memory pool **/
260 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
261                         bool* pfMissingInputs, bool fRejectAbsurdFee=false);
262
263
264 struct CNodeStateStats {
265     int nMisbehavior;
266     int nSyncHeight;
267     int nCommonHeight;
268     std::vector<int> vHeightInFlight;
269 };
270
271 struct CDiskTxPos : public CDiskBlockPos
272 {
273     unsigned int nTxOffset; // after header
274
275     ADD_SERIALIZE_METHODS;
276
277     template <typename Stream, typename Operation>
278     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
279         READWRITE(*(CDiskBlockPos*)this);
280         READWRITE(VARINT(nTxOffset));
281     }
282
283     CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
284     }
285
286     CDiskTxPos() {
287         SetNull();
288     }
289
290     void SetNull() {
291         CDiskBlockPos::SetNull();
292         nTxOffset = 0;
293     }
294 };
295
296
297 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
298
299 /**
300  * Check transaction inputs, and make sure any
301  * pay-to-script-hash transactions are evaluating IsStandard scripts
302  * 
303  * Why bother? To avoid denial-of-service attacks; an attacker
304  * can submit a standard HASH... OP_EQUAL transaction,
305  * which will get accepted into blocks. The redemption
306  * script can be anything; an attacker could use a very
307  * expensive-to-check-upon-redemption script like:
308  *   DUP CHECKSIG DROP ... repeated 100 times... OP_1
309  */
310
311 /** 
312  * Check for standard transaction types
313  * @param[in] mapInputs    Map of previous transactions that have outputs we're spending
314  * @return True if all inputs (scriptSigs) use only standard transaction forms
315  */
316 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
317
318 /** 
319  * Count ECDSA signature operations the old-fashioned (pre-0.6) way
320  * @return number of sigops this transaction's outputs will produce when spent
321  * @see CTransaction::FetchInputs
322  */
323 unsigned int GetLegacySigOpCount(const CTransaction& tx);
324
325 /**
326  * Count ECDSA signature operations in pay-to-script-hash inputs.
327  * 
328  * @param[in] mapInputs Map of previous transactions that have outputs we're spending
329  * @return maximum number of sigops required to validate this transaction's inputs
330  * @see CTransaction::FetchInputs
331  */
332 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
333
334
335 /**
336  * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
337  * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
338  * instead of being performed inline.
339  */
340 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
341                            unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata,
342                            const Consensus::Params& consensusParams, uint32_t consensusBranchId,
343                            std::vector<CScriptCheck> *pvChecks = NULL);
344
345 /** Check a transaction contextually against a set of consensus rules */
346 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, int nHeight, int dosLevel);
347
348 /** Apply the effects of this transaction on the UTXO set represented by view */
349 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
350
351 /** Transaction validation functions */
352
353 /** Context-independent validity checks */
354 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
355 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
356
357 /** Check for standard transaction types
358  * @return True if all outputs (scriptPubKeys) use only standard transaction forms
359  */
360 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
361
362 namespace Consensus {
363
364 /**
365  * Check whether all inputs of this transaction are valid (no double spends and amounts)
366  * This does not modify the UTXO set. This does not check scripts and sigs.
367  * Preconditions: tx.IsCoinBase() is false.
368  */
369 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
370
371 } // namespace Consensus
372
373 /**
374  * Check if transaction is final and can be included in a block with the
375  * specified height and time. Consensus critical.
376  */
377 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
378
379 /**
380  * Check if transaction is expired and can be included in a block with the
381  * specified height. Consensus critical.
382  */
383 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
384
385 /**
386  * Check if transaction will be final in the next block to be created.
387  *
388  * Calls IsFinalTx() with current block height and appropriate block time.
389  *
390  * See consensus/consensus.h for flag definitions.
391  */
392 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
393
394 /** 
395  * Closure representing one script verification
396  * Note that this stores references to the spending transaction 
397  */
398 class CScriptCheck
399 {
400 private:
401     CScript scriptPubKey;
402     CAmount amount;
403     const CTransaction *ptxTo;
404     unsigned int nIn;
405     unsigned int nFlags;
406     bool cacheStore;
407     uint32_t consensusBranchId;
408     ScriptError error;
409     PrecomputedTransactionData *txdata;
410
411 public:
412     CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), consensusBranchId(0), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
413     CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, uint32_t consensusBranchIdIn, PrecomputedTransactionData* txdataIn) :
414         scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
415         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), consensusBranchId(consensusBranchIdIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
416
417     bool operator()();
418
419     void swap(CScriptCheck &check) {
420         scriptPubKey.swap(check.scriptPubKey);
421         std::swap(ptxTo, check.ptxTo);
422         std::swap(amount, check.amount);
423         std::swap(nIn, check.nIn);
424         std::swap(nFlags, check.nFlags);
425         std::swap(cacheStore, check.cacheStore);
426         std::swap(consensusBranchId, check.consensusBranchId);
427         std::swap(error, check.error);
428         std::swap(txdata, check.txdata);
429     }
430
431     ScriptError GetScriptError() const { return error; }
432 };
433
434
435 /** Functions for disk access for blocks */
436 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
437 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
438 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
439
440
441 /** Functions for validating blocks and updating the block tree */
442
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(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
448
449 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
450 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
451
452 /** Context-independent validity checks */
453 bool CheckBlockHeader(int32_t height,CBlockIndex *pindex,const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
454 bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
455                 libzcash::ProofVerifier& verifier,
456                 bool fCheckPOW = true, bool fCheckMerkleRoot = true);
457
458 /** Context-dependent validity checks */
459 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
460 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
461
462 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
463 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
464
465 /**
466  * Store block on disk.
467  * JoinSplit proofs are never verified, because:
468  * - AcceptBlock doesn't perform script checks either.
469  * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere.
470  * If dbp is non-NULL, the file is known to already reside on disk
471  */
472 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
473 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
474
475
476
477 /**
478  * When there are blocks in the active chain with missing data (e.g. if the
479  * activation height and branch ID of a particular upgrade have been altered),
480  * rewind the chainstate and remove them from the block index.
481  */
482 bool RewindBlockIndex(const CChainParams& params);
483
484 class CBlockFileInfo
485 {
486 public:
487     unsigned int nBlocks;      //! number of blocks stored in file
488     unsigned int nSize;        //! number of used bytes of block file
489     unsigned int nUndoSize;    //! number of used bytes in the undo file
490     unsigned int nHeightFirst; //! lowest height of block in file
491     unsigned int nHeightLast;  //! highest height of block in file
492     uint64_t nTimeFirst;         //! earliest time of block in file
493     uint64_t nTimeLast;          //! latest time of block in file
494
495     ADD_SERIALIZE_METHODS;
496
497     template <typename Stream, typename Operation>
498     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
499         READWRITE(VARINT(nBlocks));
500         READWRITE(VARINT(nSize));
501         READWRITE(VARINT(nUndoSize));
502         READWRITE(VARINT(nHeightFirst));
503         READWRITE(VARINT(nHeightLast));
504         READWRITE(VARINT(nTimeFirst));
505         READWRITE(VARINT(nTimeLast));
506     }
507
508      void SetNull() {
509          nBlocks = 0;
510          nSize = 0;
511          nUndoSize = 0;
512          nHeightFirst = 0;
513          nHeightLast = 0;
514          nTimeFirst = 0;
515          nTimeLast = 0;
516      }
517
518      CBlockFileInfo() {
519          SetNull();
520      }
521
522      std::string ToString() const;
523
524      /** update statistics (does not update nSize) */
525      void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
526          if (nBlocks==0 || nHeightFirst > nHeightIn)
527              nHeightFirst = nHeightIn;
528          if (nBlocks==0 || nTimeFirst > nTimeIn)
529              nTimeFirst = nTimeIn;
530          nBlocks++;
531          if (nHeightIn > nHeightLast)
532              nHeightLast = nHeightIn;
533          if (nTimeIn > nTimeLast)
534              nTimeLast = nTimeIn;
535      }
536 };
537
538 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
539 class CVerifyDB {
540 public:
541     CVerifyDB();
542     ~CVerifyDB();
543     bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
544 };
545
546 /** Find the last common block between the parameter chain and a locator. */
547 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
548
549 /** Mark a block as invalid. */
550 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
551
552 /** Remove invalidity status from a block and its descendants. */
553 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
554
555 /** The currently-connected chain of blocks (protected by cs_main). */
556 extern CChain chainActive;
557
558 /** Global variable that points to the active CCoinsView (protected by cs_main) */
559 extern CCoinsViewCache *pcoinsTip;
560
561 /** Global variable that points to the active block tree (protected by cs_main) */
562 extern CBlockTreeDB *pblocktree;
563
564 /**
565  * Return the spend height, which is one more than the inputs.GetBestBlock().
566  * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
567  * This is also true for mempool checks.
568  */
569 int GetSpendHeight(const CCoinsViewCache& inputs);
570
571 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at height */
572 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight);
573
574 #endif // BITCOIN_MAIN_H
This page took 0.056506 seconds and 4 git commands to generate.