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