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 static const bool DEFAULT_TIMESTAMPINDEX = false;
107 static const bool DEFAULT_SPENTINDEX = false;
108 static const unsigned int DEFAULT_DB_MAX_OPEN_FILES = 1000;
109 static const bool DEFAULT_DB_COMPRESSION = true;
111 // Sanity check the magic numbers when we change them
112 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE);
113 BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE);
115 #define equihash_parameters_acceptable(N, K) \
116 ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \
117 MAX_PROTOCOL_MESSAGE_LENGTH-1000)
121 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
124 extern unsigned int expiryDelta;
125 extern CScript COINBASE_FLAGS;
126 extern CCriticalSection cs_main;
127 extern CTxMemPool mempool;
128 typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
129 extern BlockMap mapBlockIndex;
130 extern uint64_t nLastBlockTx;
131 extern uint64_t nLastBlockSize;
132 extern const std::string strMessageMagic;
133 extern CWaitableCriticalSection csBestBlock;
134 extern CConditionVariable cvBlockChange;
135 extern bool fExperimentalMode;
136 extern bool fImporting;
137 extern bool fReindex;
138 extern int nScriptCheckThreads;
139 extern bool fTxIndex;
140 extern bool fIsBareMultisigStd;
141 extern bool fCheckBlockIndex;
142 extern bool fCheckpointsEnabled;
143 // TODO: remove this flag by structuring our code such that
144 // it is unneeded for testing
145 extern bool fCoinbaseEnforcedProtectionEnabled;
146 extern size_t nCoinCacheUsage;
147 extern CFeeRate minRelayTxFee;
150 /** Best header we've seen so far (used for getheaders queries' starting points). */
151 extern CBlockIndex *pindexBestHeader;
153 /** Minimum disk space required - used in CheckDiskSpace() */
154 static const uint64_t nMinDiskSpace = 52428800;
156 /** Pruning-related variables and constants */
157 /** True if any block files have ever been pruned. */
158 extern bool fHavePruned;
159 /** True if we're running in -prune mode. */
160 extern bool fPruneMode;
161 /** Number of MiB of block files that we're trying to stay below. */
162 extern uint64_t nPruneTarget;
163 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
164 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
166 // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat)
167 // At 1MB per block, 288 blocks = 288MB.
168 // Add 15% for Undo data = 331MB
169 // Add 20% for Orphan block rate = 397MB
170 // We want the low water mark after pruning to be at least 397 MB and since we prune in
171 // full block file chunks, we need the high water mark which triggers the prune to be
172 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
173 // Setting the target to > than 550MB will make it likely we can respect the target.
174 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
176 /** Register with a network node to receive its signals */
177 void RegisterNodeSignals(CNodeSignals& nodeSignals);
178 /** Unregister a network node */
179 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
182 * Process an incoming block. This only returns after the best known valid
183 * block is made active. Note that it does not, however, guarantee that the
184 * specific block passed to it has been checked for validity!
186 * @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.
187 * @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.
188 * @param[in] pblock The block we want to process.
189 * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
190 * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
191 * @return True if state.IsValid()
193 bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp);
194 /** Check whether enough disk space is available for an incoming block */
195 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
196 /** Open a block file (blk?????.dat) */
197 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
198 /** Open an undo file (rev?????.dat) */
199 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
200 /** Translation to a filesystem path */
201 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
202 /** Import blocks from an external file */
203 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
204 /** Initialize a new block tree database + block data on disk */
205 bool InitBlockIndex();
206 /** Load the block tree and coins database from disk */
207 bool LoadBlockIndex();
208 /** Unload database information */
209 void UnloadBlockIndex();
210 /** Process protocol messages received from a given node */
211 bool ProcessMessages(CNode* pfrom);
213 * Send queued protocol messages to be sent to a give node.
215 * @param[in] pto The node which we are sending messages to.
216 * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
218 bool SendMessages(CNode* pto, bool fSendTrickle);
219 /** Run an instance of the script checking thread */
220 void ThreadScriptCheck();
221 /** Try to detect Partition (network isolation) attacks against us */
222 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
223 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
224 bool IsInitialBlockDownload();
225 /** Format a string that describes several potential problems detected by the core */
226 std::string GetWarnings(const std::string& strFor);
227 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
228 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
229 /** Find the best known block, and make it the tip of the block chain */
230 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
231 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
234 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
235 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
236 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
237 * (which in this case means the blockchain must be re-downloaded.)
239 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
240 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
241 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest).
242 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
243 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
244 * A db flag records the fact that at least some block files have been pruned.
246 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
248 void FindFilesToPrune(std::set<int>& setFilesToPrune);
251 * Actually unlink the specified files
253 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
255 /** Create a new block index entry for a given block hash */
256 CBlockIndex * InsertBlockIndex(uint256 hash);
257 /** Get statistics from node state */
258 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
259 /** Increase a node's misbehavior score. */
260 void Misbehaving(NodeId nodeid, int howmuch);
261 /** Flush all state, indexes and buffers to disk. */
262 void FlushStateToDisk();
263 /** Prune block files and flush state to disk. */
264 void PruneAndFlush();
266 /** (try to) add transaction to memory pool **/
267 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
268 bool* pfMissingInputs, bool fRejectAbsurdFee=false);
271 struct CNodeStateStats {
275 std::vector<int> vHeightInFlight;
278 struct CTimestampIndexIteratorKey {
279 unsigned int timestamp;
281 size_t GetSerializeSize(int nType, int nVersion) const {
284 template<typename Stream>
285 void Serialize(Stream& s, int nType, int nVersion) const {
286 ser_writedata32be(s, timestamp);
288 template<typename Stream>
289 void Unserialize(Stream& s, int nType, int nVersion) {
290 timestamp = ser_readdata32be(s);
293 CTimestampIndexIteratorKey(unsigned int time) {
297 CTimestampIndexIteratorKey() {
306 struct CTimestampIndexKey {
307 unsigned int timestamp;
310 size_t GetSerializeSize(int nType, int nVersion) const {
313 template<typename Stream>
314 void Serialize(Stream& s, int nType, int nVersion) const {
315 ser_writedata32be(s, timestamp);
316 blockHash.Serialize(s, nType, nVersion);
318 template<typename Stream>
319 void Unserialize(Stream& s, int nType, int nVersion) {
320 timestamp = ser_readdata32be(s);
321 blockHash.Unserialize(s, nType, nVersion);
324 CTimestampIndexKey(unsigned int time, uint256 hash) {
329 CTimestampIndexKey() {
339 struct CTimestampBlockIndexKey {
342 size_t GetSerializeSize(int nType, int nVersion) const {
346 template<typename Stream>
347 void Serialize(Stream& s, int nType, int nVersion) const {
348 blockHash.Serialize(s, nType, nVersion);
351 template<typename Stream>
352 void Unserialize(Stream& s, int nType, int nVersion) {
353 blockHash.Unserialize(s, nType, nVersion);
356 CTimestampBlockIndexKey(uint256 hash) {
360 CTimestampBlockIndexKey() {
369 struct CTimestampBlockIndexValue {
370 unsigned int ltimestamp;
371 size_t GetSerializeSize(int nType, int nVersion) const {
375 template<typename Stream>
376 void Serialize(Stream& s, int nType, int nVersion) const {
377 ser_writedata32be(s, ltimestamp);
380 template<typename Stream>
381 void Unserialize(Stream& s, int nType, int nVersion) {
382 ltimestamp = ser_readdata32be(s);
385 CTimestampBlockIndexValue (unsigned int time) {
389 CTimestampBlockIndexValue() {
398 struct CAddressUnspentKey {
404 size_t GetSerializeSize(int nType, int nVersion) const {
407 template<typename Stream>
408 void Serialize(Stream& s, int nType, int nVersion) const {
409 ser_writedata8(s, type);
410 hashBytes.Serialize(s, nType, nVersion);
411 txhash.Serialize(s, nType, nVersion);
412 ser_writedata32(s, index);
414 template<typename Stream>
415 void Unserialize(Stream& s, int nType, int nVersion) {
416 type = ser_readdata8(s);
417 hashBytes.Unserialize(s, nType, nVersion);
418 txhash.Unserialize(s, nType, nVersion);
419 index = ser_readdata32(s);
422 CAddressUnspentKey(unsigned int addressType, uint160 addressHash, uint256 txid, size_t indexValue) {
424 hashBytes = addressHash;
429 CAddressUnspentKey() {
441 struct CAddressUnspentValue {
446 ADD_SERIALIZE_METHODS;
448 template <typename Stream, typename Operation>
449 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
452 READWRITE(blockHeight);
455 CAddressUnspentValue(CAmount sats, CScript scriptPubKey, int height) {
457 script = scriptPubKey;
458 blockHeight = height;
461 CAddressUnspentValue() {
471 bool IsNull() const {
472 return (satoshis == -1);
476 struct CAddressIndexKey {
480 unsigned int txindex;
485 size_t GetSerializeSize(int nType, int nVersion) const {
488 template<typename Stream>
489 void Serialize(Stream& s, int nType, int nVersion) const {
490 ser_writedata8(s, type);
491 hashBytes.Serialize(s, nType, nVersion);
492 // Heights are stored big-endian for key sorting in LevelDB
493 ser_writedata32be(s, blockHeight);
494 ser_writedata32be(s, txindex);
495 txhash.Serialize(s, nType, nVersion);
496 ser_writedata32(s, index);
498 ser_writedata8(s, f);
500 template<typename Stream>
501 void Unserialize(Stream& s, int nType, int nVersion) {
502 type = ser_readdata8(s);
503 hashBytes.Unserialize(s, nType, nVersion);
504 blockHeight = ser_readdata32be(s);
505 txindex = ser_readdata32be(s);
506 txhash.Unserialize(s, nType, nVersion);
507 index = ser_readdata32(s);
508 char f = ser_readdata8(s);
512 CAddressIndexKey(unsigned int addressType, uint160 addressHash, int height, int blockindex,
513 uint256 txid, size_t indexValue, bool isSpending) {
515 hashBytes = addressHash;
516 blockHeight = height;
517 txindex = blockindex;
520 spending = isSpending;
539 struct CAddressIndexIteratorKey {
543 size_t GetSerializeSize(int nType, int nVersion) const {
546 template<typename Stream>
547 void Serialize(Stream& s, int nType, int nVersion) const {
548 ser_writedata8(s, type);
549 hashBytes.Serialize(s, nType, nVersion);
551 template<typename Stream>
552 void Unserialize(Stream& s, int nType, int nVersion) {
553 type = ser_readdata8(s);
554 hashBytes.Unserialize(s, nType, nVersion);
557 CAddressIndexIteratorKey(unsigned int addressType, uint160 addressHash) {
559 hashBytes = addressHash;
562 CAddressIndexIteratorKey() {
572 struct CAddressIndexIteratorHeightKey {
577 size_t GetSerializeSize(int nType, int nVersion) const {
580 template<typename Stream>
581 void Serialize(Stream& s, int nType, int nVersion) const {
582 ser_writedata8(s, type);
583 hashBytes.Serialize(s, nType, nVersion);
584 ser_writedata32be(s, blockHeight);
586 template<typename Stream>
587 void Unserialize(Stream& s, int nType, int nVersion) {
588 type = ser_readdata8(s);
589 hashBytes.Unserialize(s, nType, nVersion);
590 blockHeight = ser_readdata32be(s);
593 CAddressIndexIteratorHeightKey(unsigned int addressType, uint160 addressHash, int height) {
595 hashBytes = addressHash;
596 blockHeight = height;
599 CAddressIndexIteratorHeightKey() {
610 struct CDiskTxPos : public CDiskBlockPos
612 unsigned int nTxOffset; // after header
614 ADD_SERIALIZE_METHODS;
616 template <typename Stream, typename Operation>
617 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
618 READWRITE(*(CDiskBlockPos*)this);
619 READWRITE(VARINT(nTxOffset));
622 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
630 CDiskBlockPos::SetNull();
636 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
639 * Check transaction inputs, and make sure any
640 * pay-to-script-hash transactions are evaluating IsStandard scripts
642 * Why bother? To avoid denial-of-service attacks; an attacker
643 * can submit a standard HASH... OP_EQUAL transaction,
644 * which will get accepted into blocks. The redemption
645 * script can be anything; an attacker could use a very
646 * expensive-to-check-upon-redemption script like:
647 * DUP CHECKSIG DROP ... repeated 100 times... OP_1
651 * Check for standard transaction types
652 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
653 * @return True if all inputs (scriptSigs) use only standard transaction forms
655 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
658 * Count ECDSA signature operations the old-fashioned (pre-0.6) way
659 * @return number of sigops this transaction's outputs will produce when spent
660 * @see CTransaction::FetchInputs
662 unsigned int GetLegacySigOpCount(const CTransaction& tx);
665 * Count ECDSA signature operations in pay-to-script-hash inputs.
667 * @param[in] mapInputs Map of previous transactions that have outputs we're spending
668 * @return maximum number of sigops required to validate this transaction's inputs
669 * @see CTransaction::FetchInputs
671 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
675 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
676 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
677 * instead of being performed inline.
679 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks,
680 unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata,
681 const Consensus::Params& consensusParams, uint32_t consensusBranchId,
682 std::vector<CScriptCheck> *pvChecks = NULL);
684 /** Check a transaction contextually against a set of consensus rules */
685 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, int nHeight, int dosLevel);
687 /** Apply the effects of this transaction on the UTXO set represented by view */
688 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
690 /** Transaction validation functions */
692 /** Context-independent validity checks */
693 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
694 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
696 /** Check for standard transaction types
697 * @return True if all outputs (scriptPubKeys) use only standard transaction forms
699 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
701 namespace Consensus {
704 * Check whether all inputs of this transaction are valid (no double spends and amounts)
705 * This does not modify the UTXO set. This does not check scripts and sigs.
706 * Preconditions: tx.IsCoinBase() is false.
708 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
710 } // namespace Consensus
713 * Check if transaction is final and can be included in a block with the
714 * specified height and time. Consensus critical.
716 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
719 * Check if transaction is expired and can be included in a block with the
720 * specified height. Consensus critical.
722 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
725 * Check if transaction will be final in the next block to be created.
727 * Calls IsFinalTx() with current block height and appropriate block time.
729 * See consensus/consensus.h for flag definitions.
731 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
734 * Closure representing one script verification
735 * Note that this stores references to the spending transaction
740 CScript scriptPubKey;
742 const CTransaction *ptxTo;
746 uint32_t consensusBranchId;
748 PrecomputedTransactionData *txdata;
751 CScriptCheck(): amount(0), ptxTo(0), nIn(0), nFlags(0), cacheStore(false), consensusBranchId(0), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
752 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, uint32_t consensusBranchIdIn, PrecomputedTransactionData* txdataIn) :
753 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), amount(txFromIn.vout[txToIn.vin[nInIn].prevout.n].nValue),
754 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), consensusBranchId(consensusBranchIdIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
758 void swap(CScriptCheck &check) {
759 scriptPubKey.swap(check.scriptPubKey);
760 std::swap(ptxTo, check.ptxTo);
761 std::swap(amount, check.amount);
762 std::swap(nIn, check.nIn);
763 std::swap(nFlags, check.nFlags);
764 std::swap(cacheStore, check.cacheStore);
765 std::swap(consensusBranchId, check.consensusBranchId);
766 std::swap(error, check.error);
767 std::swap(txdata, check.txdata);
770 ScriptError GetScriptError() const { return error; }
773 bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector<std::pair<uint256, unsigned int> > &hashes);
774 bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value);
775 bool GetAddressIndex(uint160 addressHash, int type,
776 std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
777 int start = 0, int end = 0);
778 bool GetAddressUnspent(uint160 addressHash, int type,
779 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs);
781 /** Functions for disk access for blocks */
782 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart);
783 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW);
784 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW);
787 /** Functions for validating blocks and updating the block tree */
789 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
790 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
791 * will be true if no problems were found. Otherwise, the return value will be false in case
792 * of problems. Note that in any case, coins may be modified. */
793 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
795 /** Apply the effects of this block (with given index) on the UTXO set represented by coins */
796 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false,bool fCheckPOW = false);
798 /** Context-independent validity checks */
799 bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
800 bool CheckBlock(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state,
801 libzcash::ProofVerifier& verifier,
802 bool fCheckPOW = true, bool fCheckMerkleRoot = true);
804 /** Context-dependent validity checks */
805 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev);
806 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev);
808 /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
809 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
812 * Store block on disk.
813 * JoinSplit proofs are never verified, because:
814 * - AcceptBlock doesn't perform script checks either.
815 * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere.
816 * If dbp is non-NULL, the file is known to already reside on disk
818 bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp);
819 bool AcceptBlockHeader(int32_t *futureblockp,const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
824 * When there are blocks in the active chain with missing data (e.g. if the
825 * activation height and branch ID of a particular upgrade have been altered),
826 * rewind the chainstate and remove them from the block index.
828 bool RewindBlockIndex(const CChainParams& params);
833 unsigned int nBlocks; //! number of blocks stored in file
834 unsigned int nSize; //! number of used bytes of block file
835 unsigned int nUndoSize; //! number of used bytes in the undo file
836 unsigned int nHeightFirst; //! lowest height of block in file
837 unsigned int nHeightLast; //! highest height of block in file
838 uint64_t nTimeFirst; //! earliest time of block in file
839 uint64_t nTimeLast; //! latest time of block in file
841 ADD_SERIALIZE_METHODS;
843 template <typename Stream, typename Operation>
844 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
845 READWRITE(VARINT(nBlocks));
846 READWRITE(VARINT(nSize));
847 READWRITE(VARINT(nUndoSize));
848 READWRITE(VARINT(nHeightFirst));
849 READWRITE(VARINT(nHeightLast));
850 READWRITE(VARINT(nTimeFirst));
851 READWRITE(VARINT(nTimeLast));
868 std::string ToString() const;
870 /** update statistics (does not update nSize) */
871 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
872 if (nBlocks==0 || nHeightFirst > nHeightIn)
873 nHeightFirst = nHeightIn;
874 if (nBlocks==0 || nTimeFirst > nTimeIn)
875 nTimeFirst = nTimeIn;
877 if (nHeightIn > nHeightLast)
878 nHeightLast = nHeightIn;
879 if (nTimeIn > nTimeLast)
884 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
889 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
892 /** Find the last common block between the parameter chain and a locator. */
893 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
895 /** Mark a block as invalid. */
896 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
898 /** Remove invalidity status from a block and its descendants. */
899 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
901 /** The currently-connected chain of blocks (protected by cs_main). */
902 extern CChain chainActive;
904 /** Global variable that points to the active CCoinsView (protected by cs_main) */
905 extern CCoinsViewCache *pcoinsTip;
907 /** Global variable that points to the active block tree (protected by cs_main) */
908 extern CBlockTreeDB *pblocktree;
911 * Return the spend height, which is one more than the inputs.GetBestBlock().
912 * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
913 * This is also true for mempool checks.
915 int GetSpendHeight(const CCoinsViewCache& inputs);
917 /** Return a CMutableTransaction with contextual default values based on set of consensus rules at height */
918 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight);
920 #endif // BITCOIN_MAIN_H