]> Git Repo - VerusCoin.git/blob - src/main.h
Merge pull request #128 from miketout/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/serverchecker.h"
24 #include "script/standard.h"
25 #include "script/script_ext.h"
26 #include "spentindex.h"
27 #include "sync.h"
28 #include "tinyformat.h"
29 #include "txmempool.h"
30 #include "uint256.h"
31 #include "cheatcatcher.h"
32
33 #include <algorithm>
34 #include <exception>
35 #include <map>
36 #include <set>
37 #include <stdint.h>
38 #include <string>
39 #include <utility>
40 #include <vector>
41
42 #include <boost/unordered_map.hpp>
43
44 class CBlockIndex;
45 class CBlockTreeDB;
46 class CBloomFilter;
47 class CInv;
48 class CScriptCheck;
49 class CValidationInterface;
50 class CValidationState;
51 class PrecomputedTransactionData;
52
53 struct CNodeStateStats;
54 #define DEFAULT_MEMPOOL_EXPIRY 1
55 #define _COINBASE_MATURITY 100
56
57 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
58 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = MAX_BLOCK_SIZE;
59 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
60 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
61 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = DEFAULT_BLOCK_MAX_SIZE / 2;
62 /** Default for accepting alerts from the P2P network. */
63 static const bool DEFAULT_ALERTS = true;
64 /** Minimum alert priority for enabling safe mode. */
65 static const int ALERT_PRIORITY_SAFE_MODE = 4000;
66 /** Maximum reorg length we will accept before we shut down and alert the user. */
67 static const unsigned int MAX_REORG_LENGTH = _COINBASE_MATURITY - 1;
68 /** Maximum number of signature check operations in an IsStandard() P2SH script */
69 static const unsigned int MAX_P2SH_SIGOPS = 15;
70 /** The maximum number of sigops we're willing to relay/mine in a single tx */
71 static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
72 /** Default for -minrelaytxfee, minimum relay fee for transactions */
73 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 100;
74 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
75 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
76 /** Default for -txexpirydelta, in number of blocks */
77 static const unsigned int DEFAULT_TX_EXPIRY_DELTA = 20;
78 /** The maximum size of a blk?????.dat file (since 0.8) */
79 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
80 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
81 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
82 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
83 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
84 /** Maximum number of script-checking threads allowed */
85 static const int MAX_SCRIPTCHECK_THREADS = 16;
86 /** -par default (number of script-checking threads, 0 = auto) */
87 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
88 /** Number of blocks that can be requested at any given time from a single peer. */
89 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
90 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
91 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
92 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
93  *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
94 static const unsigned int MAX_HEADERS_RESULTS = 160;
95 /** Size of the "block download window": how far ahead of our current height do we fetch?
96  *  Larger windows tolerate larger download speed differences between peer, but increase the potential
97  *  degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
98  *  harder). We'll probably want to make this a per-peer adaptive value at some point. */
99 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
100 /** Time to wait (in seconds) between writing blocks/block index to disk. */
101 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
102 /** Time to wait (in seconds) between flushing chainstate to disk. */
103 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
104 /** Maximum length of reject messages. */
105 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
106 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
107
108 //static const bool DEFAULT_ADDRESSINDEX = false;
109 //static const bool DEFAULT_SPENTINDEX = false;
110 #define DEFAULT_ADDRESSINDEX (GetArg("-ac_cc",0) != 0 || GetArg("-ac_ccactivate",0) != 0)
111 #define DEFAULT_SPENTINDEX (GetArg("-ac_cc",0) != 0 || GetArg("-ac_ccactivate",0) != 0)
112 static const bool DEFAULT_TIMESTAMPINDEX = false;
113 static const unsigned int DEFAULT_DB_MAX_OPEN_FILES = 1000;
114 static const bool DEFAULT_DB_COMPRESSION = true;
115
116 // Sanity check the magic numbers when we change them
117 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE);
118 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE);
119
120 #define equihash_parameters_acceptable(N, K) \
121     ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \
122      MAX_PROTOCOL_MESSAGE_LENGTH-1000)
123
124 struct BlockHasher
125 {
126     size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
127 };
128
129 extern unsigned int expiryDelta;
130 extern CScript COINBASE_FLAGS;
131 extern CCriticalSection cs_main;
132 extern CTxMemPool mempool;
133 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
134 extern BlockMap mapBlockIndex;
135 extern uint64_t nLastBlockTx;
136 extern uint64_t nLastBlockSize;
137 extern const std::string strMessageMagic;
138 extern CWaitableCriticalSection csBestBlock;
139 extern CConditionVariable cvBlockChange;
140 extern bool fExperimentalMode;
141 extern bool fImporting;
142 extern bool fReindex;
143 extern int nScriptCheckThreads;
144 extern bool fTxIndex;
145 extern bool fIsBareMultisigStd;
146 extern bool fCheckBlockIndex;
147 extern bool fCheckpointsEnabled;
148 // TODO: remove this flag by structuring our code such that
149 // it is unneeded for testing
150 extern bool fCoinbaseEnforcedProtectionEnabled;
151 extern size_t nCoinCacheUsage;
152 extern CFeeRate minRelayTxFee;
153 extern bool fAlerts;
154 extern int64_t nMaxTipAge;
155
156 /** Best header we've seen so far (used for getheaders queries' starting points). */
157 extern CBlockIndex *pindexBestHeader;
158
159 /** Minimum disk space required - used in CheckDiskSpace() */
160 static const uint64_t nMinDiskSpace = 52428800;
161
162 /** Pruning-related variables and constants */
163 /** True if any block files have ever been pruned. */
164 extern bool fHavePruned;
165 /** True if we're running in -prune mode. */
166 extern bool fPruneMode;
167 /** Number of MiB of block files that we're trying to stay below. */
168 extern uint64_t nPruneTarget;
169 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
170 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
171
172 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
173 // At 1MB per block, 288 blocks = 288MB.
174 // Add 15% for Undo data = 331MB
175 // Add 20% for Orphan block rate = 397MB
176 // We want the low water mark after pruning to be at least 397 MB and since we prune in
177 // full block file chunks, we need the high water mark which triggers the prune to be
178 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
179 // Setting the target to > than 550MB will make it likely we can respect the target.
180 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
181
182 /** Register with a network node to receive its signals */
183 void RegisterNodeSignals(CNodeSignals& nodeSignals);
184 /** Unregister a network node */
185 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
186
187 /** 
188  * Process an incoming block. This only returns after the best known valid
189  * block is made active. Note that it does not, however, guarantee that the
190  * specific block passed to it has been checked for validity!
191  * 
192  * @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.
193  * @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.
194  * @param[in]   pblock  The block we want to process.
195  * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
196  * @param[out]  dbp     If pblock is stored to disk (or already there), this will be set to its location.
197  * @return True if state.IsValid()
198  */
199 bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp);
200 /** Check whether enough disk space is available for an incoming block */
201 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
202 /** Open a block file (blk?????.dat) */
203 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
204 /** Open an undo file (rev?????.dat) */
205 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
206 /** Translation to a filesystem path */
207 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
208 /** Import blocks from an external file */
209 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
210 /** Initialize a new block tree database + block data on disk */
211 bool InitBlockIndex();
212 /** Load the block tree and coins database from disk */
213 bool LoadBlockIndex();
214 /** Unload database information */
215 void UnloadBlockIndex();
216 /** Process protocol messages received from a given node */
217 bool ProcessMessages(CNode* pfrom);
218 /**
219  * Send queued protocol messages to be sent to a give node.
220  *
221  * @param[in]   pto             The node which we are sending messages to.
222  * @param[in]   fSendTrickle    When true send the trickled data, otherwise trickle the data until true.
223  */
224 bool SendMessages(CNode* pto, bool fSendTrickle);
225 /** Run an instance of the script checking thread */
226 void ThreadScriptCheck();
227 /** Try to detect Partition (network isolation) attacks against us */
228 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
229 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
230 bool IsInitialBlockDownload();
231 /** Check if the daemon is in sync, if not, it returns 1 or if due to best header only, the difference in best
232  * header and activeChain tip
233  */
234 int IsNotInSync();
235 /** Format a string that describes several potential problems detected by the core */
236 std::string GetWarnings(const std::string& strFor);
237 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
238 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
239 /** Find the best known block, and make it the tip of the block chain */
240 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
241 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
242
243 /**
244  * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
245  * The user sets the target (in MB) on the command line or in config file.  This will be run on startup and whenever new
246  * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
247  * (which in this case means the blockchain must be re-downloaded.)
248  *
249  * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
250  * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
251  * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
252  * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
253  * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
254  * A db flag records the fact that at least some block files have been pruned.
255  *
256  * @param[out]   setFilesToPrune   The set of file indices that can be unlinked will be returned
257  */
258 void FindFilesToPrune(std::set<int>& setFilesToPrune);
259
260 /**
261  *  Actually unlink the specified files
262  */
263 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
264
265 /** Create a new block index entry for a given block hash */
266 CBlockIndex * InsertBlockIndex(uint256 hash);
267 /** Get statistics from node state */
268 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
269 /** Increase a node's misbehavior score. */
270 void Misbehaving(NodeId nodeid, int howmuch);
271 /** Flush all state, indexes and buffers to disk. */
272 void FlushStateToDisk();
273 /** Prune block files and flush state to disk. */
274 void PruneAndFlush();
275
276 /** (try to) add transaction to memory pool **/
277 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
278                         bool* pfMissingInputs, bool fRejectAbsurdFee=false, int dosLevel=-1);
279
280
281 struct CNodeStateStats {
282     int nMisbehavior;
283     int nSyncHeight;
284     int nCommonHeight;
285     std::vector<int> vHeightInFlight;
286 };
287
288 struct CTimestampIndexIteratorKey {
289     unsigned int timestamp;
290
291     size_t GetSerializeSize(int nType, int nVersion) const {
292         return 4;
293     }
294     template<typename Stream>
295     void Serialize(Stream& s) const {
296         ser_writedata32be(s, timestamp);
297     }
298     template<typename Stream>
299     void Unserialize(Stream& s) {
300         timestamp = ser_readdata32be(s);
301     }
302
303     CTimestampIndexIteratorKey(unsigned int time) {
304         timestamp = time;
305     }
306
307     CTimestampIndexIteratorKey() {
308         SetNull();
309     }
310
311     void SetNull() {
312         timestamp = 0;
313     }
314 };
315
316 struct CTimestampIndexKey {
317     unsigned int timestamp;
318     uint256 blockHash;
319
320     size_t GetSerializeSize(int nType, int nVersion) const {
321         return 36;
322     }
323     template<typename Stream>
324     void Serialize(Stream& s) const {
325         ser_writedata32be(s, timestamp);
326         blockHash.Serialize(s);
327     }
328     template<typename Stream>
329     void Unserialize(Stream& s) {
330         timestamp = ser_readdata32be(s);
331         blockHash.Unserialize(s);
332     }
333
334     CTimestampIndexKey(unsigned int time, uint256 hash) {
335         timestamp = time;
336         blockHash = hash;
337     }
338
339     CTimestampIndexKey() {
340         SetNull();
341     }
342
343     void SetNull() {
344         timestamp = 0;
345         blockHash.SetNull();
346     }
347 };
348
349 struct CTimestampBlockIndexKey {
350     uint256 blockHash;
351
352     size_t GetSerializeSize(int nType, int nVersion) const {
353         return 32;
354     }
355
356     template<typename Stream>
357     void Serialize(Stream& s) const {
358         blockHash.Serialize(s);
359     }
360
361     template<typename Stream>
362     void Unserialize(Stream& s) {
363         blockHash.Unserialize(s);
364     }
365
366     CTimestampBlockIndexKey(uint256 hash) {
367         blockHash = hash;
368     }
369
370     CTimestampBlockIndexKey() {
371         SetNull();
372     }
373
374     void SetNull() {
375         blockHash.SetNull();
376     }
377 };
378
379 struct CTimestampBlockIndexValue {
380     unsigned int ltimestamp;
381     size_t GetSerializeSize(int nType, int nVersion) const {
382         return 4;
383     }
384
385     template<typename Stream>
386     void Serialize(Stream& s) const {
387         ser_writedata32be(s, ltimestamp);
388     }
389
390     template<typename Stream>
391     void Unserialize(Stream& s) {
392         ltimestamp = ser_readdata32be(s);
393     }
394
395     CTimestampBlockIndexValue (unsigned int time) {
396         ltimestamp = time;
397     }
398
399     CTimestampBlockIndexValue() {
400         SetNull();
401     }
402
403     void SetNull() {
404         ltimestamp = 0;
405     }
406 };
407
408 struct CAddressUnspentKey {
409     unsigned int type;
410     uint160 hashBytes;
411     uint256 txhash;
412     size_t index;
413
414     size_t GetSerializeSize(int nType, int nVersion) const {
415         return 57;
416     }
417     template<typename Stream>
418     void Serialize(Stream& s) const {
419         ser_writedata8(s, type);
420         hashBytes.Serialize(s);
421         txhash.Serialize(s);
422         ser_writedata32(s, index);
423     }
424     template<typename Stream>
425     void Unserialize(Stream& s) {
426         type = ser_readdata8(s);
427         hashBytes.Unserialize(s);
428         txhash.Unserialize(s);
429         index = ser_readdata32(s);
430     }
431
432     CAddressUnspentKey(unsigned int addressType, uint160 addressHash, uint256 txid, size_t indexValue) {
433         type = addressType;
434         hashBytes = addressHash;
435         txhash = txid;
436         index = indexValue;
437     }
438
439     CAddressUnspentKey() {
440         SetNull();
441     }
442
443     void SetNull() {
444         type = 0;
445         hashBytes.SetNull();
446         txhash.SetNull();
447         index = 0;
448     }
449 };
450
451 struct  CAddressUnspentValue {
452     CAmount satoshis;
453     CScript script;
454     int blockHeight;
455
456     ADD_SERIALIZE_METHODS;
457
458     template <typename Stream, typename Operation>
459     inline void SerializationOp(Stream& s, Operation ser_action) {
460         READWRITE(satoshis);
461         READWRITE(*(CScriptBase*)(&script));
462         READWRITE(blockHeight);
463     }
464
465     CAddressUnspentValue(CAmount sats, CScript scriptPubKey, int height) {
466         satoshis = sats;
467         script = scriptPubKey;
468         blockHeight = height;
469     }
470
471     CAddressUnspentValue() {
472         SetNull();
473     }
474
475     void SetNull() {
476         satoshis = -1;
477         script.clear();
478         blockHeight = 0;
479     }
480
481     bool IsNull() const {
482         return (satoshis == -1);
483     }
484 };
485
486 struct CAddressIndexKey {
487     unsigned int type;
488     uint160 hashBytes;
489     int blockHeight;
490     unsigned int txindex;
491     uint256 txhash;
492     size_t index;
493     bool spending;
494
495     size_t GetSerializeSize(int nType, int nVersion) const {
496         return 66;
497     }
498     template<typename Stream>
499     void Serialize(Stream& s) const {
500         ser_writedata8(s, type);
501         hashBytes.Serialize(s);
502         // Heights are stored big-endian for key sorting in LevelDB
503         ser_writedata32be(s, blockHeight);
504         ser_writedata32be(s, txindex);
505         txhash.Serialize(s);
506         ser_writedata32(s, index);
507         char f = spending;
508         ser_writedata8(s, f);
509     }
510     template<typename Stream>
511     void Unserialize(Stream& s) {
512         type = ser_readdata8(s);
513         hashBytes.Unserialize(s);
514         blockHeight = ser_readdata32be(s);
515         txindex = ser_readdata32be(s);
516         txhash.Unserialize(s);
517         index = ser_readdata32(s);
518         char f = ser_readdata8(s);
519         spending = f;
520     }
521
522     CAddressIndexKey(unsigned int addressType, uint160 addressHash, int height, int blockindex,
523                      uint256 txid, size_t indexValue, bool isSpending) {
524         type = addressType;
525         hashBytes = addressHash;
526         blockHeight = height;
527         txindex = blockindex;
528         txhash = txid;
529         index = indexValue;
530         spending = isSpending;
531     }
532
533     CAddressIndexKey() {
534         SetNull();
535     }
536
537     void SetNull() {
538         type = 0;
539         hashBytes.SetNull();
540         blockHeight = 0;
541         txindex = 0;
542         txhash.SetNull();
543         index = 0;
544         spending = false;
545     }
546
547 };
548
549 struct CAddressIndexIteratorKey {
550     unsigned int type;
551     uint160 hashBytes;
552
553     size_t GetSerializeSize(int nType, int nVersion) const {
554         return 21;
555     }
556     template<typename Stream>
557     void Serialize(Stream& s) const {
558         ser_writedata8(s, type);
559         hashBytes.Serialize(s);
560     }
561     template<typename Stream>
562     void Unserialize(Stream& s) {
563         type = ser_readdata8(s);
564         hashBytes.Unserialize(s);
565     }
566
567     CAddressIndexIteratorKey(unsigned int addressType, uint160 addressHash) {
568         type = addressType;
569         hashBytes = addressHash;
570     }
571
572     CAddressIndexIteratorKey() {
573         SetNull();
574     }
575
576     void SetNull() {
577         type = 0;
578         hashBytes.SetNull();
579     }
580 };
581
582 struct CAddressIndexIteratorHeightKey {
583     unsigned int type;
584     uint160 hashBytes;
585     int blockHeight;
586
587     size_t GetSerializeSize(int nType, int nVersion) const {
588         return 25;
589     }
590     template<typename Stream>
591     void Serialize(Stream& s) const {
592         ser_writedata8(s, type);
593         hashBytes.Serialize(s);
594         ser_writedata32be(s, blockHeight);
595     }
596     template<typename Stream>
597     void Unserialize(Stream& s) {
598         type = ser_readdata8(s);
599         hashBytes.Unserialize(s);
600         blockHeight = ser_readdata32be(s);
601     }
602
603     CAddressIndexIteratorHeightKey(unsigned int addressType, uint160 addressHash, int height) {
604         type = addressType;
605         hashBytes = addressHash;
606         blockHeight = height;
607     }
608
609     CAddressIndexIteratorHeightKey() {
610         SetNull();
611     }
612
613     void SetNull() {
614         type = 0;
615         hashBytes.SetNull();
616         blockHeight = 0;
617     }
618 };
619
620 struct CDiskTxPos : public CDiskBlockPos
621 {
622     unsigned int nTxOffset; // after header
623
624     ADD_SERIALIZE_METHODS;
625
626     template <typename Stream, typename Operation>
627     inline void SerializationOp(Stream& s, Operation ser_action) {
628         READWRITE(*(CDiskBlockPos*)this);
629         READWRITE(VARINT(nTxOffset));
630     }
631
632     CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
633     }
634
635     CDiskTxPos() {
636         SetNull();
637     }
638
639     void SetNull() {
640         CDiskBlockPos::SetNull();
641         nTxOffset = 0;
642     }
643 };
644
645 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
646
647 /**
648  * Check transaction inputs, and make sure any
649  * pay-to-script-hash transactions are evaluating IsStandard scripts
650  * 
651  * Why bother? To avoid denial-of-service attacks; an attacker
652  * can submit a standard HASH... OP_EQUAL transaction,
653  * which will get accepted into blocks. The redemption
654  * script can be anything; an attacker could use a very
655  * expensive-to-check-upon-redemption script like:
656  *   DUP CHECKSIG DROP ... repeated 100 times... OP_1
657  */
658
659 /** 
660  * Check for standard transaction types
661  * @param[in] mapInputs    Map of previous transactions that have outputs we're spending
662  * @return True if all inputs (scriptSigs) use only standard transaction forms
663  */
664 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
665
666 /** 
667  * Count ECDSA signature operations the old-fashioned (pre-0.6) way
668  * @return number of sigops this transaction's outputs will produce when spent
669  * @see CTransaction::FetchInputs
670  */
671 unsigned int GetLegacySigOpCount(const CTransaction& tx);
672
673 /**
674  * Count ECDSA signature operations in pay-to-script-hash inputs.
675  * 
676  * @param[in] mapInputs Map of previous transactions that have outputs we're spending
677  * @return maximum number of sigops required to validate this transaction's inputs
678  * @see CTransaction::FetchInputs
679  */
680 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
681
682
683 /**
684  * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
685  * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
686  * instead of being performed inline.
687  */
688 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
689                            unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata,
690                            const Consensus::Params& consensusParams, uint32_t consensusBranchId,
691                            std::vector<CScriptCheck> *pvChecks = NULL);
692
693 /** Check a transaction contextually against a set of consensus rules */
694 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, int nHeight, int dosLevel,
695                                 bool (*isInitBlockDownload)() = IsInitialBlockDownload);
696
697 /** Apply the effects of this transaction on the UTXO set represented by view */
698 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
699
700 /** Transaction validation functions */
701
702 /** Context-independent validity checks */
703 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
704 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
705
706 /** Check for standard transaction types
707  * @return True if all outputs (scriptPubKeys) use only standard transaction forms
708  */
709 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
710
711 namespace Consensus {
712
713 /**
714  * Check whether all inputs of this transaction are valid (no double spends and amounts)
715  * This does not modify the UTXO set. This does not check scripts and sigs.
716  * Preconditions: tx.IsCoinBase() is false.
717  */
718 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
719
720 } // namespace Consensus
721
722 /**
723  * Check if transaction is final and can be included in a block with the
724  * specified height and time. Consensus critical.
725  */
726 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
727
728 /**
729  * Check if transaction is expired and can be included in a block with the
730  * specified height. Consensus critical.
731  */
732 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
733
734 /**
735  * Check if transaction will be final in the next block to be created.
736  *
737  * Calls IsFinalTx() with current block height and appropriate block time.
738  *
739  * See consensus/consensus.h for flag definitions.
740  */
741 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
742
743 /** 
744  * Closure representing one script verification
745  * Note that this stores references to the spending transaction 
746  */
747 class CScriptCheck
748 {
749 private:
750     CScript scriptPubKey;
751     CAmount amount;
752     const CTransaction *ptxTo;
753     unsigned int nIn;
754     unsigned int nFlags;
755     bool cacheStore;
756     uint32_t consensusBranchId;
757     ScriptError error;
758     PrecomputedTransactionData *txdata;
759
760 public:
761     CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), consensusBranchId(0), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
762     CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, uint32_t consensusBranchIdIn, PrecomputedTransactionData* txdataIn) :
763         scriptPubKey(CCoinsViewCache::GetSpendFor(&txFromIn, txToIn.vin[nInIn])), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
764         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), consensusBranchId(consensusBranchIdIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
765
766     bool operator()();
767
768     void swap(CScriptCheck &check) {
769         scriptPubKey.swap(check.scriptPubKey);
770         std::swap(ptxTo, check.ptxTo);
771         std::swap(amount, check.amount);
772         std::swap(nIn, check.nIn);
773         std::swap(nFlags, check.nFlags);
774         std::swap(cacheStore, check.cacheStore);
775         std::swap(consensusBranchId, check.consensusBranchId);
776         std::swap(error, check.error);
777         std::swap(txdata, check.txdata);
778     }
779
780     ScriptError GetScriptError() const { return error; }
781 };
782
783 bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector<std::pair<uint256, unsigned int> > &hashes);
784 bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value);
785 bool GetAddressIndex(uint160 addressHash, int type,
786                      std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
787                      int start = 0, int end = 0);
788 bool GetAddressUnspent(uint160 addressHash, int type,
789                        std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs);
790
791 /** Functions for disk access for blocks */
792 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
793 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW);
794 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW);
795
796
797 /** Functions for validating blocks and updating the block tree */
798
799 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
800  *  In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
801  *  will be true if no problems were found. Otherwise, the return value will be false in case
802  *  of problems. Note that in any case, coins may be modified. */
803 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
804
805 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
806 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false,bool fCheckPOW = false);
807
808 /** Context-independent validity checks */
809 bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
810 bool CheckBlock(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
811                 libzcash::ProofVerifier& verifier,
812                 bool fCheckPOW = true, bool fCheckMerkleRoot = true);
813
814 /** Context-dependent validity checks */
815 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
816 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
817
818 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
819 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
820
821 /**
822  * Store block on disk.
823  * JoinSplit proofs are never verified, because:
824  * - AcceptBlock doesn't perform script checks either.
825  * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere.
826  * If dbp is non-NULL, the file is known to already reside on disk
827  */
828 bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
829 bool AcceptBlockHeader(int32_t *futureblockp,const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
830
831
832
833 /**
834  * When there are blocks in the active chain with missing data (e.g. if the
835  * activation height and branch ID of a particular upgrade have been altered),
836  * rewind the chainstate and remove them from the block index.
837  *
838  * clearWitnessCaches is an output parameter that will be set to true iff
839  * witness caches should be cleared in order to handle an intended long rewind.
840  */
841 bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches);
842
843 class CBlockFileInfo
844 {
845 public:
846     unsigned int nBlocks;      //! number of blocks stored in file
847     unsigned int nSize;        //! number of used bytes of block file
848     unsigned int nUndoSize;    //! number of used bytes in the undo file
849     unsigned int nHeightFirst; //! lowest height of block in file
850     unsigned int nHeightLast;  //! highest height of block in file
851     uint64_t nTimeFirst;         //! earliest time of block in file
852     uint64_t nTimeLast;          //! latest time of block in file
853
854     ADD_SERIALIZE_METHODS;
855
856     template <typename Stream, typename Operation>
857     inline void SerializationOp(Stream& s, Operation ser_action) {
858         READWRITE(VARINT(nBlocks));
859         READWRITE(VARINT(nSize));
860         READWRITE(VARINT(nUndoSize));
861         READWRITE(VARINT(nHeightFirst));
862         READWRITE(VARINT(nHeightLast));
863         READWRITE(VARINT(nTimeFirst));
864         READWRITE(VARINT(nTimeLast));
865     }
866
867      void SetNull() {
868          nBlocks = 0;
869          nSize = 0;
870          nUndoSize = 0;
871          nHeightFirst = 0;
872          nHeightLast = 0;
873          nTimeFirst = 0;
874          nTimeLast = 0;
875      }
876
877      CBlockFileInfo() {
878          SetNull();
879      }
880
881      std::string ToString() const;
882
883      /** update statistics (does not update nSize) */
884      void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
885          if (nBlocks==0 || nHeightFirst > nHeightIn)
886              nHeightFirst = nHeightIn;
887          if (nBlocks==0 || nTimeFirst > nTimeIn)
888              nTimeFirst = nTimeIn;
889          nBlocks++;
890          if (nHeightIn > nHeightLast)
891              nHeightLast = nHeightIn;
892          if (nTimeIn > nTimeLast)
893              nTimeLast = nTimeIn;
894      }
895 };
896
897 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
898 class CVerifyDB {
899 public:
900     CVerifyDB();
901     ~CVerifyDB();
902     bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
903 };
904
905 /** Find the last common block between the parameter chain and a locator. */
906 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
907
908 /** Mark a block as invalid. */
909 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
910
911 /** Remove invalidity status from a block and its descendants. */
912 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
913
914 /** The currently-connected chain of blocks (protected by cs_main). */
915 extern CChain chainActive;
916
917 /** Global variable that points to the active CCoinsView (protected by cs_main) */
918 extern CCoinsViewCache *pcoinsTip;
919
920 /** Global variable that points to the active block tree (protected by cs_main) */
921 extern CBlockTreeDB *pblocktree;
922
923 /**
924  * Return the spend height, which is one more than the inputs.GetBestBlock().
925  * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
926  * This is also true for mempool checks.
927  */
928 int GetSpendHeight(const CCoinsViewCache& inputs);
929
930 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at height */
931 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight);
932
933 #endif // BITCOIN_MAIN_H
This page took 0.079863 seconds and 4 git commands to generate.