]>
Commit | Line | Data |
---|---|---|
0a61b0df | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
db0e8ccd | 2 | // Copyright (c) 2009-2013 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. |
223b6f1b WL |
5 | #ifndef BITCOIN_MAIN_H |
6 | #define BITCOIN_MAIN_H | |
7 | ||
35b8af92 CF |
8 | #if defined(HAVE_CONFIG_H) |
9 | #include "bitcoin-config.h" | |
10 | #endif | |
11 | ||
effc2770 | 12 | #include "core.h" |
223b6f1b | 13 | #include "bignum.h" |
7f3ccb59 | 14 | #include "sync.h" |
223b6f1b | 15 | #include "net.h" |
223b6f1b WL |
16 | #include "script.h" |
17 | ||
18 | #include <list> | |
0a61b0df | 19 | |
0a61b0df | 20 | class CBlock; |
21 | class CBlockIndex; | |
0a61b0df | 22 | class CKeyItem; |
64c7ee7e | 23 | class CReserveKey; |
0a61b0df | 24 | |
40c2614e JL |
25 | class CAddress; |
26 | class CInv; | |
40c2614e | 27 | class CNode; |
40c2614e | 28 | |
40c5e409 | 29 | struct CBlockIndexWorkComparator; |
857c61df | 30 | |
9d6633ac | 31 | /** The maximum allowed size for a serialized block, in bytes (network rule) */ |
0a61b0df | 32 | static const unsigned int MAX_BLOCK_SIZE = 1000000; |
9d6633ac | 33 | /** The maximum size for mined blocks */ |
3df62878 | 34 | static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; |
69e07747 | 35 | /** The maximum size for transactions we're willing to relay/mine */ |
41e1a0d7 | 36 | static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5; |
9d6633ac | 37 | /** The maximum allowed number of signature check operations in a block (network rule) */ |
7bd9c3a3 | 38 | static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; |
9d6633ac | 39 | /** The maximum number of orphan transactions kept in memory */ |
7bd9c3a3 | 40 | static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; |
9d6633ac | 41 | /** The maximum size of a blk?????.dat file (since 0.8) */ |
5382bcf8 | 42 | static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB |
9d6633ac | 43 | /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ |
bba89aa8 | 44 | static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB |
9d6633ac | 45 | /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ |
bba89aa8 | 46 | static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB |
9d6633ac | 47 | /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */ |
450cbb09 | 48 | static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF; |
9d6633ac | 49 | /** No amount larger than this (in satoshi) is valid */ |
bde280b9 WL |
50 | static const int64 MAX_MONEY = 21000000 * COIN; |
51 | inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } | |
9d6633ac | 52 | /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ |
0a61b0df | 53 | static const int COINBASE_MATURITY = 100; |
9d6633ac | 54 | /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ |
f621326c | 55 | static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC |
f9cae832 PW |
56 | /** Maximum number of script-checking threads allowed */ |
57 | static const int MAX_SCRIPTCHECK_THREADS = 16; | |
87cce04c MC |
58 | /** Default amount of block size reserved for high-priority transactions (in bytes) */ |
59 | static const int DEFAULT_BLOCK_PRIORITY_SIZE = 27000; | |
8bb5edc1 MC |
60 | #ifdef USE_UPNP |
61 | static const int fHaveUPnP = true; | |
62 | #else | |
63 | static const int fHaveUPnP = false; | |
64 | #endif | |
0a61b0df | 65 | |
66 | ||
7bf8b7c2 | 67 | extern CScript COINBASE_FLAGS; |
52a3d263 FV |
68 | |
69 | ||
0a61b0df | 70 | |
71 | ||
72 | ||
73 | ||
74 | extern CCriticalSection cs_main; | |
223b6f1b | 75 | extern std::map<uint256, CBlockIndex*> mapBlockIndex; |
857c61df | 76 | extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; |
1657c4bc | 77 | extern uint256 nBestInvalidWork; |
0a61b0df | 78 | extern unsigned int nTransactionsUpdated; |
340f0876 LD |
79 | extern uint64 nLastBlockTx; |
80 | extern uint64 nLastBlockSize; | |
2bc4fd60 | 81 | extern const std::string strMessageMagic; |
bde280b9 | 82 | extern int64 nTimeBestReceived; |
66b02c93 | 83 | extern bool fImporting; |
7fea4846 | 84 | extern bool fReindex; |
8a28bb6d | 85 | extern bool fBenchmark; |
f9cae832 | 86 | extern int nScriptCheckThreads; |
2d1fa42e | 87 | extern bool fTxIndex; |
1c83b0a3 | 88 | extern unsigned int nCoinCacheSize; |
13c84b3b | 89 | extern bool fHaveGUI; |
0a61b0df | 90 | |
91 | // Settings | |
bde280b9 | 92 | extern int64 nTransactionFee; |
0a61b0df | 93 | |
966ae00f PK |
94 | // Minimum disk space required - used in CheckDiskSpace() |
95 | static const uint64 nMinDiskSpace = 52428800; | |
0a61b0df | 96 | |
97 | ||
1512d5ce | 98 | class CReserveKey; |
450cbb09 | 99 | class CCoinsDB; |
d979e6e3 | 100 | class CBlockTreeDB; |
15ebd486 | 101 | struct CDiskBlockPos; |
450cbb09 PW |
102 | class CCoins; |
103 | class CTxUndo; | |
104 | class CCoinsView; | |
13c51f20 | 105 | class CCoinsViewCache; |
f9cae832 | 106 | class CScriptCheck; |
ef3988ca | 107 | class CValidationState; |
00588c3f | 108 | class CWalletInterface; |
0a61b0df | 109 | |
03cac0bb FV |
110 | struct CBlockTemplate; |
111 | ||
160b028b | 112 | /** Register a wallet to receive updates from core */ |
00588c3f | 113 | void RegisterWallet(CWalletInterface* pwalletIn); |
160b028b | 114 | /** Unregister a wallet from core */ |
00588c3f | 115 | void UnregisterWallet(CWalletInterface* pwalletIn); |
e6fe8e77 EL |
116 | /** Unregister all wallets from core */ |
117 | void UnregisterAllWallets(); | |
160b028b | 118 | /** Push an updated transaction to all registered wallets */ |
00588c3f | 119 | void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL); |
8926263d | 120 | |
501da250 EL |
121 | /** Register with a network node to receive its signals */ |
122 | void RegisterNodeSignals(CNodeSignals& nodeSignals); | |
123 | /** Unregister a network node */ | |
124 | void UnregisterNodeSignals(CNodeSignals& nodeSignals); | |
125 | ||
8926263d EL |
126 | void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd); |
127 | ||
160b028b | 128 | /** Process an incoming block */ |
ef3988ca | 129 | bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL); |
160b028b | 130 | /** Check whether enough disk space is available for an incoming block */ |
ec95a809 | 131 | bool CheckDiskSpace(uint64 nAdditionalBytes = 0); |
160b028b | 132 | /** Open a block file (blk?????.dat) */ |
5382bcf8 | 133 | FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
160b028b | 134 | /** Open an undo file (rev?????.dat) */ |
5382bcf8 | 135 | FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false); |
160b028b | 136 | /** Import blocks from an external file */ |
7fea4846 | 137 | bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL); |
38603761 PW |
138 | /** Initialize a new block tree database + block data on disk */ |
139 | bool InitBlockIndex(); | |
160b028b | 140 | /** Load the block tree and coins database from disk */ |
7fea4846 | 141 | bool LoadBlockIndex(); |
f7f3a96b PW |
142 | /** Unload database information */ |
143 | void UnloadBlockIndex(); | |
1f355b66 | 144 | /** Verify consistency of the block and coin databases */ |
168ba993 | 145 | bool VerifyDB(int nCheckLevel, int nCheckDepth); |
160b028b | 146 | /** Print the loaded block tree */ |
0a61b0df | 147 | void PrintBlockTree(); |
160b028b | 148 | /** Process protocol messages received from a given node */ |
0a61b0df | 149 | bool ProcessMessages(CNode* pfrom); |
160b028b | 150 | /** Send queued protocol messages to be sent to a give node */ |
0a61b0df | 151 | bool SendMessages(CNode* pto, bool fSendTrickle); |
f9cae832 | 152 | /** Run an instance of the script checking thread */ |
21eb5ada | 153 | void ThreadScriptCheck(); |
160b028b | 154 | /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ |
0a61b0df | 155 | bool CheckProofOfWork(uint256 hash, unsigned int nBits); |
160b028b | 156 | /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */ |
bde280b9 | 157 | unsigned int ComputeMinWork(unsigned int nBase, int64 nTime); |
160b028b | 158 | /** Get the number of active peers */ |
d33cc2b5 | 159 | int GetNumBlocksOfPeers(); |
f0bf5fb2 | 160 | /** Check whether we are doing an initial block download (synchronizing from disk or network) */ |
0a61b0df | 161 | bool IsInitialBlockDownload(); |
160b028b | 162 | /** Format a string that describes several potential problems detected by the core */ |
223b6f1b | 163 | std::string GetWarnings(std::string strFor); |
160b028b | 164 | /** Retrieve a transaction (from memory pool, or from disk, if possible) */ |
450cbb09 | 165 | bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false); |
160b028b | 166 | /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */ |
ef3988ca | 167 | bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew); |
160b028b | 168 | /** Find the best known block, and make it the tip of the block chain */ |
ef3988ca | 169 | bool ConnectBestBlock(CValidationState &state); |
d247a5d1 JG |
170 | int64 GetBlockValue(int nHeight, int64 nFees); |
171 | unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock); | |
aabdf9e8 EL |
172 | |
173 | void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev); | |
174 | ||
160b028b | 175 | /** Create a new block index entry for a given block hash */ |
2d8a4829 | 176 | CBlockIndex * InsertBlockIndex(uint256 hash); |
f1136200 PW |
177 | /** Verify a signature */ |
178 | bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); | |
7851033d PW |
179 | /** Abort with a message */ |
180 | bool AbortNode(const std::string &msg); | |
857c61df | 181 | |
0a61b0df | 182 | |
183 | ||
184 | ||
185 | ||
186 | ||
187 | ||
188 | ||
189 | ||
190 | ||
2d1fa42e | 191 | struct CDiskBlockPos |
630fd8dc | 192 | { |
5382bcf8 PW |
193 | int nFile; |
194 | unsigned int nPos; | |
630fd8dc | 195 | |
5382bcf8 PW |
196 | IMPLEMENT_SERIALIZE( |
197 | READWRITE(VARINT(nFile)); | |
198 | READWRITE(VARINT(nPos)); | |
199 | ) | |
630fd8dc | 200 | |
a8a4b967 PK |
201 | CDiskBlockPos() { |
202 | SetNull(); | |
203 | } | |
204 | ||
205 | CDiskBlockPos(int nFileIn, unsigned int nPosIn) { | |
206 | nFile = nFileIn; | |
207 | nPos = nPosIn; | |
208 | } | |
209 | ||
630fd8dc | 210 | friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { |
5382bcf8 | 211 | return (a.nFile == b.nFile && a.nPos == b.nPos); |
630fd8dc PW |
212 | } |
213 | ||
214 | friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { | |
215 | return !(a == b); | |
216 | } | |
217 | ||
5382bcf8 PW |
218 | void SetNull() { nFile = -1; nPos = 0; } |
219 | bool IsNull() const { return (nFile == -1); } | |
630fd8dc PW |
220 | }; |
221 | ||
2d1fa42e PW |
222 | struct CDiskTxPos : public CDiskBlockPos |
223 | { | |
224 | unsigned int nTxOffset; // after header | |
225 | ||
226 | IMPLEMENT_SERIALIZE( | |
227 | READWRITE(*(CDiskBlockPos*)this); | |
228 | READWRITE(VARINT(nTxOffset)); | |
229 | ) | |
230 | ||
231 | CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { | |
232 | } | |
233 | ||
234 | CDiskTxPos() { | |
235 | SetNull(); | |
236 | } | |
0a61b0df | 237 | |
2d1fa42e PW |
238 | void SetNull() { |
239 | CDiskBlockPos::SetNull(); | |
240 | nTxOffset = 0; | |
241 | } | |
242 | }; | |
0a61b0df | 243 | |
244 | ||
0a61b0df | 245 | |
dbbf1d4a LD |
246 | enum GetMinFee_mode |
247 | { | |
dbbf1d4a LD |
248 | GMF_RELAY, |
249 | GMF_SEND, | |
250 | }; | |
251 | ||
87cce04c | 252 | int64 GetMinFee(const CTransaction& tx, bool fAllowFree, enum GetMinFee_mode mode); |
788536f1 | 253 | |
05df3fc6 EL |
254 | // |
255 | // Check transaction inputs, and make sure any | |
256 | // pay-to-script-hash transactions are evaluating IsStandard scripts | |
257 | // | |
258 | // Why bother? To avoid denial-of-service attacks; an attacker | |
259 | // can submit a standard HASH... OP_EQUAL transaction, | |
260 | // which will get accepted into blocks. The redemption | |
261 | // script can be anything; an attacker could use a very | |
262 | // expensive-to-check-upon-redemption script like: | |
263 | // DUP CHECKSIG DROP ... repeated 100 times... OP_1 | |
264 | // | |
922e8e29 | 265 | |
8d7849b6 | 266 | /** Check for standard transaction types |
05df3fc6 | 267 | @param[in] mapInputs Map of previous transactions that have outputs we're spending |
8d7849b6 | 268 | @return True if all inputs (scriptSigs) use only standard transaction forms |
8d7849b6 | 269 | */ |
05df3fc6 | 270 | bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs); |
8d7849b6 | 271 | |
05df3fc6 EL |
272 | /** Count ECDSA signature operations the old-fashioned (pre-0.6) way |
273 | @return number of sigops this transaction's outputs will produce when spent | |
274 | @see CTransaction::FetchInputs | |
275 | */ | |
276 | unsigned int GetLegacySigOpCount(const CTransaction& tx); | |
a206a239 | 277 | |
05df3fc6 | 278 | /** Count ECDSA signature operations in pay-to-script-hash inputs. |
0a61b0df | 279 | |
05df3fc6 EL |
280 | @param[in] mapInputs Map of previous transactions that have outputs we're spending |
281 | @return maximum number of sigops required to validate this transaction's inputs | |
282 | @see CTransaction::FetchInputs | |
283 | */ | |
284 | unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& mapInputs); | |
0a61b0df | 285 | |
0a61b0df | 286 | |
05df3fc6 EL |
287 | inline bool AllowFree(double dPriority) |
288 | { | |
289 | // Large (in bytes) low-priority (new, small-coin) transactions | |
290 | // need a fee. | |
291 | return dPriority > COIN * 144 / 250; | |
292 | } | |
0a61b0df | 293 | |
05df3fc6 EL |
294 | // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) |
295 | // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it | |
296 | // instead of being performed inline. | |
297 | bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true, | |
298 | unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, | |
299 | std::vector<CScriptCheck> *pvChecks = NULL); | |
0a61b0df | 300 | |
05df3fc6 | 301 | // Apply the effects of this transaction on the UTXO set represented by view |
18946846 | 302 | void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash); |
8d7849b6 | 303 | |
05df3fc6 EL |
304 | // Context-independent validity checks |
305 | bool CheckTransaction(const CTransaction& tx, CValidationState& state); | |
450cbb09 | 306 | |
05df3fc6 EL |
307 | /** Check for standard transaction types |
308 | @return True if all outputs (scriptPubKeys) use only standard transaction forms | |
309 | */ | |
980bfe6e | 310 | bool IsStandardTx(const CTransaction& tx, std::string& reason); |
450cbb09 | 311 | |
05df3fc6 | 312 | bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64 nBlockTime = 0); |
450cbb09 | 313 | |
05df3fc6 EL |
314 | /** Amount of bitcoins spent by the transaction. |
315 | @return sum of all outputs (note: does not include fees) | |
316 | */ | |
317 | int64 GetValueOut(const CTransaction& tx); | |
8d7849b6 | 318 | |
8adf48dc PW |
319 | /** Undo information for a CBlock */ |
320 | class CBlockUndo | |
321 | { | |
322 | public: | |
450cbb09 | 323 | std::vector<CTxUndo> vtxundo; // for all but the coinbase |
8adf48dc PW |
324 | |
325 | IMPLEMENT_SERIALIZE( | |
326 | READWRITE(vtxundo); | |
327 | ) | |
5382bcf8 | 328 | |
8539361e | 329 | bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock) |
5382bcf8 PW |
330 | { |
331 | // Open history file to append | |
332 | CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); | |
333 | if (!fileout) | |
334 | return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed"); | |
335 | ||
336 | // Write index header | |
337 | unsigned int nSize = fileout.GetSerializeSize(*this); | |
0e4b3175 | 338 | fileout << FLATDATA(Params().MessageStart()) << nSize; |
5382bcf8 PW |
339 | |
340 | // Write undo data | |
341 | long fileOutPos = ftell(fileout); | |
342 | if (fileOutPos < 0) | |
13e5cce4 | 343 | return error("CBlockUndo::WriteToDisk() : ftell failed"); |
5382bcf8 PW |
344 | pos.nPos = (unsigned int)fileOutPos; |
345 | fileout << *this; | |
346 | ||
8539361e PW |
347 | // calculate & write checksum |
348 | CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); | |
349 | hasher << hashBlock; | |
350 | hasher << *this; | |
351 | fileout << hasher.GetHash(); | |
352 | ||
5382bcf8 PW |
353 | // Flush stdio buffers and commit to disk before returning |
354 | fflush(fileout); | |
450cbb09 | 355 | if (!IsInitialBlockDownload()) |
5382bcf8 PW |
356 | FileCommit(fileout); |
357 | ||
358 | return true; | |
359 | } | |
8539361e PW |
360 | |
361 | bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock) | |
362 | { | |
363 | // Open history file to read | |
364 | CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); | |
365 | if (!filein) | |
366 | return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed"); | |
367 | ||
368 | // Read block | |
369 | uint256 hashChecksum; | |
370 | try { | |
371 | filein >> *this; | |
d0809a19 | 372 | filein >> hashChecksum; |
8539361e PW |
373 | } |
374 | catch (std::exception &e) { | |
375 | return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); | |
376 | } | |
377 | ||
8539361e PW |
378 | // Verify checksum |
379 | CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); | |
380 | hasher << hashBlock; | |
381 | hasher << *this; | |
382 | if (hashChecksum != hasher.GetHash()) | |
383 | return error("CBlockUndo::ReadFromDisk() : checksum mismatch"); | |
384 | ||
385 | return true; | |
386 | } | |
8adf48dc PW |
387 | }; |
388 | ||
0a61b0df | 389 | |
2800ce73 PW |
390 | /** Closure representing one script verification |
391 | * Note that this stores references to the spending transaction */ | |
392 | class CScriptCheck | |
393 | { | |
394 | private: | |
395 | CScript scriptPubKey; | |
396 | const CTransaction *ptxTo; | |
397 | unsigned int nIn; | |
398 | unsigned int nFlags; | |
399 | int nHashType; | |
0a61b0df | 400 | |
2800ce73 PW |
401 | public: |
402 | CScriptCheck() {} | |
403 | CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) : | |
404 | scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), | |
405 | ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { } | |
406 | ||
407 | bool operator()() const; | |
408 | ||
409 | void swap(CScriptCheck &check) { | |
410 | scriptPubKey.swap(check.scriptPubKey); | |
411 | std::swap(ptxTo, check.ptxTo); | |
412 | std::swap(nIn, check.nIn); | |
413 | std::swap(nFlags, check.nFlags); | |
414 | std::swap(nHashType, check.nHashType); | |
415 | } | |
416 | }; | |
0a61b0df | 417 | |
6b8de05d | 418 | /** A transaction with a merkle branch linking it to the block chain. */ |
0a61b0df | 419 | class CMerkleTx : public CTransaction |
420 | { | |
421 | public: | |
422 | uint256 hashBlock; | |
223b6f1b | 423 | std::vector<uint256> vMerkleBranch; |
0a61b0df | 424 | int nIndex; |
425 | ||
426 | // memory only | |
cdcc319c | 427 | mutable bool fMerkleVerified; |
0a61b0df | 428 | |
429 | ||
430 | CMerkleTx() | |
431 | { | |
432 | Init(); | |
433 | } | |
434 | ||
435 | CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) | |
436 | { | |
437 | Init(); | |
438 | } | |
439 | ||
440 | void Init() | |
441 | { | |
442 | hashBlock = 0; | |
443 | nIndex = -1; | |
444 | fMerkleVerified = false; | |
0a61b0df | 445 | } |
446 | ||
335e878b | 447 | |
0a61b0df | 448 | IMPLEMENT_SERIALIZE |
449 | ( | |
450 | nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); | |
451 | nVersion = this->nVersion; | |
452 | READWRITE(hashBlock); | |
453 | READWRITE(vMerkleBranch); | |
454 | READWRITE(nIndex); | |
455 | ) | |
456 | ||
0a61b0df | 457 | |
458 | int SetMerkleBranch(const CBlock* pblock=NULL); | |
30ab2c9c PW |
459 | int GetDepthInMainChain(CBlockIndex* &pindexRet) const; |
460 | int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } | |
0a61b0df | 461 | bool IsInMainChain() const { return GetDepthInMainChain() > 0; } |
462 | int GetBlocksToMaturity() const; | |
b1f15b21 | 463 | bool AcceptToMemoryPool(bool fLimitFree=true); |
0a61b0df | 464 | }; |
465 | ||
466 | ||
467 | ||
468 | ||
0a61b0df | 469 | |
4bedfa92 PW |
470 | /** Data structure that represents a partial merkle tree. |
471 | * | |
472 | * It respresents a subset of the txid's of a known block, in a way that | |
473 | * allows recovery of the list of txid's and the merkle root, in an | |
474 | * authenticated way. | |
475 | * | |
476 | * The encoding works as follows: we traverse the tree in depth-first order, | |
477 | * storing a bit for each traversed node, signifying whether the node is the | |
478 | * parent of at least one matched leaf txid (or a matched txid itself). In | |
479 | * case we are at the leaf level, or this bit is 0, its merkle node hash is | |
480 | * stored, and its children are not explorer further. Otherwise, no hash is | |
481 | * stored, but we recurse into both (or the only) child branch. During | |
482 | * decoding, the same depth-first traversal is performed, consuming bits and | |
483 | * hashes as they written during encoding. | |
484 | * | |
485 | * The serialization is fixed and provides a hard guarantee about the | |
486 | * encoded size: | |
487 | * | |
488 | * SIZE <= 10 + ceil(32.25*N) | |
489 | * | |
490 | * Where N represents the number of leaf nodes of the partial tree. N itself | |
491 | * is bounded by: | |
492 | * | |
493 | * N <= total_transactions | |
494 | * N <= 1 + matched_transactions*tree_height | |
495 | * | |
496 | * The serialization format: | |
497 | * - uint32 total_transactions (4 bytes) | |
498 | * - varint number of hashes (1-3 bytes) | |
499 | * - uint256[] hashes in depth-first order (<= 32*N bytes) | |
500 | * - varint number of bytes of flag bits (1-3 bytes) | |
501 | * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits) | |
502 | * The size constraints follow from this. | |
503 | */ | |
504 | class CPartialMerkleTree | |
505 | { | |
506 | protected: | |
507 | // the total number of transactions in the block | |
508 | unsigned int nTransactions; | |
509 | ||
510 | // node-is-parent-of-matched-txid bits | |
511 | std::vector<bool> vBits; | |
512 | ||
513 | // txids and internal hashes | |
514 | std::vector<uint256> vHash; | |
0a61b0df | 515 | |
4bedfa92 PW |
516 | // flag set when encountering invalid data |
517 | bool fBad; | |
0a61b0df | 518 | |
4bedfa92 PW |
519 | // helper function to efficiently calculate the number of nodes at given height in the merkle tree |
520 | unsigned int CalcTreeWidth(int height) { | |
521 | return (nTransactions+(1 << height)-1) >> height; | |
522 | } | |
523 | ||
524 | // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself) | |
525 | uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid); | |
526 | ||
527 | // recursive function that traverses tree nodes, storing the data as bits and hashes | |
528 | void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); | |
529 | ||
530 | // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. | |
531 | // it returns the hash of the respective node. | |
532 | uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch); | |
533 | ||
534 | public: | |
0a61b0df | 535 | |
4bedfa92 PW |
536 | // serialization implementation |
537 | IMPLEMENT_SERIALIZE( | |
538 | READWRITE(nTransactions); | |
539 | READWRITE(vHash); | |
540 | std::vector<unsigned char> vBytes; | |
541 | if (fRead) { | |
542 | READWRITE(vBytes); | |
543 | CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this)); | |
544 | us.vBits.resize(vBytes.size() * 8); | |
545 | for (unsigned int p = 0; p < us.vBits.size(); p++) | |
546 | us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0; | |
547 | us.fBad = false; | |
548 | } else { | |
549 | vBytes.resize((vBits.size()+7)/8); | |
550 | for (unsigned int p = 0; p < vBits.size(); p++) | |
551 | vBytes[p / 8] |= vBits[p] << (p % 8); | |
552 | READWRITE(vBytes); | |
553 | } | |
554 | ) | |
555 | ||
556 | // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them | |
557 | CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); | |
0a61b0df | 558 | |
4bedfa92 | 559 | CPartialMerkleTree(); |
0a61b0df | 560 | |
4bedfa92 PW |
561 | // extract the matching txid's represented by this partial merkle tree. |
562 | // returns the merkle root, or 0 in case of failure | |
563 | uint256 ExtractMatches(std::vector<uint256> &vMatch); | |
564 | }; | |
0a61b0df | 565 | |
566 | ||
0a61b0df | 567 | |
a6dba0fd | 568 | /** Functions for disk access for blocks */ |
226f8219 | 569 | bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos); |
80313994 | 570 | bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos); |
7db120d5 | 571 | bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex); |
0a61b0df | 572 | |
573 | ||
5c363ed6 EL |
574 | /** Functions for validating blocks and updating the block tree */ |
575 | ||
576 | /** Undo the effects of this block (with given index) on the UTXO set represented by coins. | |
577 | * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean | |
578 | * will be true if no problems were found. Otherwise, the return value will be false in case | |
579 | * of problems. Note that in any case, coins may be modified. */ | |
580 | bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL); | |
581 | ||
f3ae51dc EL |
582 | // Apply the effects of this block (with given index) on the UTXO set represented by coins |
583 | bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false); | |
584 | ||
1959997a EL |
585 | // Add this block to the block index, and if necessary, switch the active block chain to this |
586 | bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos); | |
f3ae51dc | 587 | |
38991ffa EL |
588 | // Context-independent validity checks |
589 | bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true); | |
590 | ||
2a4d3464 EL |
591 | // Store block on disk |
592 | // if dbp is provided, the file is known to already reside on disk | |
593 | bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp = NULL); | |
594 | ||
5c363ed6 EL |
595 | |
596 | ||
5382bcf8 PW |
597 | class CBlockFileInfo |
598 | { | |
599 | public: | |
600 | unsigned int nBlocks; // number of blocks stored in file | |
601 | unsigned int nSize; // number of used bytes of block file | |
602 | unsigned int nUndoSize; // number of used bytes in the undo file | |
603 | unsigned int nHeightFirst; // lowest height of block in file | |
604 | unsigned int nHeightLast; // highest height of block in file | |
605 | uint64 nTimeFirst; // earliest time of block in file | |
606 | uint64 nTimeLast; // latest time of block in file | |
607 | ||
608 | IMPLEMENT_SERIALIZE( | |
609 | READWRITE(VARINT(nBlocks)); | |
610 | READWRITE(VARINT(nSize)); | |
611 | READWRITE(VARINT(nUndoSize)); | |
612 | READWRITE(VARINT(nHeightFirst)); | |
613 | READWRITE(VARINT(nHeightLast)); | |
614 | READWRITE(VARINT(nTimeFirst)); | |
615 | READWRITE(VARINT(nTimeLast)); | |
616 | ) | |
617 | ||
618 | void SetNull() { | |
619 | nBlocks = 0; | |
620 | nSize = 0; | |
621 | nUndoSize = 0; | |
622 | nHeightFirst = 0; | |
623 | nHeightLast = 0; | |
624 | nTimeFirst = 0; | |
625 | nTimeLast = 0; | |
626 | } | |
627 | ||
628 | CBlockFileInfo() { | |
629 | SetNull(); | |
630 | } | |
631 | ||
632 | std::string ToString() const { | |
69e07747 | 633 | return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str()); |
5382bcf8 PW |
634 | } |
635 | ||
636 | // update statistics (does not update nSize) | |
637 | void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) { | |
638 | if (nBlocks==0 || nHeightFirst > nHeightIn) | |
639 | nHeightFirst = nHeightIn; | |
640 | if (nBlocks==0 || nTimeFirst > nTimeIn) | |
641 | nTimeFirst = nTimeIn; | |
642 | nBlocks++; | |
367c29d6 | 643 | if (nHeightIn > nHeightLast) |
5382bcf8 PW |
644 | nHeightLast = nHeightIn; |
645 | if (nTimeIn > nTimeLast) | |
646 | nTimeLast = nTimeIn; | |
647 | } | |
648 | }; | |
649 | ||
650 | extern CCriticalSection cs_LastBlockFile; | |
651 | extern CBlockFileInfo infoLastBlockFile; | |
652 | extern int nLastBlockFile; | |
0a61b0df | 653 | |
857c61df PW |
654 | enum BlockStatus { |
655 | BLOCK_VALID_UNKNOWN = 0, | |
656 | BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future | |
657 | BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint | |
658 | BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root | |
659 | BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30 | |
660 | BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok | |
661 | BLOCK_VALID_MASK = 7, | |
662 | ||
663 | BLOCK_HAVE_DATA = 8, // full block available in blk*.dat | |
664 | BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat | |
665 | BLOCK_HAVE_MASK = 24, | |
666 | ||
667 | BLOCK_FAILED_VALID = 32, // stage after last reached validness failed | |
668 | BLOCK_FAILED_CHILD = 64, // descends from failed block | |
669 | BLOCK_FAILED_MASK = 96 | |
670 | }; | |
671 | ||
6b8de05d PW |
672 | /** The block chain is a tree shaped structure starting with the |
673 | * genesis block at the root, with each block potentially having multiple | |
0fe8010a PW |
674 | * candidates to be the next block. A blockindex may have multiple pprev pointing |
675 | * to it, but at most one of them can be part of the currently active branch. | |
6b8de05d | 676 | */ |
0a61b0df | 677 | class CBlockIndex |
678 | { | |
679 | public: | |
857c61df | 680 | // pointer to the hash of the block, if any. memory is owned by this CBlockIndex |
0a61b0df | 681 | const uint256* phashBlock; |
857c61df PW |
682 | |
683 | // pointer to the index of the predecessor of this block | |
0a61b0df | 684 | CBlockIndex* pprev; |
857c61df | 685 | |
857c61df | 686 | // height of the entry in the chain. The genesis block has height 0 |
0a61b0df | 687 | int nHeight; |
857c61df PW |
688 | |
689 | // Which # file this block is stored in (blk?????.dat) | |
690 | int nFile; | |
691 | ||
692 | // Byte offset within blk?????.dat where this block's data is stored | |
693 | unsigned int nDataPos; | |
694 | ||
695 | // Byte offset within rev?????.dat where this block's undo data is stored | |
5382bcf8 | 696 | unsigned int nUndoPos; |
857c61df PW |
697 | |
698 | // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block | |
1657c4bc | 699 | uint256 nChainWork; |
0a61b0df | 700 | |
857c61df PW |
701 | // Number of transactions in this block. |
702 | // Note: in a potential headers-first mode, this number cannot be relied upon | |
703 | unsigned int nTx; | |
704 | ||
705 | // (memory only) Number of transactions in the chain up to and including this block | |
706 | unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030 | |
707 | ||
708 | // Verification status of this block. See enum BlockStatus | |
709 | unsigned int nStatus; | |
710 | ||
0a61b0df | 711 | // block header |
712 | int nVersion; | |
713 | uint256 hashMerkleRoot; | |
714 | unsigned int nTime; | |
715 | unsigned int nBits; | |
716 | unsigned int nNonce; | |
717 | ||
718 | ||
719 | CBlockIndex() | |
720 | { | |
721 | phashBlock = NULL; | |
722 | pprev = NULL; | |
0a61b0df | 723 | nHeight = 0; |
857c61df PW |
724 | nFile = 0; |
725 | nDataPos = 0; | |
450cbb09 | 726 | nUndoPos = 0; |
1657c4bc | 727 | nChainWork = 0; |
857c61df PW |
728 | nTx = 0; |
729 | nChainTx = 0; | |
730 | nStatus = 0; | |
0a61b0df | 731 | |
732 | nVersion = 0; | |
733 | hashMerkleRoot = 0; | |
734 | nTime = 0; | |
735 | nBits = 0; | |
736 | nNonce = 0; | |
737 | } | |
738 | ||
e754cf41 | 739 | CBlockIndex(CBlockHeader& block) |
0a61b0df | 740 | { |
741 | phashBlock = NULL; | |
742 | pprev = NULL; | |
0a61b0df | 743 | nHeight = 0; |
857c61df PW |
744 | nFile = 0; |
745 | nDataPos = 0; | |
5382bcf8 | 746 | nUndoPos = 0; |
1657c4bc | 747 | nChainWork = 0; |
857c61df PW |
748 | nTx = 0; |
749 | nChainTx = 0; | |
750 | nStatus = 0; | |
0a61b0df | 751 | |
752 | nVersion = block.nVersion; | |
753 | hashMerkleRoot = block.hashMerkleRoot; | |
754 | nTime = block.nTime; | |
755 | nBits = block.nBits; | |
756 | nNonce = block.nNonce; | |
757 | } | |
758 | ||
630fd8dc | 759 | CDiskBlockPos GetBlockPos() const { |
857c61df PW |
760 | CDiskBlockPos ret; |
761 | if (nStatus & BLOCK_HAVE_DATA) { | |
762 | ret.nFile = nFile; | |
763 | ret.nPos = nDataPos; | |
a8a4b967 | 764 | } |
857c61df | 765 | return ret; |
5382bcf8 PW |
766 | } |
767 | ||
768 | CDiskBlockPos GetUndoPos() const { | |
857c61df PW |
769 | CDiskBlockPos ret; |
770 | if (nStatus & BLOCK_HAVE_UNDO) { | |
771 | ret.nFile = nFile; | |
772 | ret.nPos = nUndoPos; | |
a8a4b967 | 773 | } |
5382bcf8 | 774 | return ret; |
630fd8dc PW |
775 | } |
776 | ||
e754cf41 | 777 | CBlockHeader GetBlockHeader() const |
f03304a9 | 778 | { |
e754cf41 | 779 | CBlockHeader block; |
f03304a9 | 780 | block.nVersion = nVersion; |
781 | if (pprev) | |
782 | block.hashPrevBlock = pprev->GetBlockHash(); | |
783 | block.hashMerkleRoot = hashMerkleRoot; | |
784 | block.nTime = nTime; | |
785 | block.nBits = nBits; | |
786 | block.nNonce = nNonce; | |
787 | return block; | |
788 | } | |
789 | ||
0a61b0df | 790 | uint256 GetBlockHash() const |
791 | { | |
792 | return *phashBlock; | |
793 | } | |
794 | ||
bde280b9 | 795 | int64 GetBlockTime() const |
0a61b0df | 796 | { |
bde280b9 | 797 | return (int64)nTime; |
0a61b0df | 798 | } |
799 | ||
800 | CBigNum GetBlockWork() const | |
801 | { | |
9b8eb4d6 | 802 | CBigNum bnTarget; |
803 | bnTarget.SetCompact(nBits); | |
804 | if (bnTarget <= 0) | |
0a61b0df | 805 | return 0; |
9b8eb4d6 | 806 | return (CBigNum(1)<<256) / (bnTarget+1); |
0a61b0df | 807 | } |
808 | ||
0a61b0df | 809 | bool CheckIndex() const |
810 | { | |
811 | return CheckProofOfWork(GetBlockHash(), nBits); | |
812 | } | |
813 | ||
0a61b0df | 814 | enum { nMedianTimeSpan=11 }; |
815 | ||
bde280b9 | 816 | int64 GetMedianTimePast() const |
0a61b0df | 817 | { |
bde280b9 WL |
818 | int64 pmedian[nMedianTimeSpan]; |
819 | int64* pbegin = &pmedian[nMedianTimeSpan]; | |
820 | int64* pend = &pmedian[nMedianTimeSpan]; | |
0a61b0df | 821 | |
822 | const CBlockIndex* pindex = this; | |
823 | for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) | |
824 | *(--pbegin) = pindex->GetBlockTime(); | |
825 | ||
223b6f1b | 826 | std::sort(pbegin, pend); |
0a61b0df | 827 | return pbegin[(pend - pbegin)/2]; |
828 | } | |
829 | ||
4c6d41b8 | 830 | int64 GetMedianTime() const; |
0a61b0df | 831 | |
de237cbf GA |
832 | /** |
833 | * Returns true if there are nRequired or more blocks of minVersion or above | |
834 | * in the last nToCheck blocks, starting at pstart and going backwards. | |
835 | */ | |
836 | static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, | |
837 | unsigned int nRequired, unsigned int nToCheck); | |
0a61b0df | 838 | |
223b6f1b | 839 | std::string ToString() const |
0a61b0df | 840 | { |
4c6d41b8 PW |
841 | return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", |
842 | pprev, nHeight, | |
1c06aa98 PW |
843 | hashMerkleRoot.ToString().c_str(), |
844 | GetBlockHash().ToString().c_str()); | |
0a61b0df | 845 | } |
846 | ||
847 | void print() const | |
848 | { | |
881a85a2 | 849 | LogPrintf("%s\n", ToString().c_str()); |
0a61b0df | 850 | } |
851 | }; | |
852 | ||
857c61df PW |
853 | struct CBlockIndexWorkComparator |
854 | { | |
855 | bool operator()(CBlockIndex *pa, CBlockIndex *pb) { | |
1657c4bc PW |
856 | if (pa->nChainWork > pb->nChainWork) return false; |
857 | if (pa->nChainWork < pb->nChainWork) return true; | |
857c61df PW |
858 | |
859 | if (pa->GetBlockHash() < pb->GetBlockHash()) return false; | |
860 | if (pa->GetBlockHash() > pb->GetBlockHash()) return true; | |
861 | ||
862 | return false; // identical blocks | |
863 | } | |
864 | }; | |
865 | ||
0a61b0df | 866 | |
867 | ||
6b8de05d | 868 | /** Used to marshal pointers into hashes for db storage. */ |
0a61b0df | 869 | class CDiskBlockIndex : public CBlockIndex |
870 | { | |
871 | public: | |
872 | uint256 hashPrev; | |
0a61b0df | 873 | |
450cbb09 | 874 | CDiskBlockIndex() { |
0a61b0df | 875 | hashPrev = 0; |
0a61b0df | 876 | } |
877 | ||
450cbb09 | 878 | explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { |
0a61b0df | 879 | hashPrev = (pprev ? pprev->GetBlockHash() : 0); |
0a61b0df | 880 | } |
881 | ||
882 | IMPLEMENT_SERIALIZE | |
883 | ( | |
884 | if (!(nType & SER_GETHASH)) | |
857c61df PW |
885 | READWRITE(VARINT(nVersion)); |
886 | ||
887 | READWRITE(VARINT(nHeight)); | |
888 | READWRITE(VARINT(nStatus)); | |
889 | READWRITE(VARINT(nTx)); | |
890 | if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) | |
891 | READWRITE(VARINT(nFile)); | |
892 | if (nStatus & BLOCK_HAVE_DATA) | |
893 | READWRITE(VARINT(nDataPos)); | |
894 | if (nStatus & BLOCK_HAVE_UNDO) | |
895 | READWRITE(VARINT(nUndoPos)); | |
0a61b0df | 896 | |
897 | // block header | |
898 | READWRITE(this->nVersion); | |
899 | READWRITE(hashPrev); | |
900 | READWRITE(hashMerkleRoot); | |
901 | READWRITE(nTime); | |
902 | READWRITE(nBits); | |
903 | READWRITE(nNonce); | |
904 | ) | |
905 | ||
906 | uint256 GetBlockHash() const | |
907 | { | |
e754cf41 | 908 | CBlockHeader block; |
0a61b0df | 909 | block.nVersion = nVersion; |
910 | block.hashPrevBlock = hashPrev; | |
911 | block.hashMerkleRoot = hashMerkleRoot; | |
912 | block.nTime = nTime; | |
913 | block.nBits = nBits; | |
914 | block.nNonce = nNonce; | |
915 | return block.GetHash(); | |
916 | } | |
917 | ||
918 | ||
223b6f1b | 919 | std::string ToString() const |
0a61b0df | 920 | { |
223b6f1b | 921 | std::string str = "CDiskBlockIndex("; |
0a61b0df | 922 | str += CBlockIndex::ToString(); |
450cbb09 | 923 | str += strprintf("\n hashBlock=%s, hashPrev=%s)", |
0a61b0df | 924 | GetBlockHash().ToString().c_str(), |
1c06aa98 | 925 | hashPrev.ToString().c_str()); |
0a61b0df | 926 | return str; |
927 | } | |
928 | ||
929 | void print() const | |
930 | { | |
881a85a2 | 931 | LogPrintf("%s\n", ToString().c_str()); |
0a61b0df | 932 | } |
933 | }; | |
934 | ||
ef3988ca PW |
935 | /** Capture information about block/transaction validation */ |
936 | class CValidationState { | |
937 | private: | |
938 | enum mode_state { | |
939 | MODE_VALID, // everything ok | |
940 | MODE_INVALID, // network rule violation (DoS value may be set) | |
941 | MODE_ERROR, // run-time error | |
942 | } mode; | |
943 | int nDoS; | |
944 | public: | |
945 | CValidationState() : mode(MODE_VALID), nDoS(0) {} | |
946 | bool DoS(int level, bool ret = false) { | |
947 | if (mode == MODE_ERROR) | |
948 | return ret; | |
949 | nDoS += level; | |
950 | mode = MODE_INVALID; | |
951 | return ret; | |
952 | } | |
953 | bool Invalid(bool ret = false) { | |
954 | return DoS(0, ret); | |
955 | } | |
7851033d | 956 | bool Error() { |
ef3988ca | 957 | mode = MODE_ERROR; |
7851033d PW |
958 | return false; |
959 | } | |
960 | bool Abort(const std::string &msg) { | |
961 | AbortNode(msg); | |
962 | return Error(); | |
ef3988ca PW |
963 | } |
964 | bool IsValid() { | |
965 | return mode == MODE_VALID; | |
966 | } | |
967 | bool IsInvalid() { | |
968 | return mode == MODE_INVALID; | |
969 | } | |
970 | bool IsError() { | |
971 | return mode == MODE_ERROR; | |
972 | } | |
973 | bool IsInvalid(int &nDoSOut) { | |
974 | if (IsInvalid()) { | |
975 | nDoSOut = nDoS; | |
976 | return true; | |
977 | } | |
978 | return false; | |
979 | } | |
980 | }; | |
0a61b0df | 981 | |
4c6d41b8 PW |
982 | /** An in-memory indexed chain of blocks. */ |
983 | class CChain { | |
984 | private: | |
985 | std::vector<CBlockIndex*> vChain; | |
0a61b0df | 986 | |
4c6d41b8 PW |
987 | public: |
988 | /** Returns the index entry for the genesis block of this chain, or NULL if none. */ | |
989 | CBlockIndex *Genesis() const { | |
990 | return vChain.size() > 0 ? vChain[0] : NULL; | |
991 | } | |
0a61b0df | 992 | |
4c6d41b8 PW |
993 | /** Returns the index entry for the tip of this chain, or NULL if none. */ |
994 | CBlockIndex *Tip() const { | |
995 | return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL; | |
996 | } | |
997 | ||
998 | /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */ | |
999 | CBlockIndex *operator[](int nHeight) const { | |
1000 | if (nHeight < 0 || nHeight >= (int)vChain.size()) | |
1001 | return NULL; | |
1002 | return vChain[nHeight]; | |
1003 | } | |
1004 | ||
1005 | /** Compare two chains efficiently. */ | |
1006 | friend bool operator==(const CChain &a, const CChain &b) { | |
1007 | return a.vChain.size() == b.vChain.size() && | |
1008 | a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1]; | |
1009 | } | |
1010 | ||
1011 | /** Efficiently check whether a block is present in this chain. */ | |
1012 | bool Contains(const CBlockIndex *pindex) const { | |
1013 | return (*this)[pindex->nHeight] == pindex; | |
1014 | } | |
1015 | ||
1016 | /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */ | |
1017 | CBlockIndex *Next(const CBlockIndex *pindex) const { | |
1018 | if (Contains(pindex)) | |
1019 | return (*this)[pindex->nHeight + 1]; | |
1020 | else | |
1021 | return NULL; | |
1022 | } | |
1023 | ||
1024 | /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ | |
1025 | int Height() const { | |
1026 | return vChain.size() - 1; | |
1027 | } | |
1028 | ||
1029 | /** Set/initialize a chain with a given tip. Returns the forking point. */ | |
1030 | CBlockIndex *SetTip(CBlockIndex *pindex); | |
e4daecda PW |
1031 | |
1032 | /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ | |
1033 | CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const; | |
1034 | ||
1035 | /** Find the last common block between this chain and a locator. */ | |
1036 | CBlockIndex *FindFork(const CBlockLocator &locator) const; | |
4c6d41b8 | 1037 | }; |
0a61b0df | 1038 | |
4c6d41b8 PW |
1039 | /** The currently-connected chain of blocks. */ |
1040 | extern CChain chainActive; | |
0a61b0df | 1041 | |
1042 | ||
1043 | ||
0a61b0df | 1044 | |
1045 | ||
1046 | ||
1047 | ||
e4ff4e68 | 1048 | |
1049 | ||
235507ae JG |
1050 | class CTxMemPool |
1051 | { | |
1052 | public: | |
2461aba1 | 1053 | static bool fChecks; |
235507ae JG |
1054 | mutable CCriticalSection cs; |
1055 | std::map<uint256, CTransaction> mapTx; | |
1056 | std::map<COutPoint, CInPoint> mapNextTx; | |
8e45ed66 | 1057 | |
9d14e689 | 1058 | bool accept(CValidationState &state, const CTransaction &tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false); |
159bc481 | 1059 | bool addUnchecked(const uint256& hash, const CTransaction &tx); |
231b3999 PW |
1060 | bool remove(const CTransaction &tx, bool fRecursive = false); |
1061 | bool removeConflicts(const CTransaction &tx); | |
639b61d7 | 1062 | void clear(); |
25d5c195 | 1063 | void queryHashes(std::vector<uint256>& vtxid); |
450cbb09 | 1064 | void pruneSpent(const uint256& hash, CCoins &coins); |
2461aba1 | 1065 | void check(CCoinsViewCache *pcoins) const; |
8e45ed66 JG |
1066 | |
1067 | unsigned long size() | |
1068 | { | |
1069 | LOCK(cs); | |
1070 | return mapTx.size(); | |
1071 | } | |
ca4c4c53 JG |
1072 | |
1073 | bool exists(uint256 hash) | |
1074 | { | |
1075 | return (mapTx.count(hash) != 0); | |
1076 | } | |
1077 | ||
1078 | CTransaction& lookup(uint256 hash) | |
1079 | { | |
1080 | return mapTx[hash]; | |
1081 | } | |
235507ae JG |
1082 | }; |
1083 | ||
8e45ed66 JG |
1084 | extern CTxMemPool mempool; |
1085 | ||
beeb5761 PW |
1086 | struct CCoinsStats |
1087 | { | |
1088 | int nHeight; | |
e31aa7c9 | 1089 | uint256 hashBlock; |
beeb5761 PW |
1090 | uint64 nTransactions; |
1091 | uint64 nTransactionOutputs; | |
1092 | uint64 nSerializedSize; | |
e31aa7c9 PW |
1093 | uint256 hashSerialized; |
1094 | int64 nTotalAmount; | |
beeb5761 | 1095 | |
e31aa7c9 | 1096 | CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {} |
beeb5761 PW |
1097 | }; |
1098 | ||
450cbb09 PW |
1099 | /** Abstract view on the open txout dataset. */ |
1100 | class CCoinsView | |
1101 | { | |
1102 | public: | |
1103 | // Retrieve the CCoins (unspent transaction outputs) for a given txid | |
f369d02c | 1104 | virtual bool GetCoins(const uint256 &txid, CCoins &coins); |
450cbb09 PW |
1105 | |
1106 | // Modify the CCoins for a given txid | |
f369d02c | 1107 | virtual bool SetCoins(const uint256 &txid, const CCoins &coins); |
450cbb09 PW |
1108 | |
1109 | // Just check whether we have data for a given txid. | |
1110 | // This may (but cannot always) return true for fully spent transactions | |
f369d02c | 1111 | virtual bool HaveCoins(const uint256 &txid); |
450cbb09 PW |
1112 | |
1113 | // Retrieve the block index whose state this CCoinsView currently represents | |
1114 | virtual CBlockIndex *GetBestBlock(); | |
1115 | ||
1116 | // Modify the currently active block index | |
1117 | virtual bool SetBestBlock(CBlockIndex *pindex); | |
c2ed184f PW |
1118 | |
1119 | // Do a bulk modification (multiple SetCoins + one SetBestBlock) | |
ae8bfd12 | 1120 | virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); |
c2ed184f PW |
1121 | |
1122 | // Calculate statistics about the unspent transaction output set | |
beeb5761 | 1123 | virtual bool GetStats(CCoinsStats &stats); |
c9c7d482 PW |
1124 | |
1125 | // As we use CCoinsViews polymorphically, have a virtual destructor | |
13e5cce4 | 1126 | virtual ~CCoinsView() {} |
450cbb09 PW |
1127 | }; |
1128 | ||
1129 | /** CCoinsView backed by another CCoinsView */ | |
1130 | class CCoinsViewBacked : public CCoinsView | |
1131 | { | |
1132 | protected: | |
1133 | CCoinsView *base; | |
1134 | ||
1135 | public: | |
1136 | CCoinsViewBacked(CCoinsView &viewIn); | |
f369d02c PW |
1137 | bool GetCoins(const uint256 &txid, CCoins &coins); |
1138 | bool SetCoins(const uint256 &txid, const CCoins &coins); | |
1139 | bool HaveCoins(const uint256 &txid); | |
450cbb09 PW |
1140 | CBlockIndex *GetBestBlock(); |
1141 | bool SetBestBlock(CBlockIndex *pindex); | |
1142 | void SetBackend(CCoinsView &viewIn); | |
ae8bfd12 | 1143 | bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); |
beeb5761 | 1144 | bool GetStats(CCoinsStats &stats); |
450cbb09 PW |
1145 | }; |
1146 | ||
1147 | /** CCoinsView that adds a memory cache for transactions to another CCoinsView */ | |
1148 | class CCoinsViewCache : public CCoinsViewBacked | |
1149 | { | |
1150 | protected: | |
1151 | CBlockIndex *pindexTip; | |
1152 | std::map<uint256,CCoins> cacheCoins; | |
1153 | ||
1154 | public: | |
1155 | CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false); | |
c2ed184f PW |
1156 | |
1157 | // Standard CCoinsView methods | |
f369d02c PW |
1158 | bool GetCoins(const uint256 &txid, CCoins &coins); |
1159 | bool SetCoins(const uint256 &txid, const CCoins &coins); | |
1160 | bool HaveCoins(const uint256 &txid); | |
450cbb09 PW |
1161 | CBlockIndex *GetBestBlock(); |
1162 | bool SetBestBlock(CBlockIndex *pindex); | |
ae8bfd12 | 1163 | bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); |
c2ed184f PW |
1164 | |
1165 | // Return a modifiable reference to a CCoins. Check HaveCoins first. | |
1166 | // Many methods explicitly require a CCoinsViewCache because of this method, to reduce | |
1167 | // copying. | |
f369d02c | 1168 | CCoins &GetCoins(const uint256 &txid); |
c2ed184f PW |
1169 | |
1170 | // Push the modifications applied to this cache to its base. | |
1171 | // Failure to call this method before destruction will cause the changes to be forgotten. | |
450cbb09 | 1172 | bool Flush(); |
c2ed184f PW |
1173 | |
1174 | // Calculate the size of the cache (in number of transactions) | |
ae8bfd12 | 1175 | unsigned int GetCacheSize(); |
13c51f20 | 1176 | |
05df3fc6 EL |
1177 | /** Amount of bitcoins coming in to a transaction |
1178 | Note that lightweight clients may not know anything besides the hash of previous transactions, | |
1179 | so may not be able to calculate this. | |
1180 | ||
1181 | @param[in] tx transaction for which we are checking input total | |
1182 | @return Sum of value of all inputs (scriptSigs) | |
1183 | @see CTransaction::FetchInputs | |
1184 | */ | |
1185 | int64 GetValueIn(const CTransaction& tx); | |
faaeae1e | 1186 | |
05df3fc6 EL |
1187 | // Check whether all prevouts of the transaction are present in the UTXO set represented by this view |
1188 | bool HaveInputs(const CTransaction& tx); | |
1189 | ||
1190 | const CTxOut &GetOutputFor(const CTxIn& input); | |
1191 | ||
13c51f20 | 1192 | private: |
f369d02c | 1193 | std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid); |
450cbb09 PW |
1194 | }; |
1195 | ||
1196 | /** CCoinsView that brings transactions from a memorypool into view. | |
1197 | It does not check for spendings by memory pool transactions. */ | |
1198 | class CCoinsViewMemPool : public CCoinsViewBacked | |
1199 | { | |
1200 | protected: | |
1201 | CTxMemPool &mempool; | |
1202 | ||
1203 | public: | |
1204 | CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn); | |
f369d02c PW |
1205 | bool GetCoins(const uint256 &txid, CCoins &coins); |
1206 | bool HaveCoins(const uint256 &txid); | |
450cbb09 PW |
1207 | }; |
1208 | ||
d979e6e3 | 1209 | /** Global variable that points to the active CCoinsView (protected by cs_main) */ |
ae8bfd12 PW |
1210 | extern CCoinsViewCache *pcoinsTip; |
1211 | ||
d979e6e3 PW |
1212 | /** Global variable that points to the active block tree (protected by cs_main) */ |
1213 | extern CBlockTreeDB *pblocktree; | |
1214 | ||
03cac0bb FV |
1215 | struct CBlockTemplate |
1216 | { | |
1217 | CBlock block; | |
1218 | std::vector<int64_t> vTxFees; | |
1219 | std::vector<int64_t> vTxSigOps; | |
1220 | }; | |
1221 | ||
9fb106e7 MC |
1222 | |
1223 | ||
1224 | ||
1225 | ||
1226 | ||
1227 | /** Used to relay blocks as header + vector<merkle branch> | |
1228 | * to filtered nodes. | |
1229 | */ | |
1230 | class CMerkleBlock | |
1231 | { | |
1232 | public: | |
21aaf255 | 1233 | // Public only for unit testing |
9fb106e7 | 1234 | CBlockHeader header; |
21aaf255 | 1235 | CPartialMerkleTree txn; |
9fb106e7 | 1236 | |
21aaf255 MC |
1237 | public: |
1238 | // Public only for unit testing and relay testing | |
1239 | // (not relayed) | |
1240 | std::vector<std::pair<unsigned int, uint256> > vMatchedTxn; | |
9fb106e7 MC |
1241 | |
1242 | // Create from a CBlock, filtering transactions according to filter | |
1243 | // Note that this will call IsRelevantAndUpdate on the filter for each transaction, | |
1244 | // thus the filter will likely be modified. | |
1245 | CMerkleBlock(const CBlock& block, CBloomFilter& filter); | |
1246 | ||
1247 | IMPLEMENT_SERIALIZE | |
1248 | ( | |
1249 | READWRITE(header); | |
21aaf255 | 1250 | READWRITE(txn); |
9fb106e7 MC |
1251 | ) |
1252 | }; | |
1253 | ||
00588c3f PW |
1254 | |
1255 | class CWalletInterface { | |
1256 | protected: | |
1257 | virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) =0; | |
1258 | virtual void EraseFromWallet(const uint256 &hash) =0; | |
1259 | virtual void SetBestChain(const CBlockLocator &locator) =0; | |
1260 | virtual void UpdatedTransaction(const uint256 &hash) =0; | |
1261 | virtual void Inventory(const uint256 &hash) =0; | |
1262 | virtual void ResendWalletTransactions() =0; | |
1263 | friend void ::RegisterWallet(CWalletInterface*); | |
1264 | friend void ::UnregisterWallet(CWalletInterface*); | |
1265 | friend void ::UnregisterAllWallets(); | |
1266 | }; | |
1267 | ||
223b6f1b | 1268 | #endif |