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.
9 #if defined(HAVE_CONFIG_H)
10 #include "config/bitcoin-config.h"
15 #include "chainparams.h"
17 #include "consensus/consensus.h"
18 #include "consensus/upgrades.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 "spentindex.h"
27 #include "tinyformat.h"
28 #include "txmempool.h"
40 #include <boost/unordered_map.hpp>
47 class CValidationInterface;
48 class CValidationState;
49 class PrecomputedTransactionData;
51 struct CNodeStateStats;
52 #define DEFAULT_MEMPOOL_EXPIRY 1
53 #define _COINBASE_MATURITY 100
55 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
56 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = MAX_BLOCK_SIZE;
57 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
58 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
59 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = DEFAULT_BLOCK_MAX_SIZE / 2;
60 /** Default for accepting alerts from the P2P network. */
61 static const bool DEFAULT_ALERTS = true;
62 /** Minimum alert priority for enabling safe mode. */
63 static const int ALERT_PRIORITY_SAFE_MODE = 4000;
64 /** Maximum reorg length we will accept before we shut down and alert the user. */
65 static const unsigned int MAX_REORG_LENGTH = _COINBASE_MATURITY - 1;
66 /** Maximum number of signature check operations in an IsStandard() P2SH script */
67 static const unsigned int MAX_P2SH_SIGOPS = 15;
68 /** The maximum number of sigops we're willing to relay/mine in a single tx */
69 static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
70 /** Default for -minrelaytxfee, minimum relay fee for transactions */
71 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 100;
72 /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
73 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
74 /** Default for -txexpirydelta, in number of blocks */
75 static const unsigned int DEFAULT_TX_EXPIRY_DELTA = 20;
76 /** The maximum size of a blk?????.dat file (since 0.8) */
77 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
78 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
79 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
80 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
81 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 = 160;
93 /** Size of the "block download window": how far ahead of our current height do we fetch?
94 * Larger windows tolerate larger download speed differences between peer, but increase the potential
95 * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
96 * harder). We'll probably want to make this a per-peer adaptive value at some point. */
97 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
98 /** Time to wait (in seconds) between writing blocks/block index to disk. */
99 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
100 /** Time to wait (in seconds) between flushing chainstate to disk. */
101 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
102 /** Maximum length of reject messages. */
103 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
105 //static const bool DEFAULT_ADDRESSINDEX = false;
106 #define DEFAULT_ADDRESSINDEX (GetArg("-ac_cc",0) != 0)
107 static const bool DEFAULT_TIMESTAMPINDEX = false;
108 static const bool DEFAULT_SPENTINDEX = false;
109 static const unsigned int DEFAULT_DB_MAX_OPEN_FILES = 1000;
110 static const bool DEFAULT_DB_COMPRESSION = true;
112 // Sanity check the magic numbers when we change them
113 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE);
114 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE);
116 #define equihash_parameters_acceptable(N, K) \
117 ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \
118 MAX_PROTOCOL_MESSAGE_LENGTH-1000)
122 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
125 extern unsigned int expiryDelta;
126 extern CScript COINBASE_FLAGS;
127 extern CCriticalSection cs_main;
128 extern CTxMemPool mempool;
129 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
130 extern BlockMap mapBlockIndex;
131 extern uint64_t nLastBlockTx;
132 extern uint64_t nLastBlockSize;
133 extern const std::string strMessageMagic;
134 extern CWaitableCriticalSection csBestBlock;
135 extern CConditionVariable cvBlockChange;
136 extern bool fExperimentalMode;
137 extern bool fImporting;
138 extern bool fReindex;
139 extern int nScriptCheckThreads;
140 extern bool fTxIndex;
141 extern bool fIsBareMultisigStd;
142 extern bool fCheckBlockIndex;
143 extern bool fCheckpointsEnabled;
144 // TODO: remove this flag by structuring our code such that
145 // it is unneeded for testing
146 extern bool fCoinbaseEnforcedProtectionEnabled;
147 extern size_t nCoinCacheUsage;
148 extern CFeeRate minRelayTxFee;
151 /** Best header we've seen so far (used for getheaders queries' starting points). */
152 extern CBlockIndex *pindexBestHeader;
154 /** Minimum disk space required - used in CheckDiskSpace() */
155 static const uint64_t nMinDiskSpace = 52428800;
157 /** Pruning-related variables and constants */
158 /** True if any block files have ever been pruned. */
159 extern bool fHavePruned;
160 /** True if we're running in -prune mode. */
161 extern bool fPruneMode;
162 /** Number of MiB of block files that we're trying to stay below. */
163 extern uint64_t nPruneTarget;
164 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
165 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
167 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
168 // At 1MB per block, 288 blocks = 288MB.
169 // Add 15% for Undo data = 331MB
170 // Add 20% for Orphan block rate = 397MB
171 // We want the low water mark after pruning to be at least 397 MB and since we prune in
172 // full block file chunks, we need the high water mark which triggers the prune to be
173 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
174 // Setting the target to > than 550MB will make it likely we can respect the target.
175 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
177 /** Register with a network node to receive its signals */
178 void RegisterNodeSignals(CNodeSignals& nodeSignals);
179 /** Unregister a network node */
180 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
183 * Process an incoming block. This only returns after the best known valid
184 * block is made active. Note that it does not, however, guarantee that the
185 * specific block passed to it has been checked for validity!
187 * @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.
188 * @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.
189 * @param[in] pblock The block we want to process.
190 * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
191 * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
192 * @return True if state.IsValid()
194 bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp);
195 /** Check whether enough disk space is available for an incoming block */
196 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
197 /** Open a block file (blk?????.dat) */
198 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
199 /** Open an undo file (rev?????.dat) */
200 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
201 /** Translation to a filesystem path */
202 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
203 /** Import blocks from an external file */
204 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
205 /** Initialize a new block tree database + block data on disk */
206 bool InitBlockIndex();
207 /** Load the block tree and coins database from disk */
208 bool LoadBlockIndex();
209 /** Unload database information */
210 void UnloadBlockIndex();
211 /** Process protocol messages received from a given node */
212 bool ProcessMessages(CNode* pfrom);
214 * Send queued protocol messages to be sent to a give node.
216 * @param[in] pto The node which we are sending messages to.
217 * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
219 bool SendMessages(CNode* pto, bool fSendTrickle);
220 /** Run an instance of the script checking thread */
221 void ThreadScriptCheck();
222 /** Try to detect Partition (network isolation) attacks against us */
223 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
224 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
225 bool IsInitialBlockDownload();
226 /** Format a string that describes several potential problems detected by the core */
227 std::string GetWarnings(const std::string& strFor);
228 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
229 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
230 /** Find the best known block, and make it the tip of the block chain */
231 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
232 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
235 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
236 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
237 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
238 * (which in this case means the blockchain must be re-downloaded.)
240 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
241 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
242 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
243 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
244 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
245 * A db flag records the fact that at least some block files have been pruned.
247 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
249 void FindFilesToPrune(std::set<int>& setFilesToPrune);
252 * Actually unlink the specified files
254 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
256 /** Create a new block index entry for a given block hash */
257 CBlockIndex * InsertBlockIndex(uint256 hash);
258 /** Get statistics from node state */
259 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
260 /** Increase a node's misbehavior score. */
261 void Misbehaving(NodeId nodeid, int howmuch);
262 /** Flush all state, indexes and buffers to disk. */
263 void FlushStateToDisk();
264 /** Prune block files and flush state to disk. */
265 void PruneAndFlush();
267 /** (try to) add transaction to memory pool **/
268 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
269 bool* pfMissingInputs, bool fRejectAbsurdFee=false);
272 struct CNodeStateStats {
276 std::vector<int> vHeightInFlight;
279 struct CTimestampIndexIteratorKey {
280 unsigned int timestamp;
282 size_t GetSerializeSize(int nType, int nVersion) const {
285 template<typename Stream>
286 void Serialize(Stream& s, int nType, int nVersion) const {
287 ser_writedata32be(s, timestamp);
289 template<typename Stream>
290 void Unserialize(Stream& s, int nType, int nVersion) {
291 timestamp = ser_readdata32be(s);
294 CTimestampIndexIteratorKey(unsigned int time) {
298 CTimestampIndexIteratorKey() {
307 struct CTimestampIndexKey {
308 unsigned int timestamp;
311 size_t GetSerializeSize(int nType, int nVersion) const {
314 template<typename Stream>
315 void Serialize(Stream& s, int nType, int nVersion) const {
316 ser_writedata32be(s, timestamp);
317 blockHash.Serialize(s, nType, nVersion);
319 template<typename Stream>
320 void Unserialize(Stream& s, int nType, int nVersion) {
321 timestamp = ser_readdata32be(s);
322 blockHash.Unserialize(s, nType, nVersion);
325 CTimestampIndexKey(unsigned int time, uint256 hash) {
330 CTimestampIndexKey() {
340 struct CTimestampBlockIndexKey {
343 size_t GetSerializeSize(int nType, int nVersion) const {
347 template<typename Stream>
348 void Serialize(Stream& s, int nType, int nVersion) const {
349 blockHash.Serialize(s, nType, nVersion);
352 template<typename Stream>
353 void Unserialize(Stream& s, int nType, int nVersion) {
354 blockHash.Unserialize(s, nType, nVersion);
357 CTimestampBlockIndexKey(uint256 hash) {
361 CTimestampBlockIndexKey() {
370 struct CTimestampBlockIndexValue {
371 unsigned int ltimestamp;
372 size_t GetSerializeSize(int nType, int nVersion) const {
376 template<typename Stream>
377 void Serialize(Stream& s, int nType, int nVersion) const {
378 ser_writedata32be(s, ltimestamp);
381 template<typename Stream>
382 void Unserialize(Stream& s, int nType, int nVersion) {
383 ltimestamp = ser_readdata32be(s);
386 CTimestampBlockIndexValue (unsigned int time) {
390 CTimestampBlockIndexValue() {
399 struct CAddressUnspentKey {
405 size_t GetSerializeSize(int nType, int nVersion) const {
408 template<typename Stream>
409 void Serialize(Stream& s, int nType, int nVersion) const {
410 ser_writedata8(s, type);
411 hashBytes.Serialize(s, nType, nVersion);
412 txhash.Serialize(s, nType, nVersion);
413 ser_writedata32(s, index);
415 template<typename Stream>
416 void Unserialize(Stream& s, int nType, int nVersion) {
417 type = ser_readdata8(s);
418 hashBytes.Unserialize(s, nType, nVersion);
419 txhash.Unserialize(s, nType, nVersion);
420 index = ser_readdata32(s);
423 CAddressUnspentKey(unsigned int addressType, uint160 addressHash, uint256 txid, size_t indexValue) {
425 hashBytes = addressHash;
430 CAddressUnspentKey() {
442 struct CAddressUnspentValue {
447 ADD_SERIALIZE_METHODS;
449 template <typename Stream, typename Operation>
450 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
453 READWRITE(blockHeight);
456 CAddressUnspentValue(CAmount sats, CScript scriptPubKey, int height) {
458 script = scriptPubKey;
459 blockHeight = height;
462 CAddressUnspentValue() {
472 bool IsNull() const {
473 return (satoshis == -1);
477 struct CAddressIndexKey {
481 unsigned int txindex;
486 size_t GetSerializeSize(int nType, int nVersion) const {
489 template<typename Stream>
490 void Serialize(Stream& s, int nType, int nVersion) const {
491 ser_writedata8(s, type);
492 hashBytes.Serialize(s, nType, nVersion);
493 // Heights are stored big-endian for key sorting in LevelDB
494 ser_writedata32be(s, blockHeight);
495 ser_writedata32be(s, txindex);
496 txhash.Serialize(s, nType, nVersion);
497 ser_writedata32(s, index);
499 ser_writedata8(s, f);
501 template<typename Stream>
502 void Unserialize(Stream& s, int nType, int nVersion) {
503 type = ser_readdata8(s);
504 hashBytes.Unserialize(s, nType, nVersion);
505 blockHeight = ser_readdata32be(s);
506 txindex = ser_readdata32be(s);
507 txhash.Unserialize(s, nType, nVersion);
508 index = ser_readdata32(s);
509 char f = ser_readdata8(s);
513 CAddressIndexKey(unsigned int addressType, uint160 addressHash, int height, int blockindex,
514 uint256 txid, size_t indexValue, bool isSpending) {
516 hashBytes = addressHash;
517 blockHeight = height;
518 txindex = blockindex;
521 spending = isSpending;
540 struct CAddressIndexIteratorKey {
544 size_t GetSerializeSize(int nType, int nVersion) const {
547 template<typename Stream>
548 void Serialize(Stream& s, int nType, int nVersion) const {
549 ser_writedata8(s, type);
550 hashBytes.Serialize(s, nType, nVersion);
552 template<typename Stream>
553 void Unserialize(Stream& s, int nType, int nVersion) {
554 type = ser_readdata8(s);
555 hashBytes.Unserialize(s, nType, nVersion);
558 CAddressIndexIteratorKey(unsigned int addressType, uint160 addressHash) {
560 hashBytes = addressHash;
563 CAddressIndexIteratorKey() {
573 struct CAddressIndexIteratorHeightKey {
578 size_t GetSerializeSize(int nType, int nVersion) const {
581 template<typename Stream>
582 void Serialize(Stream& s, int nType, int nVersion) const {
583 ser_writedata8(s, type);
584 hashBytes.Serialize(s, nType, nVersion);
585 ser_writedata32be(s, blockHeight);
587 template<typename Stream>
588 void Unserialize(Stream& s, int nType, int nVersion) {
589 type = ser_readdata8(s);
590 hashBytes.Unserialize(s, nType, nVersion);
591 blockHeight = ser_readdata32be(s);
594 CAddressIndexIteratorHeightKey(unsigned int addressType, uint160 addressHash, int height) {
596 hashBytes = addressHash;
597 blockHeight = height;
600 CAddressIndexIteratorHeightKey() {
611 struct CDiskTxPos : public CDiskBlockPos
613 unsigned int nTxOffset; // after header
615 ADD_SERIALIZE_METHODS;
617 template <typename Stream, typename Operation>
618 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
619 READWRITE(*(CDiskBlockPos*)this);
620 READWRITE(VARINT(nTxOffset));
623 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
631 CDiskBlockPos::SetNull();
637 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
640 * Check transaction inputs, and make sure any
641 * pay-to-script-hash transactions are evaluating IsStandard scripts
643 * Why bother? To avoid denial-of-service attacks; an attacker
644 * can submit a standard HASH... OP_EQUAL transaction,
645 * which will get accepted into blocks. The redemption
646 * script can be anything; an attacker could use a very
647 * expensive-to-check-upon-redemption script like:
648 * DUP CHECKSIG DROP ... repeated 100 times... OP_1
652 * Check for standard transaction types
653 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
654 * @return True if all inputs (scriptSigs) use only standard transaction forms
656 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
659 * Count ECDSA signature operations the old-fashioned (pre-0.6) way
660 * @return number of sigops this transaction's outputs will produce when spent
661 * @see CTransaction::FetchInputs
663 unsigned int GetLegacySigOpCount(const CTransaction& tx);
666 * Count ECDSA signature operations in pay-to-script-hash inputs.
668 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
669 * @return maximum number of sigops required to validate this transaction's inputs
670 * @see CTransaction::FetchInputs
672 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
676 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
677 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
678 * instead of being performed inline.
680 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
681 unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata,
682 const Consensus::Params& consensusParams, uint32_t consensusBranchId,
683 std::vector<CScriptCheck> *pvChecks = NULL);
685 /** Check a transaction contextually against a set of consensus rules */
686 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, int nHeight, int dosLevel);
688 /** Apply the effects of this transaction on the UTXO set represented by view */
689 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
691 /** Transaction validation functions */
693 /** Context-independent validity checks */
694 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
695 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
697 /** Check for standard transaction types
698 * @return True if all outputs (scriptPubKeys) use only standard transaction forms
700 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
702 namespace Consensus {
705 * Check whether all inputs of this transaction are valid (no double spends and amounts)
706 * This does not modify the UTXO set. This does not check scripts and sigs.
707 * Preconditions: tx.IsCoinBase() is false.
709 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
711 } // namespace Consensus
714 * Check if transaction is final and can be included in a block with the
715 * specified height and time. Consensus critical.
717 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
720 * Check if transaction is expired and can be included in a block with the
721 * specified height. Consensus critical.
723 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
726 * Check if transaction will be final in the next block to be created.
728 * Calls IsFinalTx() with current block height and appropriate block time.
730 * See consensus/consensus.h for flag definitions.
732 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
735 * Closure representing one script verification
736 * Note that this stores references to the spending transaction
741 CScript scriptPubKey;
743 const CTransaction *ptxTo;
747 uint32_t consensusBranchId;
749 PrecomputedTransactionData *txdata;
752 CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), consensusBranchId(0), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
753 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, uint32_t consensusBranchIdIn, PrecomputedTransactionData* txdataIn) :
754 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
755 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), consensusBranchId(consensusBranchIdIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
759 void swap(CScriptCheck &check) {
760 scriptPubKey.swap(check.scriptPubKey);
761 std::swap(ptxTo, check.ptxTo);
762 std::swap(amount, check.amount);
763 std::swap(nIn, check.nIn);
764 std::swap(nFlags, check.nFlags);
765 std::swap(cacheStore, check.cacheStore);
766 std::swap(consensusBranchId, check.consensusBranchId);
767 std::swap(error, check.error);
768 std::swap(txdata, check.txdata);
771 ScriptError GetScriptError() const { return error; }
774 bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector<std::pair<uint256, unsigned int> > &hashes);
775 bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value);
776 bool GetAddressIndex(uint160 addressHash, int type,
777 std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
778 int start = 0, int end = 0);
779 bool GetAddressUnspent(uint160 addressHash, int type,
780 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs);
782 /** Functions for disk access for blocks */
783 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
784 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW);
785 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW);
788 /** Functions for validating blocks and updating the block tree */
790 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
791 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
792 * will be true if no problems were found. Otherwise, the return value will be false in case
793 * of problems. Note that in any case, coins may be modified. */
794 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
796 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
797 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false,bool fCheckPOW = false);
799 /** Context-independent validity checks */
800 bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
801 bool CheckBlock(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
802 libzcash::ProofVerifier& verifier,
803 bool fCheckPOW = true, bool fCheckMerkleRoot = true);
805 /** Context-dependent validity checks */
806 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
807 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
809 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
810 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
813 * Store block on disk.
814 * JoinSplit proofs are never verified, because:
815 * - AcceptBlock doesn't perform script checks either.
816 * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere.
817 * If dbp is non-NULL, the file is known to already reside on disk
819 bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
820 bool AcceptBlockHeader(int32_t *futureblockp,const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
825 * When there are blocks in the active chain with missing data (e.g. if the
826 * activation height and branch ID of a particular upgrade have been altered),
827 * rewind the chainstate and remove them from the block index.
829 bool RewindBlockIndex(const CChainParams& params);
834 unsigned int nBlocks; //! number of blocks stored in file
835 unsigned int nSize; //! number of used bytes of block file
836 unsigned int nUndoSize; //! number of used bytes in the undo file
837 unsigned int nHeightFirst; //! lowest height of block in file
838 unsigned int nHeightLast; //! highest height of block in file
839 uint64_t nTimeFirst; //! earliest time of block in file
840 uint64_t nTimeLast; //! latest time of block in file
842 ADD_SERIALIZE_METHODS;
844 template <typename Stream, typename Operation>
845 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
846 READWRITE(VARINT(nBlocks));
847 READWRITE(VARINT(nSize));
848 READWRITE(VARINT(nUndoSize));
849 READWRITE(VARINT(nHeightFirst));
850 READWRITE(VARINT(nHeightLast));
851 READWRITE(VARINT(nTimeFirst));
852 READWRITE(VARINT(nTimeLast));
869 std::string ToString() const;
871 /** update statistics (does not update nSize) */
872 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
873 if (nBlocks==0 || nHeightFirst > nHeightIn)
874 nHeightFirst = nHeightIn;
875 if (nBlocks==0 || nTimeFirst > nTimeIn)
876 nTimeFirst = nTimeIn;
878 if (nHeightIn > nHeightLast)
879 nHeightLast = nHeightIn;
880 if (nTimeIn > nTimeLast)
885 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
890 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
893 /** Find the last common block between the parameter chain and a locator. */
894 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
896 /** Mark a block as invalid. */
897 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
899 /** Remove invalidity status from a block and its descendants. */
900 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
902 /** The currently-connected chain of blocks (protected by cs_main). */
903 extern CChain chainActive;
905 /** Global variable that points to the active CCoinsView (protected by cs_main) */
906 extern CCoinsViewCache *pcoinsTip;
908 /** Global variable that points to the active block tree (protected by cs_main) */
909 extern CBlockTreeDB *pblocktree;
912 * Return the spend height, which is one more than the inputs.GetBestBlock().
913 * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
914 * This is also true for mempool checks.
916 int GetSpendHeight(const CCoinsViewCache& inputs);
918 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at height */
919 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight);
921 #endif // BITCOIN_MAIN_H