Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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