]>
Commit | Line | Data |
---|---|---|
0a61b0df | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
f914f1a7 | 2 | // Copyright (c) 2009-2014 The Bitcoin Core developers |
c5b390b6 | 3 | // Distributed under the MIT software license, see the accompanying |
3a25a2b9 | 4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
51ed9ec9 | 5 | |
223b6f1b WL |
6 | #ifndef BITCOIN_MAIN_H |
7 | #define BITCOIN_MAIN_H | |
8 | ||
35b8af92 | 9 | #if defined(HAVE_CONFIG_H) |
f3967bcc | 10 | #include "config/bitcoin-config.h" |
35b8af92 CF |
11 | #endif |
12 | ||
eda37330 | 13 | #include "amount.h" |
e8b5f0d5 | 14 | #include "chain.h" |
51ed9ec9 | 15 | #include "chainparams.h" |
a0fa20a1 | 16 | #include "coins.h" |
691161d4 | 17 | #include "consensus/consensus.h" |
18 | #include "net.h" | |
d2270111 LD |
19 | #include "primitives/block.h" |
20 | #include "primitives/transaction.h" | |
c4408a6c | 21 | #include "script/script.h" |
5c1e798a | 22 | #include "script/sigcache.h" |
c4408a6c | 23 | #include "script/standard.h" |
51ed9ec9 | 24 | #include "sync.h" |
85c579e3 | 25 | #include "tinyformat.h" |
51ed9ec9 BD |
26 | #include "txmempool.h" |
27 | #include "uint256.h" | |
223b6f1b | 28 | |
51ed9ec9 BD |
29 | #include <algorithm> |
30 | #include <exception> | |
31 | #include <map> | |
32 | #include <set> | |
33 | #include <stdint.h> | |
34 | #include <string> | |
35 | #include <utility> | |
36 | #include <vector> | |
0a61b0df | 37 | |
8a41e1ed PW |
38 | #include <boost/unordered_map.hpp> |
39 | ||
0a61b0df | 40 | class CBlockIndex; |
771d5002 | 41 | class CBlockTreeDB; |
51ed9ec9 | 42 | class CBloomFilter; |
40c2614e | 43 | class CInv; |
771d5002 PK |
44 | class CScriptCheck; |
45 | class CValidationInterface; | |
46 | class CValidationState; | |
47 | ||
771d5002 | 48 | struct CNodeStateStats; |
40c2614e | 49 | |
037b4f14 | 50 | /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/ |
e2a6161f | 51 | static const unsigned int DEFAULT_BLOCK_MAX_SIZE = MAX_BLOCK_SIZE; |
037b4f14 | 52 | static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0; |
ad898b40 | 53 | /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/ |
e2a6161f | 54 | static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = DEFAULT_BLOCK_MAX_SIZE / 2; |
4d9c7fe6 WL |
55 | /** Default for accepting alerts from the P2P network. */ |
56 | static const bool DEFAULT_ALERTS = true; | |
a40034f7 JG |
57 | /** Minimum alert priority for enabling safe mode. */ |
58 | static const int ALERT_PRIORITY_SAFE_MODE = 4000; | |
c5b390b6 | 59 | /** Maximum number of signature check operations in an IsStandard() P2SH script */ |
7f3b4e95 | 60 | static const unsigned int MAX_P2SH_SIGOPS = 15; |
9ee09dc6 | 61 | /** The maximum number of sigops we're willing to relay/mine in a single tx */ |
23f34359 | 62 | static const unsigned int MAX_STANDARD_TX_SIGOPS = MAX_BLOCK_SIGOPS/5; |
ba0625f2 | 63 | /** Default for -minrelaytxfee, minimum relay fee for transactions */ |
0f724e71 | 64 | static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 100; |
aa3c697e GA |
65 | /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */ |
66 | static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100; | |
9d6633ac | 67 | /** The maximum size of a blk?????.dat file (since 0.8) */ |
5382bcf8 | 68 | static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB |
9d6633ac | 69 | /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ |
bba89aa8 | 70 | static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB |
9d6633ac | 71 | /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ |
bba89aa8 | 72 | static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB |
f9cae832 PW |
73 | /** Maximum number of script-checking threads allowed */ |
74 | static const int MAX_SCRIPTCHECK_THREADS = 16; | |
5409404d PK |
75 | /** -par default (number of script-checking threads, 0 = auto) */ |
76 | static const int DEFAULT_SCRIPTCHECK_THREADS = 0; | |
f59d8f0b | 77 | /** Number of blocks that can be requested at any given time from a single peer. */ |
341735eb PW |
78 | static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16; |
79 | /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */ | |
80 | static const unsigned int BLOCK_STALLING_TIMEOUT = 2; | |
81 | /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends | |
7e6d23b1 | 82 | * less than this number, we reached its tip. Changing this value is a protocol upgrade. */ |
b93c8139 | 83 | static const unsigned int MAX_HEADERS_RESULTS = 160; |
341735eb PW |
84 | /** Size of the "block download window": how far ahead of our current height do we fetch? |
85 | * Larger windows tolerate larger download speed differences between peer, but increase the potential | |
86 | * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning | |
87 | * harder). We'll probably want to make this a per-peer adaptive value at some point. */ | |
88 | static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; | |
67708acf PW |
89 | /** Time to wait (in seconds) between writing blocks/block index to disk. */ |
90 | static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60; | |
91 | /** Time to wait (in seconds) between flushing chainstate to disk. */ | |
92 | static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60; | |
307f7d48 PW |
93 | /** Maximum length of reject messages. */ |
94 | static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111; | |
f59d8f0b | 95 | |
e2a6161f S |
96 | // Sanity check the magic numbers when we change them |
97 | BOOST_STATIC_ASSERT(DEFAULT_BLOCK_MAX_SIZE <= MAX_BLOCK_SIZE); | |
98 | BOOST_STATIC_ASSERT(DEFAULT_BLOCK_PRIORITY_SIZE <= DEFAULT_BLOCK_MAX_SIZE); | |
99 | ||
c6a7e897 DH |
100 | #define equihash_parameters_acceptable(N, K) \ |
101 | ((CBlockHeader::HEADER_SIZE + equihash_solution_size(N, K))*MAX_HEADERS_RESULTS < \ | |
102 | MAX_PROTOCOL_MESSAGE_LENGTH-1000) | |
103 | ||
8a41e1ed PW |
104 | struct BlockHasher |
105 | { | |
80765854 | 106 | size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); } |
8a41e1ed | 107 | }; |
0a61b0df | 108 | |
7bf8b7c2 | 109 | extern CScript COINBASE_FLAGS; |
0a61b0df | 110 | extern CCriticalSection cs_main; |
319b1160 | 111 | extern CTxMemPool mempool; |
8a41e1ed | 112 | typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap; |
145d5be8 | 113 | extern BlockMap mapBlockIndex; |
51ed9ec9 BD |
114 | extern uint64_t nLastBlockTx; |
115 | extern uint64_t nLastBlockSize; | |
2bc4fd60 | 116 | extern const std::string strMessageMagic; |
ff6a7af1 LD |
117 | extern CWaitableCriticalSection csBestBlock; |
118 | extern CConditionVariable cvBlockChange; | |
1f015f6a | 119 | extern bool fExperimentalMode; |
66b02c93 | 120 | extern bool fImporting; |
7fea4846 | 121 | extern bool fReindex; |
f9cae832 | 122 | extern int nScriptCheckThreads; |
2d1fa42e | 123 | extern bool fTxIndex; |
3da434a2 | 124 | extern bool fIsBareMultisigStd; |
3fcfbc8a | 125 | extern bool fCheckBlockIndex; |
a8cdaf5c | 126 | extern bool fCheckpointsEnabled; |
d212ba32 SB |
127 | // TODO: remove this flag by structuring our code such that |
128 | // it is unneeded for testing | |
129 | extern bool fCoinbaseEnforcedProtectionEnabled; | |
fc684ad8 | 130 | extern size_t nCoinCacheUsage; |
13fc83c7 | 131 | extern CFeeRate minRelayTxFee; |
4d9c7fe6 | 132 | extern bool fAlerts; |
0a61b0df | 133 | |
c5b390b6 | 134 | /** Best header we've seen so far (used for getheaders queries' starting points). */ |
ad6e6017 PW |
135 | extern CBlockIndex *pindexBestHeader; |
136 | ||
c5b390b6 | 137 | /** Minimum disk space required - used in CheckDiskSpace() */ |
51ed9ec9 | 138 | static const uint64_t nMinDiskSpace = 52428800; |
0a61b0df | 139 | |
f9ec3f0f | 140 | /** Pruning-related variables and constants */ |
141 | /** True if any block files have ever been pruned. */ | |
142 | extern bool fHavePruned; | |
143 | /** True if we're running in -prune mode. */ | |
144 | extern bool fPruneMode; | |
145 | /** Number of MiB of block files that we're trying to stay below. */ | |
146 | extern uint64_t nPruneTarget; | |
147 | /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */ | |
148 | static const signed int MIN_BLOCKS_TO_KEEP = 288; | |
149 | ||
150 | // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat) | |
151 | // At 1MB per block, 288 blocks = 288MB. | |
152 | // Add 15% for Undo data = 331MB | |
153 | // Add 20% for Orphan block rate = 397MB | |
154 | // We want the low water mark after pruning to be at least 397 MB and since we prune in | |
155 | // full block file chunks, we need the high water mark which triggers the prune to be | |
156 | // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB | |
157 | // Setting the target to > than 550MB will make it likely we can respect the target. | |
158 | static const signed int MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; | |
159 | ||
501da250 EL |
160 | /** Register with a network node to receive its signals */ |
161 | void RegisterNodeSignals(CNodeSignals& nodeSignals); | |
162 | /** Unregister a network node */ | |
163 | void UnregisterNodeSignals(CNodeSignals& nodeSignals); | |
164 | ||
c5b390b6 MF |
165 | /** |
166 | * Process an incoming block. This only returns after the best known valid | |
167 | * block is made active. Note that it does not, however, guarantee that the | |
168 | * specific block passed to it has been checked for validity! | |
169 | * | |
26c16d9d | 170 | * @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. |
c5b390b6 MF |
171 | * @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. |
172 | * @param[in] pblock The block we want to process. | |
304892fc | 173 | * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers. |
c5b390b6 MF |
174 | * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location. |
175 | * @return True if state.IsValid() | |
176 | */ | |
304892fc | 177 | bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp); |
160b028b | 178 | /** Check whether enough disk space is available for an incoming block */ |
51ed9ec9 | 179 | bool CheckDiskSpace(uint64_t nAdditionalBytes = 0); |
160b028b | 180 | /** Open a block file (blk?????.dat) */ |
5382bcf8 | 181 | FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
160b028b | 182 | /** Open an undo file (rev?????.dat) */ |
5382bcf8 | 183 | FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
ec7eb0fa SD |
184 | /** Translation to a filesystem path */ |
185 | boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix); | |
160b028b | 186 | /** Import blocks from an external file */ |
7fea4846 | 187 | bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL); |
38603761 PW |
188 | /** Initialize a new block tree database + block data on disk */ |
189 | bool InitBlockIndex(); | |
160b028b | 190 | /** Load the block tree and coins database from disk */ |
7fea4846 | 191 | bool LoadBlockIndex(); |
f7f3a96b PW |
192 | /** Unload database information */ |
193 | void UnloadBlockIndex(); | |
160b028b | 194 | /** Process protocol messages received from a given node */ |
0a61b0df | 195 | bool ProcessMessages(CNode* pfrom); |
fc720207 RV |
196 | /** |
197 | * Send queued protocol messages to be sent to a give node. | |
198 | * | |
199 | * @param[in] pto The node which we are sending messages to. | |
200 | * @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true. | |
201 | */ | |
0a61b0df | 202 | bool SendMessages(CNode* pto, bool fSendTrickle); |
f9cae832 | 203 | /** Run an instance of the script checking thread */ |
21eb5ada | 204 | void ThreadScriptCheck(); |
36cba8f1 | 205 | /** Try to detect Partition (network isolation) attacks against us */ |
fce474c9 | 206 | void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing); |
f0bf5fb2 | 207 | /** Check whether we are doing an initial block download (synchronizing from disk or network) */ |
0a61b0df | 208 | bool IsInitialBlockDownload(); |
160b028b | 209 | /** Format a string that describes several potential problems detected by the core */ |
db954a65 | 210 | std::string GetWarnings(const std::string& strFor); |
160b028b | 211 | /** Retrieve a transaction (from memory pool, or from disk, if possible) */ |
450cbb09 | 212 | bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false); |
160b028b | 213 | /** Find the best known block, and make it the tip of the block chain */ |
92bb6f2f | 214 | bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL); |
935bd0a4 | 215 | CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams); |
aabdf9e8 | 216 | |
f9ec3f0f | 217 | /** |
218 | * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target. | |
219 | * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new | |
220 | * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex | |
221 | * (which in this case means the blockchain must be re-downloaded.) | |
222 | * | |
223 | * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set. | |
224 | * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.) | |
225 | * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 10 on regtest). | |
226 | * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip. | |
227 | * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files. | |
228 | * A db flag records the fact that at least some block files have been pruned. | |
229 | * | |
230 | * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned | |
231 | */ | |
232 | void FindFilesToPrune(std::set<int>& setFilesToPrune); | |
233 | ||
234 | /** | |
235 | * Actually unlink the specified files | |
236 | */ | |
237 | void UnlinkPrunedFiles(std::set<int>& setFilesToPrune); | |
238 | ||
160b028b | 239 | /** Create a new block index entry for a given block hash */ |
2d8a4829 | 240 | CBlockIndex * InsertBlockIndex(uint256 hash); |
b2864d2f PW |
241 | /** Get statistics from node state */ |
242 | bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats); | |
f59d8f0b PW |
243 | /** Increase a node's misbehavior score. */ |
244 | void Misbehaving(NodeId nodeid, int howmuch); | |
51ce901a PW |
245 | /** Flush all state, indexes and buffers to disk. */ |
246 | void FlushStateToDisk(); | |
f9ec3f0f | 247 | /** Prune block files and flush state to disk. */ |
248 | void PruneAndFlush(); | |
857c61df | 249 | |
319b1160 GA |
250 | /** (try to) add transaction to memory pool **/ |
251 | bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, | |
1371e6f5 | 252 | bool* pfMissingInputs, bool fRejectAbsurdFee=false); |
0a61b0df | 253 | |
254 | ||
b2864d2f PW |
255 | struct CNodeStateStats { |
256 | int nMisbehavior; | |
aa815647 | 257 | int nSyncHeight; |
ad6e6017 PW |
258 | int nCommonHeight; |
259 | std::vector<int> vHeightInFlight; | |
b2864d2f PW |
260 | }; |
261 | ||
2d1fa42e PW |
262 | struct CDiskTxPos : public CDiskBlockPos |
263 | { | |
264 | unsigned int nTxOffset; // after header | |
265 | ||
3f6540ad | 266 | ADD_SERIALIZE_METHODS; |
3d796f89 | 267 | |
84881f8c | 268 | template <typename Stream, typename Operation> |
31e9a838 | 269 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
2d1fa42e PW |
270 | READWRITE(*(CDiskBlockPos*)this); |
271 | READWRITE(VARINT(nTxOffset)); | |
3d796f89 | 272 | } |
2d1fa42e PW |
273 | |
274 | CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { | |
275 | } | |
276 | ||
277 | CDiskTxPos() { | |
278 | SetNull(); | |
279 | } | |
0a61b0df | 280 | |
2d1fa42e PW |
281 | void SetNull() { |
282 | CDiskBlockPos::SetNull(); | |
283 | nTxOffset = 0; | |
284 | } | |
285 | }; | |
0a61b0df | 286 | |
287 | ||
a372168e | 288 | CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree); |
788536f1 | 289 | |
c5b390b6 MF |
290 | /** |
291 | * Check transaction inputs, and make sure any | |
292 | * pay-to-script-hash transactions are evaluating IsStandard scripts | |
293 | * | |
294 | * Why bother? To avoid denial-of-service attacks; an attacker | |
295 | * can submit a standard HASH... OP_EQUAL transaction, | |
296 | * which will get accepted into blocks. The redemption | |
297 | * script can be anything; an attacker could use a very | |
298 | * expensive-to-check-upon-redemption script like: | |
299 | * DUP CHECKSIG DROP ... repeated 100 times... OP_1 | |
300 | */ | |
922e8e29 | 301 | |
c5b390b6 MF |
302 | /** |
303 | * Check for standard transaction types | |
304 | * @param[in] mapInputs Map of previous transactions that have outputs we're spending | |
305 | * @return True if all inputs (scriptSigs) use only standard transaction forms | |
306 | */ | |
d0867acb | 307 | bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs); |
8d7849b6 | 308 | |
c5b390b6 MF |
309 | /** |
310 | * Count ECDSA signature operations the old-fashioned (pre-0.6) way | |
311 | * @return number of sigops this transaction's outputs will produce when spent | |
312 | * @see CTransaction::FetchInputs | |
313 | */ | |
05df3fc6 | 314 | unsigned int GetLegacySigOpCount(const CTransaction& tx); |
a206a239 | 315 | |
c5b390b6 MF |
316 | /** |
317 | * Count ECDSA signature operations in pay-to-script-hash inputs. | |
318 | * | |
319 | * @param[in] mapInputs Map of previous transactions that have outputs we're spending | |
320 | * @return maximum number of sigops required to validate this transaction's inputs | |
321 | * @see CTransaction::FetchInputs | |
05df3fc6 | 322 | */ |
d0867acb | 323 | unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs); |
0a61b0df | 324 | |
0a61b0df | 325 | |
c5b390b6 MF |
326 | /** |
327 | * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) | |
328 | * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it | |
329 | * instead of being performed inline. | |
330 | */ | |
10df6fb3 | 331 | bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks, |
c0dde76d SB |
332 | unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, |
333 | std::vector<CScriptCheck> *pvChecks = NULL); | |
0a61b0df | 334 | |
2c901fd8 | 335 | bool NonContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks, |
c0dde76d SB |
336 | unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, |
337 | std::vector<CScriptCheck> *pvChecks = NULL); | |
2c901fd8 | 338 | |
c5b390b6 | 339 | /** Apply the effects of this transaction on the UTXO set represented by view */ |
d7621ccf | 340 | void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight); |
8d7849b6 | 341 | |
c5b390b6 | 342 | /** Context-independent validity checks */ |
6fb8d0c2 | 343 | bool CheckTransaction(const CTransaction& tx, CValidationState& state, libzcash::ProofVerifier& verifier); |
948d4e6c | 344 | bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state); |
450cbb09 | 345 | |
05df3fc6 | 346 | /** Check for standard transaction types |
c5b390b6 MF |
347 | * @return True if all outputs (scriptPubKeys) use only standard transaction forms |
348 | */ | |
980bfe6e | 349 | bool IsStandardTx(const CTransaction& tx, std::string& reason); |
450cbb09 | 350 | |
75a4d512 PT |
351 | /** |
352 | * Check if transaction is final and can be included in a block with the | |
353 | * specified height and time. Consensus critical. | |
354 | */ | |
355 | bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime); | |
356 | ||
357 | /** | |
358 | * Check if transaction will be final in the next block to be created. | |
359 | * | |
360 | * Calls IsFinalTx() with current block height and appropriate block time. | |
a1d3c6fb MF |
361 | * |
362 | * See consensus/consensus.h for flag definitions. | |
75a4d512 | 363 | */ |
a1d3c6fb | 364 | bool CheckFinalTx(const CTransaction &tx, int flags = -1); |
450cbb09 | 365 | |
c5b390b6 MF |
366 | /** |
367 | * Closure representing one script verification | |
368 | * Note that this stores references to the spending transaction | |
369 | */ | |
2800ce73 PW |
370 | class CScriptCheck |
371 | { | |
372 | private: | |
373 | CScript scriptPubKey; | |
374 | const CTransaction *ptxTo; | |
375 | unsigned int nIn; | |
376 | unsigned int nFlags; | |
e790c370 | 377 | bool cacheStore; |
307f7d48 | 378 | ScriptError error; |
0a61b0df | 379 | |
2800ce73 | 380 | public: |
307f7d48 | 381 | CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {} |
e790c370 | 382 | CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) : |
2800ce73 | 383 | scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), |
307f7d48 | 384 | ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) { } |
2800ce73 | 385 | |
307f7d48 | 386 | bool operator()(); |
2800ce73 PW |
387 | |
388 | void swap(CScriptCheck &check) { | |
389 | scriptPubKey.swap(check.scriptPubKey); | |
390 | std::swap(ptxTo, check.ptxTo); | |
391 | std::swap(nIn, check.nIn); | |
392 | std::swap(nFlags, check.nFlags); | |
e790c370 | 393 | std::swap(cacheStore, check.cacheStore); |
307f7d48 | 394 | std::swap(error, check.error); |
2800ce73 | 395 | } |
307f7d48 PW |
396 | |
397 | ScriptError GetScriptError() const { return error; } | |
2800ce73 | 398 | }; |
0a61b0df | 399 | |
0a61b0df | 400 | |
a6dba0fd | 401 | /** Functions for disk access for blocks */ |
e6973430 | 402 | bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart); |
80313994 | 403 | bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos); |
7db120d5 | 404 | bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex); |
0a61b0df | 405 | |
406 | ||
5c363ed6 EL |
407 | /** Functions for validating blocks and updating the block tree */ |
408 | ||
409 | /** Undo the effects of this block (with given index) on the UTXO set represented by coins. | |
410 | * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean | |
411 | * will be true if no problems were found. Otherwise, the return value will be false in case | |
412 | * of problems. Note that in any case, coins may be modified. */ | |
413 | bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL); | |
414 | ||
c5b390b6 | 415 | /** Apply the effects of this block (with given index) on the UTXO set represented by coins */ |
df08a626 | 416 | bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false); |
f3ae51dc | 417 | |
c5b390b6 | 418 | /** Context-independent validity checks */ |
f4573470 | 419 | bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true); |
6fb8d0c2 JG |
420 | bool CheckBlock(const CBlock& block, CValidationState& state, |
421 | libzcash::ProofVerifier& verifier, | |
422 | bool fCheckPOW = true, bool fCheckMerkleRoot = true); | |
38991ffa | 423 | |
c5b390b6 | 424 | /** Context-dependent validity checks */ |
a48f2d6d LD |
425 | bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex *pindexPrev); |
426 | bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex *pindexPrev); | |
427 | ||
c5b390b6 | 428 | /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */ |
df08a626 LD |
429 | bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex *pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true); |
430 | ||
6fb8d0c2 JG |
431 | /** |
432 | * Store block on disk. | |
433 | * JoinSplit proofs are never verified, because: | |
434 | * - AcceptBlock doesn't perform script checks either. | |
435 | * - The only caller of AcceptBlock verifies JoinSplit proofs elsewhere. | |
436 | * If dbp is non-NULL, the file is known to already reside on disk | |
437 | */ | |
304892fc | 438 | bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, bool fRequested, CDiskBlockPos* dbp); |
341735eb | 439 | bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL); |
2a4d3464 | 440 | |
5c363ed6 EL |
441 | |
442 | ||
5382bcf8 PW |
443 | class CBlockFileInfo |
444 | { | |
445 | public: | |
c5b390b6 MF |
446 | unsigned int nBlocks; //! number of blocks stored in file |
447 | unsigned int nSize; //! number of used bytes of block file | |
448 | unsigned int nUndoSize; //! number of used bytes in the undo file | |
449 | unsigned int nHeightFirst; //! lowest height of block in file | |
450 | unsigned int nHeightLast; //! highest height of block in file | |
451 | uint64_t nTimeFirst; //! earliest time of block in file | |
452 | uint64_t nTimeLast; //! latest time of block in file | |
5382bcf8 | 453 | |
3f6540ad | 454 | ADD_SERIALIZE_METHODS; |
3d796f89 | 455 | |
84881f8c | 456 | template <typename Stream, typename Operation> |
31e9a838 | 457 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
5382bcf8 PW |
458 | READWRITE(VARINT(nBlocks)); |
459 | READWRITE(VARINT(nSize)); | |
460 | READWRITE(VARINT(nUndoSize)); | |
461 | READWRITE(VARINT(nHeightFirst)); | |
462 | READWRITE(VARINT(nHeightLast)); | |
463 | READWRITE(VARINT(nTimeFirst)); | |
464 | READWRITE(VARINT(nTimeLast)); | |
3d796f89 | 465 | } |
5382bcf8 PW |
466 | |
467 | void SetNull() { | |
468 | nBlocks = 0; | |
469 | nSize = 0; | |
470 | nUndoSize = 0; | |
471 | nHeightFirst = 0; | |
472 | nHeightLast = 0; | |
473 | nTimeFirst = 0; | |
474 | nTimeLast = 0; | |
475 | } | |
476 | ||
477 | CBlockFileInfo() { | |
478 | SetNull(); | |
479 | } | |
480 | ||
651480c8 | 481 | std::string ToString() const; |
5382bcf8 | 482 | |
c5b390b6 | 483 | /** update statistics (does not update nSize) */ |
51ed9ec9 | 484 | void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) { |
5382bcf8 PW |
485 | if (nBlocks==0 || nHeightFirst > nHeightIn) |
486 | nHeightFirst = nHeightIn; | |
487 | if (nBlocks==0 || nTimeFirst > nTimeIn) | |
488 | nTimeFirst = nTimeIn; | |
489 | nBlocks++; | |
367c29d6 | 490 | if (nHeightIn > nHeightLast) |
5382bcf8 PW |
491 | nHeightLast = nHeightIn; |
492 | if (nTimeIn > nTimeLast) | |
493 | nTimeLast = nTimeIn; | |
494 | } | |
495 | }; | |
496 | ||
06a91d96 CL |
497 | /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ |
498 | class CVerifyDB { | |
499 | public: | |
06a91d96 CL |
500 | CVerifyDB(); |
501 | ~CVerifyDB(); | |
2e280311 | 502 | bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth); |
06a91d96 CL |
503 | }; |
504 | ||
6db83db3 | 505 | /** Find the last common block between the parameter chain and a locator. */ |
506 | CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator); | |
0a61b0df | 507 | |
9b0a8d31 PW |
508 | /** Mark a block as invalid. */ |
509 | bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex); | |
510 | ||
511 | /** Remove invalidity status from a block and its descendants. */ | |
512 | bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex); | |
513 | ||
4c6d41b8 PW |
514 | /** The currently-connected chain of blocks. */ |
515 | extern CChain chainActive; | |
0a61b0df | 516 | |
d979e6e3 | 517 | /** Global variable that points to the active CCoinsView (protected by cs_main) */ |
ae8bfd12 PW |
518 | extern CCoinsViewCache *pcoinsTip; |
519 | ||
d979e6e3 PW |
520 | /** Global variable that points to the active block tree (protected by cs_main) */ |
521 | extern CBlockTreeDB *pblocktree; | |
522 | ||
093303a8 | 523 | #endif // BITCOIN_MAIN_H |