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

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