You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.h 25KB

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