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 "script/script_ext.h"
26 #include "spentindex.h"
28 #include "tinyformat.h"
29 #include "txmempool.h"
31 #include "cheatcatcher.h"
42 #include <boost/unordered_map.hpp>
49 class CValidationInterface;
50 class CValidationState;
51 class PrecomputedTransactionData;
53 struct CNodeStateStats;
54 #define DEFAULT_MEMPOOL_EXPIRY 1
55 #define _COINBASE_MATURITY 100
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;
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;
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);
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)
126 size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
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;
154 extern int64_t nMaxTipAge;
156 /** Best header we've seen so far (used for getheaders queries' starting points). */
157 extern CBlockIndex *pindexBestHeader;
159 /** Minimum disk space required - used in CheckDiskSpace() */
160 static const uint64_t nMinDiskSpace = 52428800;
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;
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;
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);
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!
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()
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);
219 * Send queued protocol messages to be sent to a give node.
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.
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
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);
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.)
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.
256 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
258 void FindFilesToPrune(std::set<int>& setFilesToPrune);
261 * Actually unlink the specified files
263 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune);
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();
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);
281 struct CNodeStateStats {
285 std::vector<int> vHeightInFlight;
288 struct CTimestampIndexIteratorKey {
289 unsigned int timestamp;
291 size_t GetSerializeSize(int nType, int nVersion) const {
294 template<typename Stream>
295 void Serialize(Stream& s) const {
296 ser_writedata32be(s, timestamp);
298 template<typename Stream>
299 void Unserialize(Stream& s) {
300 timestamp = ser_readdata32be(s);
303 CTimestampIndexIteratorKey(unsigned int time) {
307 CTimestampIndexIteratorKey() {
316 struct CTimestampIndexKey {
317 unsigned int timestamp;
320 size_t GetSerializeSize(int nType, int nVersion) const {
323 template<typename Stream>
324 void Serialize(Stream& s) const {
325 ser_writedata32be(s, timestamp);
326 blockHash.Serialize(s);
328 template<typename Stream>
329 void Unserialize(Stream& s) {
330 timestamp = ser_readdata32be(s);
331 blockHash.Unserialize(s);
334 CTimestampIndexKey(unsigned int time, uint256 hash) {
339 CTimestampIndexKey() {
349 struct CTimestampBlockIndexKey {
352 size_t GetSerializeSize(int nType, int nVersion) const {
356 template<typename Stream>
357 void Serialize(Stream& s) const {
358 blockHash.Serialize(s);
361 template<typename Stream>
362 void Unserialize(Stream& s) {
363 blockHash.Unserialize(s);
366 CTimestampBlockIndexKey(uint256 hash) {
370 CTimestampBlockIndexKey() {
379 struct CTimestampBlockIndexValue {
380 unsigned int ltimestamp;
381 size_t GetSerializeSize(int nType, int nVersion) const {
385 template<typename Stream>
386 void Serialize(Stream& s) const {
387 ser_writedata32be(s, ltimestamp);
390 template<typename Stream>
391 void Unserialize(Stream& s) {
392 ltimestamp = ser_readdata32be(s);
395 CTimestampBlockIndexValue (unsigned int time) {
399 CTimestampBlockIndexValue() {
408 struct CAddressUnspentKey {
414 size_t GetSerializeSize(int nType, int nVersion) const {
417 template<typename Stream>
418 void Serialize(Stream& s) const {
419 ser_writedata8(s, type);
420 hashBytes.Serialize(s);
422 ser_writedata32(s, index);
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);
432 CAddressUnspentKey(unsigned int addressType, uint160 addressHash, uint256 txid, size_t indexValue) {
434 hashBytes = addressHash;
439 CAddressUnspentKey() {
451 struct CAddressUnspentValue {
456 ADD_SERIALIZE_METHODS;
458 template <typename Stream, typename Operation>
459 inline void SerializationOp(Stream& s, Operation ser_action) {
461 READWRITE(*(CScriptBase*)(&script));
462 READWRITE(blockHeight);
465 CAddressUnspentValue(CAmount sats, CScript scriptPubKey, int height) {
467 script = scriptPubKey;
468 blockHeight = height;
471 CAddressUnspentValue() {
481 bool IsNull() const {
482 return (satoshis == -1);
486 struct CAddressIndexKey {
490 unsigned int txindex;
495 size_t GetSerializeSize(int nType, int nVersion) const {
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);
506 ser_writedata32(s, index);
508 ser_writedata8(s, f);
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);
522 CAddressIndexKey(unsigned int addressType, uint160 addressHash, int height, int blockindex,
523 uint256 txid, size_t indexValue, bool isSpending) {
525 hashBytes = addressHash;
526 blockHeight = height;
527 txindex = blockindex;
530 spending = isSpending;
549 struct CAddressIndexIteratorKey {
553 size_t GetSerializeSize(int nType, int nVersion) const {
556 template<typename Stream>
557 void Serialize(Stream& s) const {
558 ser_writedata8(s, type);
559 hashBytes.Serialize(s);
561 template<typename Stream>
562 void Unserialize(Stream& s) {
563 type = ser_readdata8(s);
564 hashBytes.Unserialize(s);
567 CAddressIndexIteratorKey(unsigned int addressType, uint160 addressHash) {
569 hashBytes = addressHash;
572 CAddressIndexIteratorKey() {
582 struct CAddressIndexIteratorHeightKey {
587 size_t GetSerializeSize(int nType, int nVersion) const {
590 template<typename Stream>
591 void Serialize(Stream& s) const {
592 ser_writedata8(s, type);
593 hashBytes.Serialize(s);
594 ser_writedata32be(s, blockHeight);
596 template<typename Stream>
597 void Unserialize(Stream& s) {
598 type = ser_readdata8(s);
599 hashBytes.Unserialize(s);
600 blockHeight = ser_readdata32be(s);
603 CAddressIndexIteratorHeightKey(unsigned int addressType, uint160 addressHash, int height) {
605 hashBytes = addressHash;
606 blockHeight = height;
609 CAddressIndexIteratorHeightKey() {
620 struct CDiskTxPos : public CDiskBlockPos
622 unsigned int nTxOffset; // after header
624 ADD_SERIALIZE_METHODS;
626 template <typename Stream, typename Operation>
627 inline void SerializationOp(Stream& s, Operation ser_action) {
628 READWRITE(*(CDiskBlockPos*)this);
629 READWRITE(VARINT(nTxOffset));
632 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
640 CDiskBlockPos::SetNull();
645 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
648 * Check transaction inputs, and make sure any
649 * pay-to-script-hash transactions are evaluating IsStandard scripts
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
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
664 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId);
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
671 unsigned int GetLegacySigOpCount(const CTransaction& tx);
674 * Count ECDSA signature operations in pay-to-script-hash inputs.
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
680 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
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.
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);
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);
697 /** Apply the effects of this transaction on the UTXO set represented by view */
698 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
700 /** Transaction validation functions */
702 /** Context-independent validity checks */
703 bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier);
704 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state);
706 /** Check for standard transaction types
707 * @return True if all outputs (scriptPubKeys) use only standard transaction forms
709 bool IsStandardTx(const CTransaction& tx, std::string& reason, int nHeight = 0);
711 namespace Consensus {
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.
718 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams);
720 } // namespace Consensus
723 * Check if transaction is final and can be included in a block with the
724 * specified height and time. Consensus critical.
726 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
729 * Check if transaction is expired and can be included in a block with the
730 * specified height. Consensus critical.
732 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight);
735 * Check if transaction will be final in the next block to be created.
737 * Calls IsFinalTx() with current block height and appropriate block time.
739 * See consensus/consensus.h for flag definitions.
741 bool CheckFinalTx(const CTransaction &tx, int flags = -1);
744 * Closure representing one script verification
745 * Note that this stores references to the spending transaction
750 CScript scriptPubKey;
752 const CTransaction *ptxTo;
756 uint32_t consensusBranchId;
758 PrecomputedTransactionData *txdata;
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) { }
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);
780 ScriptError GetScriptError() const { return error; }
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);
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);
797 /** Functions for validating blocks and updating the block tree */
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);
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);
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);
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);
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);
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
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);
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.
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.
841 bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches);
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
854 ADD_SERIALIZE_METHODS;
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));
881 std::string ToString() const;
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;
890 if (nHeightIn > nHeightLast)
891 nHeightLast = nHeightIn;
892 if (nTimeIn > nTimeLast)
897 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
902 bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
905 /** Find the last common block between the parameter chain and a locator. */
906 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
908 /** Mark a block as invalid. */
909 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex);
911 /** Remove invalidity status from a block and its descendants. */
912 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex);
914 /** The currently-connected chain of blocks (protected by cs_main). */
915 extern CChain chainActive;
917 /** Global variable that points to the active CCoinsView (protected by cs_main) */
918 extern CCoinsViewCache *pcoinsTip;
920 /** Global variable that points to the active block tree (protected by cs_main) */
921 extern CBlockTreeDB *pblocktree;
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.
928 int GetSpendHeight(const CCoinsViewCache& inputs);
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);
933 #endif // BITCOIN_MAIN_H