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