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 26KB

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