]>
Commit | Line | Data |
---|---|---|
0a61b0df | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
57702541 | 2 | // Copyright (c) 2009-2014 The Bitcoin developers |
0a61b0df | 3 | // Distributed under the MIT/X11 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 | ||
e8b5f0d5 | 13 | #include "chain.h" |
51ed9ec9 | 14 | #include "chainparams.h" |
a0fa20a1 | 15 | #include "coins.h" |
51ed9ec9 | 16 | #include "core.h" |
223b6f1b | 17 | #include "net.h" |
b343c1a1 | 18 | #include "pow.h" |
c4408a6c | 19 | #include "script/script.h" |
20 | #include "script/standard.h" | |
51ed9ec9 BD |
21 | #include "sync.h" |
22 | #include "txmempool.h" | |
23 | #include "uint256.h" | |
223b6f1b | 24 | |
51ed9ec9 BD |
25 | #include <algorithm> |
26 | #include <exception> | |
27 | #include <map> | |
28 | #include <set> | |
29 | #include <stdint.h> | |
30 | #include <string> | |
31 | #include <utility> | |
32 | #include <vector> | |
0a61b0df | 33 | |
8a41e1ed PW |
34 | #include <boost/unordered_map.hpp> |
35 | ||
0a61b0df | 36 | class CBlockIndex; |
51ed9ec9 | 37 | class CBloomFilter; |
40c2614e | 38 | class CInv; |
40c2614e | 39 | |
9d6633ac | 40 | /** The maximum allowed size for a serialized block, in bytes (network rule) */ |
0a61b0df | 41 | static const unsigned int MAX_BLOCK_SIZE = 1000000; |
037b4f14 | 42 | /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/ |
ad898b40 | 43 | static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000; |
037b4f14 | 44 | static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0; |
ad898b40 GA |
45 | /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/ |
46 | static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000; | |
69e07747 | 47 | /** The maximum size for transactions we're willing to relay/mine */ |
ad898b40 | 48 | static const unsigned int MAX_STANDARD_TX_SIZE = 100000; |
9d6633ac | 49 | /** The maximum allowed number of signature check operations in a block (network rule) */ |
7bd9c3a3 | 50 | static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; |
7f3b4e95 GA |
51 | /** Maxiumum number of signature check operations in an IsStandard() P2SH script */ |
52 | static const unsigned int MAX_P2SH_SIGOPS = 15; | |
9ee09dc6 PT |
53 | /** The maximum number of sigops we're willing to relay/mine in a single tx */ |
54 | static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5; | |
aa3c697e GA |
55 | /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */ |
56 | static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100; | |
7b45d943 | 57 | /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */ |
58 | static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750; | |
9d6633ac | 59 | /** The maximum size of a blk?????.dat file (since 0.8) */ |
5382bcf8 | 60 | static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB |
9d6633ac | 61 | /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ |
bba89aa8 | 62 | static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB |
9d6633ac | 63 | /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ |
bba89aa8 | 64 | static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB |
9d6633ac | 65 | /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ |
0a61b0df | 66 | static const int COINBASE_MATURITY = 100; |
9d6633ac | 67 | /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ |
f621326c | 68 | static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC |
f9cae832 PW |
69 | /** Maximum number of script-checking threads allowed */ |
70 | static const int MAX_SCRIPTCHECK_THREADS = 16; | |
5409404d PK |
71 | /** -par default (number of script-checking threads, 0 = auto) */ |
72 | static const int DEFAULT_SCRIPTCHECK_THREADS = 0; | |
f59d8f0b PW |
73 | /** Number of blocks that can be requested at any given time from a single peer. */ |
74 | static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128; | |
75 | /** Timeout in seconds before considering a block download peer unresponsive. */ | |
76 | static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60; | |
77 | ||
358ce266 GA |
78 | /** "reject" message codes **/ |
79 | static const unsigned char REJECT_MALFORMED = 0x01; | |
80 | static const unsigned char REJECT_INVALID = 0x10; | |
81 | static const unsigned char REJECT_OBSOLETE = 0x11; | |
82 | static const unsigned char REJECT_DUPLICATE = 0x12; | |
83 | static const unsigned char REJECT_NONSTANDARD = 0x40; | |
84 | static const unsigned char REJECT_DUST = 0x41; | |
85 | static const unsigned char REJECT_INSUFFICIENTFEE = 0x42; | |
86 | static const unsigned char REJECT_CHECKPOINT = 0x43; | |
87 | ||
8a41e1ed PW |
88 | struct BlockHasher |
89 | { | |
90 | size_t operator()(const uint256& hash) const { return hash.GetLow64(); } | |
91 | }; | |
0a61b0df | 92 | |
7bf8b7c2 | 93 | extern CScript COINBASE_FLAGS; |
0a61b0df | 94 | extern CCriticalSection cs_main; |
319b1160 | 95 | extern CTxMemPool mempool; |
8a41e1ed | 96 | typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap; |
145d5be8 | 97 | extern BlockMap mapBlockIndex; |
51ed9ec9 BD |
98 | extern uint64_t nLastBlockTx; |
99 | extern uint64_t nLastBlockSize; | |
2bc4fd60 | 100 | extern const std::string strMessageMagic; |
51ed9ec9 | 101 | extern int64_t nTimeBestReceived; |
ff6a7af1 LD |
102 | extern CWaitableCriticalSection csBestBlock; |
103 | extern CConditionVariable cvBlockChange; | |
66b02c93 | 104 | extern bool fImporting; |
7fea4846 | 105 | extern bool fReindex; |
f9cae832 | 106 | extern int nScriptCheckThreads; |
2d1fa42e | 107 | extern bool fTxIndex; |
3da434a2 | 108 | extern bool fIsBareMultisigStd; |
1c83b0a3 | 109 | extern unsigned int nCoinCacheSize; |
13fc83c7 | 110 | extern CFeeRate minRelayTxFee; |
0a61b0df | 111 | |
966ae00f | 112 | // Minimum disk space required - used in CheckDiskSpace() |
51ed9ec9 | 113 | static const uint64_t nMinDiskSpace = 52428800; |
0a61b0df | 114 | |
115 | ||
d979e6e3 | 116 | class CBlockTreeDB; |
450cbb09 | 117 | class CTxUndo; |
f9cae832 | 118 | class CScriptCheck; |
ef3988ca | 119 | class CValidationState; |
00588c3f | 120 | class CWalletInterface; |
b2864d2f | 121 | struct CNodeStateStats; |
0a61b0df | 122 | |
03cac0bb FV |
123 | struct CBlockTemplate; |
124 | ||
160b028b | 125 | /** Register a wallet to receive updates from core */ |
00588c3f | 126 | void RegisterWallet(CWalletInterface* pwalletIn); |
160b028b | 127 | /** Unregister a wallet from core */ |
00588c3f | 128 | void UnregisterWallet(CWalletInterface* pwalletIn); |
e6fe8e77 EL |
129 | /** Unregister all wallets from core */ |
130 | void UnregisterAllWallets(); | |
160b028b | 131 | /** Push an updated transaction to all registered wallets */ |
d38da59b | 132 | void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL); |
8926263d | 133 | |
501da250 EL |
134 | /** Register with a network node to receive its signals */ |
135 | void RegisterNodeSignals(CNodeSignals& nodeSignals); | |
136 | /** Unregister a network node */ | |
137 | void UnregisterNodeSignals(CNodeSignals& nodeSignals); | |
138 | ||
8926263d EL |
139 | void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd); |
140 | ||
160b028b | 141 | /** Process an incoming block */ |
ef3988ca | 142 | bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL); |
160b028b | 143 | /** Check whether enough disk space is available for an incoming block */ |
51ed9ec9 | 144 | bool CheckDiskSpace(uint64_t nAdditionalBytes = 0); |
160b028b | 145 | /** Open a block file (blk?????.dat) */ |
5382bcf8 | 146 | FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
160b028b | 147 | /** Open an undo file (rev?????.dat) */ |
5382bcf8 | 148 | FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
ec7eb0fa SD |
149 | /** Translation to a filesystem path */ |
150 | boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix); | |
160b028b | 151 | /** Import blocks from an external file */ |
7fea4846 | 152 | bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL); |
38603761 PW |
153 | /** Initialize a new block tree database + block data on disk */ |
154 | bool InitBlockIndex(); | |
160b028b | 155 | /** Load the block tree and coins database from disk */ |
7fea4846 | 156 | bool LoadBlockIndex(); |
f7f3a96b PW |
157 | /** Unload database information */ |
158 | void UnloadBlockIndex(); | |
160b028b | 159 | /** Print the loaded block tree */ |
0a61b0df | 160 | void PrintBlockTree(); |
160b028b | 161 | /** Process protocol messages received from a given node */ |
0a61b0df | 162 | bool ProcessMessages(CNode* pfrom); |
160b028b | 163 | /** Send queued protocol messages to be sent to a give node */ |
0a61b0df | 164 | bool SendMessages(CNode* pto, bool fSendTrickle); |
f9cae832 | 165 | /** Run an instance of the script checking thread */ |
21eb5ada | 166 | void ThreadScriptCheck(); |
f0bf5fb2 | 167 | /** Check whether we are doing an initial block download (synchronizing from disk or network) */ |
0a61b0df | 168 | bool IsInitialBlockDownload(); |
160b028b | 169 | /** Format a string that describes several potential problems detected by the core */ |
223b6f1b | 170 | std::string GetWarnings(std::string strFor); |
160b028b | 171 | /** Retrieve a transaction (from memory pool, or from disk, if possible) */ |
450cbb09 | 172 | bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false); |
160b028b | 173 | /** Find the best known block, and make it the tip of the block chain */ |
92bb6f2f | 174 | bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL); |
a372168e | 175 | CAmount GetBlockValue(int nHeight, const CAmount& nFees); |
aabdf9e8 | 176 | |
160b028b | 177 | /** Create a new block index entry for a given block hash */ |
2d8a4829 | 178 | CBlockIndex * InsertBlockIndex(uint256 hash); |
7851033d PW |
179 | /** Abort with a message */ |
180 | bool AbortNode(const std::string &msg); | |
b2864d2f PW |
181 | /** Get statistics from node state */ |
182 | bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats); | |
f59d8f0b PW |
183 | /** Increase a node's misbehavior score. */ |
184 | void Misbehaving(NodeId nodeid, int howmuch); | |
185 | ||
857c61df | 186 | |
319b1160 GA |
187 | /** (try to) add transaction to memory pool **/ |
188 | bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, | |
189 | bool* pfMissingInputs, bool fRejectInsaneFee=false); | |
0a61b0df | 190 | |
191 | ||
b2864d2f PW |
192 | struct CNodeStateStats { |
193 | int nMisbehavior; | |
aa815647 | 194 | int nSyncHeight; |
b2864d2f PW |
195 | }; |
196 | ||
2d1fa42e PW |
197 | struct CDiskTxPos : public CDiskBlockPos |
198 | { | |
199 | unsigned int nTxOffset; // after header | |
200 | ||
3f6540ad | 201 | ADD_SERIALIZE_METHODS; |
3d796f89 | 202 | |
84881f8c | 203 | template <typename Stream, typename Operation> |
31e9a838 | 204 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
2d1fa42e PW |
205 | READWRITE(*(CDiskBlockPos*)this); |
206 | READWRITE(VARINT(nTxOffset)); | |
3d796f89 | 207 | } |
2d1fa42e PW |
208 | |
209 | CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { | |
210 | } | |
211 | ||
212 | CDiskTxPos() { | |
213 | SetNull(); | |
214 | } | |
0a61b0df | 215 | |
2d1fa42e PW |
216 | void SetNull() { |
217 | CDiskBlockPos::SetNull(); | |
218 | nTxOffset = 0; | |
219 | } | |
220 | }; | |
0a61b0df | 221 | |
222 | ||
a372168e | 223 | CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree); |
788536f1 | 224 | |
05df3fc6 EL |
225 | // |
226 | // Check transaction inputs, and make sure any | |
227 | // pay-to-script-hash transactions are evaluating IsStandard scripts | |
228 | // | |
229 | // Why bother? To avoid denial-of-service attacks; an attacker | |
230 | // can submit a standard HASH... OP_EQUAL transaction, | |
231 | // which will get accepted into blocks. The redemption | |
232 | // script can be anything; an attacker could use a very | |
233 | // expensive-to-check-upon-redemption script like: | |
234 | // DUP CHECKSIG DROP ... repeated 100 times... OP_1 | |
235 | // | |
922e8e29 | 236 | |
e935293e MF |
237 | /** Check for standard transaction types |
238 | @param[in] mapInputs Map of previous transactions that have outputs we're spending | |
239 | @return True if all inputs (scriptSigs) use only standard transaction forms | |
240 | */ | |
d0867acb | 241 | bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs); |
8d7849b6 | 242 | |
05df3fc6 EL |
243 | /** Count ECDSA signature operations the old-fashioned (pre-0.6) way |
244 | @return number of sigops this transaction's outputs will produce when spent | |
245 | @see CTransaction::FetchInputs | |
246 | */ | |
247 | unsigned int GetLegacySigOpCount(const CTransaction& tx); | |
a206a239 | 248 | |
05df3fc6 | 249 | /** Count ECDSA signature operations in pay-to-script-hash inputs. |
0a61b0df | 250 | |
05df3fc6 EL |
251 | @param[in] mapInputs Map of previous transactions that have outputs we're spending |
252 | @return maximum number of sigops required to validate this transaction's inputs | |
253 | @see CTransaction::FetchInputs | |
254 | */ | |
d0867acb | 255 | unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs); |
0a61b0df | 256 | |
0a61b0df | 257 | |
05df3fc6 EL |
258 | // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) |
259 | // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it | |
260 | // instead of being performed inline. | |
d0867acb | 261 | bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks = true, |
68f7d1d7 | 262 | unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS, |
05df3fc6 | 263 | std::vector<CScriptCheck> *pvChecks = NULL); |
0a61b0df | 264 | |
05df3fc6 | 265 | // Apply the effects of this transaction on the UTXO set represented by view |
d38da59b | 266 | void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight); |
8d7849b6 | 267 | |
05df3fc6 EL |
268 | // Context-independent validity checks |
269 | bool CheckTransaction(const CTransaction& tx, CValidationState& state); | |
450cbb09 | 270 | |
05df3fc6 EL |
271 | /** Check for standard transaction types |
272 | @return True if all outputs (scriptPubKeys) use only standard transaction forms | |
273 | */ | |
980bfe6e | 274 | bool IsStandardTx(const CTransaction& tx, std::string& reason); |
450cbb09 | 275 | |
51ed9ec9 | 276 | bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0); |
450cbb09 | 277 | |
8adf48dc PW |
278 | /** Undo information for a CBlock */ |
279 | class CBlockUndo | |
280 | { | |
281 | public: | |
450cbb09 | 282 | std::vector<CTxUndo> vtxundo; // for all but the coinbase |
8adf48dc | 283 | |
3f6540ad | 284 | ADD_SERIALIZE_METHODS; |
3d796f89 | 285 | |
84881f8c | 286 | template <typename Stream, typename Operation> |
31e9a838 | 287 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
8adf48dc | 288 | READWRITE(vtxundo); |
3d796f89 | 289 | } |
5382bcf8 | 290 | |
651480c8 WL |
291 | bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock); |
292 | bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock); | |
8adf48dc PW |
293 | }; |
294 | ||
0a61b0df | 295 | |
2800ce73 PW |
296 | /** Closure representing one script verification |
297 | * Note that this stores references to the spending transaction */ | |
298 | class CScriptCheck | |
299 | { | |
300 | private: | |
301 | CScript scriptPubKey; | |
302 | const CTransaction *ptxTo; | |
303 | unsigned int nIn; | |
304 | unsigned int nFlags; | |
0a61b0df | 305 | |
2800ce73 | 306 | public: |
ce3649fb | 307 | CScriptCheck(): ptxTo(0), nIn(0), nFlags(0) {} |
308 | CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn) : | |
2800ce73 | 309 | scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), |
ce3649fb | 310 | ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn) { } |
2800ce73 PW |
311 | |
312 | bool operator()() const; | |
313 | ||
314 | void swap(CScriptCheck &check) { | |
315 | scriptPubKey.swap(check.scriptPubKey); | |
316 | std::swap(ptxTo, check.ptxTo); | |
317 | std::swap(nIn, check.nIn); | |
318 | std::swap(nFlags, check.nFlags); | |
2800ce73 PW |
319 | } |
320 | }; | |
0a61b0df | 321 | |
4bedfa92 PW |
322 | /** Data structure that represents a partial merkle tree. |
323 | * | |
324 | * It respresents a subset of the txid's of a known block, in a way that | |
325 | * allows recovery of the list of txid's and the merkle root, in an | |
326 | * authenticated way. | |
327 | * | |
328 | * The encoding works as follows: we traverse the tree in depth-first order, | |
329 | * storing a bit for each traversed node, signifying whether the node is the | |
330 | * parent of at least one matched leaf txid (or a matched txid itself). In | |
331 | * case we are at the leaf level, or this bit is 0, its merkle node hash is | |
332 | * stored, and its children are not explorer further. Otherwise, no hash is | |
333 | * stored, but we recurse into both (or the only) child branch. During | |
334 | * decoding, the same depth-first traversal is performed, consuming bits and | |
335 | * hashes as they written during encoding. | |
336 | * | |
337 | * The serialization is fixed and provides a hard guarantee about the | |
338 | * encoded size: | |
339 | * | |
340 | * SIZE <= 10 + ceil(32.25*N) | |
341 | * | |
342 | * Where N represents the number of leaf nodes of the partial tree. N itself | |
343 | * is bounded by: | |
344 | * | |
345 | * N <= total_transactions | |
346 | * N <= 1 + matched_transactions*tree_height | |
347 | * | |
348 | * The serialization format: | |
349 | * - uint32 total_transactions (4 bytes) | |
350 | * - varint number of hashes (1-3 bytes) | |
351 | * - uint256[] hashes in depth-first order (<= 32*N bytes) | |
352 | * - varint number of bytes of flag bits (1-3 bytes) | |
353 | * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits) | |
354 | * The size constraints follow from this. | |
355 | */ | |
356 | class CPartialMerkleTree | |
357 | { | |
358 | protected: | |
359 | // the total number of transactions in the block | |
360 | unsigned int nTransactions; | |
361 | ||
362 | // node-is-parent-of-matched-txid bits | |
363 | std::vector<bool> vBits; | |
364 | ||
365 | // txids and internal hashes | |
366 | std::vector<uint256> vHash; | |
0a61b0df | 367 | |
4bedfa92 PW |
368 | // flag set when encountering invalid data |
369 | bool fBad; | |
0a61b0df | 370 | |
4bedfa92 PW |
371 | // helper function to efficiently calculate the number of nodes at given height in the merkle tree |
372 | unsigned int CalcTreeWidth(int height) { | |
373 | return (nTransactions+(1 << height)-1) >> height; | |
374 | } | |
375 | ||
376 | // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself) | |
377 | uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid); | |
378 | ||
379 | // recursive function that traverses tree nodes, storing the data as bits and hashes | |
380 | void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); | |
381 | ||
382 | // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. | |
383 | // it returns the hash of the respective node. | |
384 | uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch); | |
385 | ||
386 | public: | |
0a61b0df | 387 | |
4bedfa92 | 388 | // serialization implementation |
3f6540ad | 389 | ADD_SERIALIZE_METHODS; |
3d796f89 | 390 | |
84881f8c | 391 | template <typename Stream, typename Operation> |
31e9a838 | 392 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
4bedfa92 PW |
393 | READWRITE(nTransactions); |
394 | READWRITE(vHash); | |
395 | std::vector<unsigned char> vBytes; | |
47eb7659 | 396 | if (ser_action.ForRead()) { |
4bedfa92 PW |
397 | READWRITE(vBytes); |
398 | CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this)); | |
399 | us.vBits.resize(vBytes.size() * 8); | |
400 | for (unsigned int p = 0; p < us.vBits.size(); p++) | |
401 | us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0; | |
402 | us.fBad = false; | |
403 | } else { | |
404 | vBytes.resize((vBits.size()+7)/8); | |
405 | for (unsigned int p = 0; p < vBits.size(); p++) | |
406 | vBytes[p / 8] |= vBits[p] << (p % 8); | |
407 | READWRITE(vBytes); | |
408 | } | |
3d796f89 | 409 | } |
4bedfa92 PW |
410 | |
411 | // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them | |
412 | CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); | |
0a61b0df | 413 | |
4bedfa92 | 414 | CPartialMerkleTree(); |
0a61b0df | 415 | |
4bedfa92 PW |
416 | // extract the matching txid's represented by this partial merkle tree. |
417 | // returns the merkle root, or 0 in case of failure | |
418 | uint256 ExtractMatches(std::vector<uint256> &vMatch); | |
419 | }; | |
0a61b0df | 420 | |
421 | ||
0a61b0df | 422 | |
a6dba0fd | 423 | /** Functions for disk access for blocks */ |
226f8219 | 424 | bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos); |
80313994 | 425 | bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos); |
7db120d5 | 426 | bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex); |
0a61b0df | 427 | |
428 | ||
5c363ed6 EL |
429 | /** Functions for validating blocks and updating the block tree */ |
430 | ||
431 | /** Undo the effects of this block (with given index) on the UTXO set represented by coins. | |
432 | * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean | |
433 | * will be true if no problems were found. Otherwise, the return value will be false in case | |
434 | * of problems. Note that in any case, coins may be modified. */ | |
435 | bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL); | |
436 | ||
f3ae51dc EL |
437 | // Apply the effects of this block (with given index) on the UTXO set represented by coins |
438 | bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false); | |
439 | ||
1959997a EL |
440 | // Add this block to the block index, and if necessary, switch the active block chain to this |
441 | bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos); | |
f3ae51dc | 442 | |
38991ffa | 443 | // Context-independent validity checks |
f4573470 | 444 | bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true); |
38991ffa EL |
445 | bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true); |
446 | ||
2a4d3464 EL |
447 | // Store block on disk |
448 | // if dbp is provided, the file is known to already reside on disk | |
942b33a1 PW |
449 | bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL); |
450 | bool AcceptBlockHeader(CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL); | |
2a4d3464 | 451 | |
5c363ed6 EL |
452 | |
453 | ||
5382bcf8 PW |
454 | class CBlockFileInfo |
455 | { | |
456 | public: | |
457 | unsigned int nBlocks; // number of blocks stored in file | |
458 | unsigned int nSize; // number of used bytes of block file | |
459 | unsigned int nUndoSize; // number of used bytes in the undo file | |
460 | unsigned int nHeightFirst; // lowest height of block in file | |
461 | unsigned int nHeightLast; // highest height of block in file | |
51ed9ec9 BD |
462 | uint64_t nTimeFirst; // earliest time of block in file |
463 | uint64_t nTimeLast; // latest time of block in file | |
5382bcf8 | 464 | |
3f6540ad | 465 | ADD_SERIALIZE_METHODS; |
3d796f89 | 466 | |
84881f8c | 467 | template <typename Stream, typename Operation> |
31e9a838 | 468 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
5382bcf8 PW |
469 | READWRITE(VARINT(nBlocks)); |
470 | READWRITE(VARINT(nSize)); | |
471 | READWRITE(VARINT(nUndoSize)); | |
472 | READWRITE(VARINT(nHeightFirst)); | |
473 | READWRITE(VARINT(nHeightLast)); | |
474 | READWRITE(VARINT(nTimeFirst)); | |
475 | READWRITE(VARINT(nTimeLast)); | |
3d796f89 | 476 | } |
5382bcf8 PW |
477 | |
478 | void SetNull() { | |
479 | nBlocks = 0; | |
480 | nSize = 0; | |
481 | nUndoSize = 0; | |
482 | nHeightFirst = 0; | |
483 | nHeightLast = 0; | |
484 | nTimeFirst = 0; | |
485 | nTimeLast = 0; | |
486 | } | |
487 | ||
488 | CBlockFileInfo() { | |
489 | SetNull(); | |
490 | } | |
491 | ||
651480c8 | 492 | std::string ToString() const; |
5382bcf8 PW |
493 | |
494 | // update statistics (does not update nSize) | |
51ed9ec9 | 495 | void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) { |
5382bcf8 PW |
496 | if (nBlocks==0 || nHeightFirst > nHeightIn) |
497 | nHeightFirst = nHeightIn; | |
498 | if (nBlocks==0 || nTimeFirst > nTimeIn) | |
499 | nTimeFirst = nTimeIn; | |
500 | nBlocks++; | |
367c29d6 | 501 | if (nHeightIn > nHeightLast) |
5382bcf8 PW |
502 | nHeightLast = nHeightIn; |
503 | if (nTimeIn > nTimeLast) | |
504 | nTimeLast = nTimeIn; | |
505 | } | |
506 | }; | |
507 | ||
ef3988ca PW |
508 | /** Capture information about block/transaction validation */ |
509 | class CValidationState { | |
510 | private: | |
511 | enum mode_state { | |
512 | MODE_VALID, // everything ok | |
513 | MODE_INVALID, // network rule violation (DoS value may be set) | |
514 | MODE_ERROR, // run-time error | |
515 | } mode; | |
516 | int nDoS; | |
358ce266 GA |
517 | std::string strRejectReason; |
518 | unsigned char chRejectCode; | |
b33b9a6f | 519 | bool corruptionPossible; |
ef3988ca | 520 | public: |
8bdd2877 | 521 | CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {} |
358ce266 GA |
522 | bool DoS(int level, bool ret = false, |
523 | unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", | |
524 | bool corruptionIn=false) { | |
525 | chRejectCode = chRejectCodeIn; | |
526 | strRejectReason = strRejectReasonIn; | |
527 | corruptionPossible = corruptionIn; | |
ef3988ca PW |
528 | if (mode == MODE_ERROR) |
529 | return ret; | |
530 | nDoS += level; | |
531 | mode = MODE_INVALID; | |
532 | return ret; | |
533 | } | |
358ce266 GA |
534 | bool Invalid(bool ret = false, |
535 | unsigned char _chRejectCode=0, std::string _strRejectReason="") { | |
536 | return DoS(0, ret, _chRejectCode, _strRejectReason); | |
ef3988ca | 537 | } |
c117d9e9 LD |
538 | bool Error(std::string strRejectReasonIn="") { |
539 | if (mode == MODE_VALID) | |
540 | strRejectReason = strRejectReasonIn; | |
ef3988ca | 541 | mode = MODE_ERROR; |
7851033d PW |
542 | return false; |
543 | } | |
544 | bool Abort(const std::string &msg) { | |
545 | AbortNode(msg); | |
c117d9e9 | 546 | return Error(msg); |
ef3988ca | 547 | } |
75f51f2a | 548 | bool IsValid() const { |
ef3988ca PW |
549 | return mode == MODE_VALID; |
550 | } | |
75f51f2a | 551 | bool IsInvalid() const { |
ef3988ca PW |
552 | return mode == MODE_INVALID; |
553 | } | |
75f51f2a | 554 | bool IsError() const { |
ef3988ca PW |
555 | return mode == MODE_ERROR; |
556 | } | |
75f51f2a | 557 | bool IsInvalid(int &nDoSOut) const { |
ef3988ca PW |
558 | if (IsInvalid()) { |
559 | nDoSOut = nDoS; | |
560 | return true; | |
561 | } | |
562 | return false; | |
563 | } | |
75f51f2a | 564 | bool CorruptionPossible() const { |
b33b9a6f MC |
565 | return corruptionPossible; |
566 | } | |
358ce266 GA |
567 | unsigned char GetRejectCode() const { return chRejectCode; } |
568 | std::string GetRejectReason() const { return strRejectReason; } | |
ef3988ca | 569 | }; |
0a61b0df | 570 | |
06a91d96 CL |
571 | /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ |
572 | class CVerifyDB { | |
573 | public: | |
06a91d96 CL |
574 | CVerifyDB(); |
575 | ~CVerifyDB(); | |
2e280311 | 576 | bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth); |
06a91d96 CL |
577 | }; |
578 | ||
6db83db3 | 579 | /** Find the last common block between the parameter chain and a locator. */ |
580 | CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator); | |
0a61b0df | 581 | |
4c6d41b8 PW |
582 | /** The currently-connected chain of blocks. */ |
583 | extern CChain chainActive; | |
0a61b0df | 584 | |
d979e6e3 | 585 | /** Global variable that points to the active CCoinsView (protected by cs_main) */ |
ae8bfd12 PW |
586 | extern CCoinsViewCache *pcoinsTip; |
587 | ||
d979e6e3 PW |
588 | /** Global variable that points to the active block tree (protected by cs_main) */ |
589 | extern CBlockTreeDB *pblocktree; | |
590 | ||
03cac0bb FV |
591 | struct CBlockTemplate |
592 | { | |
593 | CBlock block; | |
a372168e | 594 | std::vector<CAmount> vTxFees; |
03cac0bb FV |
595 | std::vector<int64_t> vTxSigOps; |
596 | }; | |
597 | ||
9fb106e7 MC |
598 | |
599 | ||
600 | ||
601 | ||
602 | ||
603 | /** Used to relay blocks as header + vector<merkle branch> | |
604 | * to filtered nodes. | |
605 | */ | |
606 | class CMerkleBlock | |
607 | { | |
608 | public: | |
21aaf255 | 609 | // Public only for unit testing |
9fb106e7 | 610 | CBlockHeader header; |
21aaf255 | 611 | CPartialMerkleTree txn; |
9fb106e7 | 612 | |
21aaf255 MC |
613 | public: |
614 | // Public only for unit testing and relay testing | |
615 | // (not relayed) | |
616 | std::vector<std::pair<unsigned int, uint256> > vMatchedTxn; | |
9fb106e7 MC |
617 | |
618 | // Create from a CBlock, filtering transactions according to filter | |
619 | // Note that this will call IsRelevantAndUpdate on the filter for each transaction, | |
620 | // thus the filter will likely be modified. | |
621 | CMerkleBlock(const CBlock& block, CBloomFilter& filter); | |
622 | ||
3f6540ad | 623 | ADD_SERIALIZE_METHODS; |
3d796f89 | 624 | |
84881f8c | 625 | template <typename Stream, typename Operation> |
31e9a838 | 626 | inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { |
9fb106e7 | 627 | READWRITE(header); |
21aaf255 | 628 | READWRITE(txn); |
3d796f89 | 629 | } |
9fb106e7 MC |
630 | }; |
631 | ||
00588c3f PW |
632 | |
633 | class CWalletInterface { | |
634 | protected: | |
d38da59b | 635 | virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) =0; |
00588c3f PW |
636 | virtual void EraseFromWallet(const uint256 &hash) =0; |
637 | virtual void SetBestChain(const CBlockLocator &locator) =0; | |
638 | virtual void UpdatedTransaction(const uint256 &hash) =0; | |
639 | virtual void Inventory(const uint256 &hash) =0; | |
640 | virtual void ResendWalletTransactions() =0; | |
641 | friend void ::RegisterWallet(CWalletInterface*); | |
642 | friend void ::UnregisterWallet(CWalletInterface*); | |
643 | friend void ::UnregisterAllWallets(); | |
644 | }; | |
645 | ||
093303a8 | 646 | #endif // BITCOIN_MAIN_H |