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

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