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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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 "chainparams.h"
  11. #include "coins.h"
  12. #include "core.h"
  13. #include "net.h"
  14. #include "pow.h"
  15. #include "script.h"
  16. #include "sync.h"
  17. #include "txmempool.h"
  18. #include "uint256.h"
  19. #include <algorithm>
  20. #include <exception>
  21. #include <map>
  22. #include <set>
  23. #include <stdint.h>
  24. #include <string>
  25. #include <utility>
  26. #include <vector>
  27. class CBlockIndex;
  28. class CBloomFilter;
  29. class CInv;
  30. /** The maximum allowed size for a serialized block, in bytes (network rule) */
  31. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  32. /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
  33. static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
  34. static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
  35. /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
  36. static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
  37. /** The maximum size for transactions we're willing to relay/mine */
  38. static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
  39. /** The maximum allowed number of signature check operations in a block (network rule) */
  40. static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  41. /** Maxiumum number of signature check operations in an IsStandard() P2SH script */
  42. static const unsigned int MAX_P2SH_SIGOPS = 15;
  43. /** The maximum number of sigops we're willing to relay/mine in a single tx */
  44. static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
  45. /** The maximum number of orphan transactions kept in memory */
  46. static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
  47. /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */
  48. static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
  49. /** The maximum size of a blk?????.dat file (since 0.8) */
  50. static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
  51. /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
  52. static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
  53. /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
  54. static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
  55. /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
  56. static const int COINBASE_MATURITY = 100;
  57. /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
  58. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  59. /** Maximum number of script-checking threads allowed */
  60. static const int MAX_SCRIPTCHECK_THREADS = 16;
  61. /** -par default (number of script-checking threads, 0 = auto) */
  62. static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
  63. /** Number of blocks that can be requested at any given time from a single peer. */
  64. static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
  65. /** Timeout in seconds before considering a block download peer unresponsive. */
  66. static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
  67. /** "reject" message codes **/
  68. static const unsigned char REJECT_MALFORMED = 0x01;
  69. static const unsigned char REJECT_INVALID = 0x10;
  70. static const unsigned char REJECT_OBSOLETE = 0x11;
  71. static const unsigned char REJECT_DUPLICATE = 0x12;
  72. static const unsigned char REJECT_NONSTANDARD = 0x40;
  73. static const unsigned char REJECT_DUST = 0x41;
  74. static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
  75. static const unsigned char REJECT_CHECKPOINT = 0x43;
  76. extern CScript COINBASE_FLAGS;
  77. extern CCriticalSection cs_main;
  78. extern CTxMemPool mempool;
  79. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  80. extern uint64_t nLastBlockTx;
  81. extern uint64_t nLastBlockSize;
  82. extern const std::string strMessageMagic;
  83. extern int64_t nTimeBestReceived;
  84. extern CWaitableCriticalSection csBestBlock;
  85. extern CConditionVariable cvBlockChange;
  86. extern bool fImporting;
  87. extern bool fReindex;
  88. extern int nScriptCheckThreads;
  89. extern bool fTxIndex;
  90. extern bool fIsBareMultisigStd;
  91. extern unsigned int nCoinCacheSize;
  92. extern CFeeRate minRelayTxFee;
  93. // Minimum disk space required - used in CheckDiskSpace()
  94. static const uint64_t nMinDiskSpace = 52428800;
  95. class CBlockTreeDB;
  96. struct CDiskBlockPos;
  97. class CTxUndo;
  98. class CScriptCheck;
  99. class CValidationState;
  100. class CWalletInterface;
  101. struct CNodeStateStats;
  102. struct CBlockTemplate;
  103. /** Register a wallet to receive updates from core */
  104. void RegisterWallet(CWalletInterface* pwalletIn);
  105. /** Unregister a wallet from core */
  106. void UnregisterWallet(CWalletInterface* pwalletIn);
  107. /** Unregister all wallets from core */
  108. void UnregisterAllWallets();
  109. /** Push an updated transaction to all registered wallets */
  110. void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
  111. /** Register with a network node to receive its signals */
  112. void RegisterNodeSignals(CNodeSignals& nodeSignals);
  113. /** Unregister a network node */
  114. void UnregisterNodeSignals(CNodeSignals& nodeSignals);
  115. void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
  116. /** Process an incoming block */
  117. bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
  118. /** Check whether enough disk space is available for an incoming block */
  119. bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
  120. /** Open a block file (blk?????.dat) */
  121. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  122. /** Open an undo file (rev?????.dat) */
  123. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  124. /** Import blocks from an external file */
  125. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
  126. /** Initialize a new block tree database + block data on disk */
  127. bool InitBlockIndex();
  128. /** Load the block tree and coins database from disk */
  129. bool LoadBlockIndex();
  130. /** Unload database information */
  131. void UnloadBlockIndex();
  132. /** Print the loaded block tree */
  133. void PrintBlockTree();
  134. /** Process protocol messages received from a given node */
  135. bool ProcessMessages(CNode* pfrom);
  136. /** Send queued protocol messages to be sent to a give node */
  137. bool SendMessages(CNode* pto, bool fSendTrickle);
  138. /** Run an instance of the script checking thread */
  139. void ThreadScriptCheck();
  140. /** Check whether we are doing an initial block download (synchronizing from disk or network) */
  141. bool IsInitialBlockDownload();
  142. /** Format a string that describes several potential problems detected by the core */
  143. std::string GetWarnings(std::string strFor);
  144. /** Retrieve a transaction (from memory pool, or from disk, if possible) */
  145. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
  146. /** Find the best known block, and make it the tip of the block chain */
  147. bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
  148. int64_t GetBlockValue(int nHeight, int64_t nFees);
  149. /** Create a new block index entry for a given block hash */
  150. CBlockIndex * InsertBlockIndex(uint256 hash);
  151. /** Verify a signature */
  152. bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
  153. /** Abort with a message */
  154. bool AbortNode(const std::string &msg);
  155. /** Get statistics from node state */
  156. bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
  157. /** Increase a node's misbehavior score. */
  158. void Misbehaving(NodeId nodeid, int howmuch);
  159. /** (try to) add transaction to memory pool **/
  160. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
  161. bool* pfMissingInputs, bool fRejectInsaneFee=false);
  162. struct CNodeStateStats {
  163. int nMisbehavior;
  164. int nSyncHeight;
  165. };
  166. struct CDiskBlockPos
  167. {
  168. int nFile;
  169. unsigned int nPos;
  170. ADD_SERIALIZE_METHODS;
  171. template <typename Stream, typename Operation>
  172. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  173. READWRITE(VARINT(nFile));
  174. READWRITE(VARINT(nPos));
  175. }
  176. CDiskBlockPos() {
  177. SetNull();
  178. }
  179. CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
  180. nFile = nFileIn;
  181. nPos = nPosIn;
  182. }
  183. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  184. return (a.nFile == b.nFile && a.nPos == b.nPos);
  185. }
  186. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  187. return !(a == b);
  188. }
  189. void SetNull() { nFile = -1; nPos = 0; }
  190. bool IsNull() const { return (nFile == -1); }
  191. };
  192. struct CDiskTxPos : public CDiskBlockPos
  193. {
  194. unsigned int nTxOffset; // after header
  195. ADD_SERIALIZE_METHODS;
  196. template <typename Stream, typename Operation>
  197. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  198. READWRITE(*(CDiskBlockPos*)this);
  199. READWRITE(VARINT(nTxOffset));
  200. }
  201. CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
  202. }
  203. CDiskTxPos() {
  204. SetNull();
  205. }
  206. void SetNull() {
  207. CDiskBlockPos::SetNull();
  208. nTxOffset = 0;
  209. }
  210. };
  211. int64_t GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
  212. //
  213. // Check transaction inputs, and make sure any
  214. // pay-to-script-hash transactions are evaluating IsStandard scripts
  215. //
  216. // Why bother? To avoid denial-of-service attacks; an attacker
  217. // can submit a standard HASH... OP_EQUAL transaction,
  218. // which will get accepted into blocks. The redemption
  219. // script can be anything; an attacker could use a very
  220. // expensive-to-check-upon-redemption script like:
  221. // DUP CHECKSIG DROP ... repeated 100 times... OP_1
  222. //
  223. /** Check for standard transaction types
  224. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  225. @return True if all inputs (scriptSigs) use only standard transaction forms
  226. */
  227. bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
  228. /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
  229. @return number of sigops this transaction's outputs will produce when spent
  230. @see CTransaction::FetchInputs
  231. */
  232. unsigned int GetLegacySigOpCount(const CTransaction& tx);
  233. /** Count ECDSA signature operations in pay-to-script-hash inputs.
  234. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  235. @return maximum number of sigops required to validate this transaction's inputs
  236. @see CTransaction::FetchInputs
  237. */
  238. unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
  239. // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
  240. // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
  241. // instead of being performed inline.
  242. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks = true,
  243. unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS,
  244. std::vector<CScriptCheck> *pvChecks = NULL);
  245. // Apply the effects of this transaction on the UTXO set represented by view
  246. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight);
  247. // Context-independent validity checks
  248. bool CheckTransaction(const CTransaction& tx, CValidationState& state);
  249. /** Check for standard transaction types
  250. @return True if all outputs (scriptPubKeys) use only standard transaction forms
  251. */
  252. bool IsStandardTx(const CTransaction& tx, std::string& reason);
  253. bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
  254. /** Undo information for a CBlock */
  255. class CBlockUndo
  256. {
  257. public:
  258. std::vector<CTxUndo> vtxundo; // for all but the coinbase
  259. ADD_SERIALIZE_METHODS;
  260. template <typename Stream, typename Operation>
  261. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  262. READWRITE(vtxundo);
  263. }
  264. bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock);
  265. bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock);
  266. };
  267. /** Closure representing one script verification
  268. * Note that this stores references to the spending transaction */
  269. class CScriptCheck
  270. {
  271. private:
  272. CScript scriptPubKey;
  273. const CTransaction *ptxTo;
  274. unsigned int nIn;
  275. unsigned int nFlags;
  276. int nHashType;
  277. public:
  278. CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), nHashType(0) {}
  279. CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
  280. scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
  281. ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
  282. bool operator()() const;
  283. void swap(CScriptCheck &check) {
  284. scriptPubKey.swap(check.scriptPubKey);
  285. std::swap(ptxTo, check.ptxTo);
  286. std::swap(nIn, check.nIn);
  287. std::swap(nFlags, check.nFlags);
  288. std::swap(nHashType, check.nHashType);
  289. }
  290. };
  291. /** Data structure that represents a partial merkle tree.
  292. *
  293. * It respresents a subset of the txid's of a known block, in a way that
  294. * allows recovery of the list of txid's and the merkle root, in an
  295. * authenticated way.
  296. *
  297. * The encoding works as follows: we traverse the tree in depth-first order,
  298. * storing a bit for each traversed node, signifying whether the node is the
  299. * parent of at least one matched leaf txid (or a matched txid itself). In
  300. * case we are at the leaf level, or this bit is 0, its merkle node hash is
  301. * stored, and its children are not explorer further. Otherwise, no hash is
  302. * stored, but we recurse into both (or the only) child branch. During
  303. * decoding, the same depth-first traversal is performed, consuming bits and
  304. * hashes as they written during encoding.
  305. *
  306. * The serialization is fixed and provides a hard guarantee about the
  307. * encoded size:
  308. *
  309. * SIZE <= 10 + ceil(32.25*N)
  310. *
  311. * Where N represents the number of leaf nodes of the partial tree. N itself
  312. * is bounded by:
  313. *
  314. * N <= total_transactions
  315. * N <= 1 + matched_transactions*tree_height
  316. *
  317. * The serialization format:
  318. * - uint32 total_transactions (4 bytes)
  319. * - varint number of hashes (1-3 bytes)
  320. * - uint256[] hashes in depth-first order (<= 32*N bytes)
  321. * - varint number of bytes of flag bits (1-3 bytes)
  322. * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
  323. * The size constraints follow from this.
  324. */
  325. class CPartialMerkleTree
  326. {
  327. protected:
  328. // the total number of transactions in the block
  329. unsigned int nTransactions;
  330. // node-is-parent-of-matched-txid bits
  331. std::vector<bool> vBits;
  332. // txids and internal hashes
  333. std::vector<uint256> vHash;
  334. // flag set when encountering invalid data
  335. bool fBad;
  336. // helper function to efficiently calculate the number of nodes at given height in the merkle tree
  337. unsigned int CalcTreeWidth(int height) {
  338. return (nTransactions+(1 << height)-1) >> height;
  339. }
  340. // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
  341. uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
  342. // recursive function that traverses tree nodes, storing the data as bits and hashes
  343. void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  344. // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
  345. // it returns the hash of the respective node.
  346. uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
  347. public:
  348. // serialization implementation
  349. ADD_SERIALIZE_METHODS;
  350. template <typename Stream, typename Operation>
  351. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  352. READWRITE(nTransactions);
  353. READWRITE(vHash);
  354. std::vector<unsigned char> vBytes;
  355. if (ser_action.ForRead()) {
  356. READWRITE(vBytes);
  357. CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
  358. us.vBits.resize(vBytes.size() * 8);
  359. for (unsigned int p = 0; p < us.vBits.size(); p++)
  360. us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
  361. us.fBad = false;
  362. } else {
  363. vBytes.resize((vBits.size()+7)/8);
  364. for (unsigned int p = 0; p < vBits.size(); p++)
  365. vBytes[p / 8] |= vBits[p] << (p % 8);
  366. READWRITE(vBytes);
  367. }
  368. }
  369. // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
  370. CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  371. CPartialMerkleTree();
  372. // extract the matching txid's represented by this partial merkle tree.
  373. // returns the merkle root, or 0 in case of failure
  374. uint256 ExtractMatches(std::vector<uint256> &vMatch);
  375. };
  376. /** Functions for disk access for blocks */
  377. bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
  378. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
  379. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
  380. /** Functions for validating blocks and updating the block tree */
  381. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
  382. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
  383. * will be true if no problems were found. Otherwise, the return value will be false in case
  384. * of problems. Note that in any case, coins may be modified. */
  385. bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
  386. // Apply the effects of this block (with given index) on the UTXO set represented by coins
  387. bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
  388. // Add this block to the block index, and if necessary, switch the active block chain to this
  389. bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
  390. // Context-independent validity checks
  391. bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
  392. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
  393. // Store block on disk
  394. // if dbp is provided, the file is known to already reside on disk
  395. bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL);
  396. bool AcceptBlockHeader(CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
  397. class CBlockFileInfo
  398. {
  399. public:
  400. unsigned int nBlocks; // number of blocks stored in file
  401. unsigned int nSize; // number of used bytes of block file
  402. unsigned int nUndoSize; // number of used bytes in the undo file
  403. unsigned int nHeightFirst; // lowest height of block in file
  404. unsigned int nHeightLast; // highest height of block in file
  405. uint64_t nTimeFirst; // earliest time of block in file
  406. uint64_t nTimeLast; // latest time of block in file
  407. ADD_SERIALIZE_METHODS;
  408. template <typename Stream, typename Operation>
  409. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  410. READWRITE(VARINT(nBlocks));
  411. READWRITE(VARINT(nSize));
  412. READWRITE(VARINT(nUndoSize));
  413. READWRITE(VARINT(nHeightFirst));
  414. READWRITE(VARINT(nHeightLast));
  415. READWRITE(VARINT(nTimeFirst));
  416. READWRITE(VARINT(nTimeLast));
  417. }
  418. void SetNull() {
  419. nBlocks = 0;
  420. nSize = 0;
  421. nUndoSize = 0;
  422. nHeightFirst = 0;
  423. nHeightLast = 0;
  424. nTimeFirst = 0;
  425. nTimeLast = 0;
  426. }
  427. CBlockFileInfo() {
  428. SetNull();
  429. }
  430. std::string ToString() const;
  431. // update statistics (does not update nSize)
  432. void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
  433. if (nBlocks==0 || nHeightFirst > nHeightIn)
  434. nHeightFirst = nHeightIn;
  435. if (nBlocks==0 || nTimeFirst > nTimeIn)
  436. nTimeFirst = nTimeIn;
  437. nBlocks++;
  438. if (nHeightIn > nHeightLast)
  439. nHeightLast = nHeightIn;
  440. if (nTimeIn > nTimeLast)
  441. nTimeLast = nTimeIn;
  442. }
  443. };
  444. enum BlockStatus {
  445. BLOCK_VALID_UNKNOWN = 0,
  446. BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
  447. BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
  448. BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
  449. BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
  450. BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
  451. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
  452. BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
  453. BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
  454. BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
  455. BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
  456. BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
  457. BLOCK_FAILED_CHILD = 64, // descends from failed block
  458. BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
  459. };
  460. /** The block chain is a tree shaped structure starting with the
  461. * genesis block at the root, with each block potentially having multiple
  462. * candidates to be the next block. A blockindex may have multiple pprev pointing
  463. * to it, but at most one of them can be part of the currently active branch.
  464. */
  465. class CBlockIndex
  466. {
  467. public:
  468. // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
  469. const uint256* phashBlock;
  470. // pointer to the index of the predecessor of this block
  471. CBlockIndex* pprev;
  472. // pointer to the index of some further predecessor of this block
  473. CBlockIndex* pskip;
  474. // height of the entry in the chain. The genesis block has height 0
  475. int nHeight;
  476. // Which # file this block is stored in (blk?????.dat)
  477. int nFile;
  478. // Byte offset within blk?????.dat where this block's data is stored
  479. unsigned int nDataPos;
  480. // Byte offset within rev?????.dat where this block's undo data is stored
  481. unsigned int nUndoPos;
  482. // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  483. uint256 nChainWork;
  484. // Number of transactions in this block.
  485. // Note: in a potential headers-first mode, this number cannot be relied upon
  486. unsigned int nTx;
  487. // (memory only) Number of transactions in the chain up to and including this block
  488. unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
  489. // Verification status of this block. See enum BlockStatus
  490. unsigned int nStatus;
  491. // block header
  492. int nVersion;
  493. uint256 hashMerkleRoot;
  494. unsigned int nTime;
  495. unsigned int nBits;
  496. unsigned int nNonce;
  497. // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
  498. uint32_t nSequenceId;
  499. void SetNull()
  500. {
  501. phashBlock = NULL;
  502. pprev = NULL;
  503. pskip = NULL;
  504. nHeight = 0;
  505. nFile = 0;
  506. nDataPos = 0;
  507. nUndoPos = 0;
  508. nChainWork = 0;
  509. nTx = 0;
  510. nChainTx = 0;
  511. nStatus = 0;
  512. nSequenceId = 0;
  513. nVersion = 0;
  514. hashMerkleRoot = 0;
  515. nTime = 0;
  516. nBits = 0;
  517. nNonce = 0;
  518. }
  519. CBlockIndex()
  520. {
  521. SetNull();
  522. }
  523. CBlockIndex(CBlockHeader& block)
  524. {
  525. SetNull();
  526. nVersion = block.nVersion;
  527. hashMerkleRoot = block.hashMerkleRoot;
  528. nTime = block.nTime;
  529. nBits = block.nBits;
  530. nNonce = block.nNonce;
  531. }
  532. CDiskBlockPos GetBlockPos() const {
  533. CDiskBlockPos ret;
  534. if (nStatus & BLOCK_HAVE_DATA) {
  535. ret.nFile = nFile;
  536. ret.nPos = nDataPos;
  537. }
  538. return ret;
  539. }
  540. CDiskBlockPos GetUndoPos() const {
  541. CDiskBlockPos ret;
  542. if (nStatus & BLOCK_HAVE_UNDO) {
  543. ret.nFile = nFile;
  544. ret.nPos = nUndoPos;
  545. }
  546. return ret;
  547. }
  548. CBlockHeader GetBlockHeader() const
  549. {
  550. CBlockHeader block;
  551. block.nVersion = nVersion;
  552. if (pprev)
  553. block.hashPrevBlock = pprev->GetBlockHash();
  554. block.hashMerkleRoot = hashMerkleRoot;
  555. block.nTime = nTime;
  556. block.nBits = nBits;
  557. block.nNonce = nNonce;
  558. return block;
  559. }
  560. uint256 GetBlockHash() const
  561. {
  562. return *phashBlock;
  563. }
  564. int64_t GetBlockTime() const
  565. {
  566. return (int64_t)nTime;
  567. }
  568. uint256 GetBlockWork() const
  569. {
  570. return GetProofIncrement(nBits);
  571. }
  572. enum { nMedianTimeSpan=11 };
  573. int64_t GetMedianTimePast() const
  574. {
  575. int64_t pmedian[nMedianTimeSpan];
  576. int64_t* pbegin = &pmedian[nMedianTimeSpan];
  577. int64_t* pend = &pmedian[nMedianTimeSpan];
  578. const CBlockIndex* pindex = this;
  579. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  580. *(--pbegin) = pindex->GetBlockTime();
  581. std::sort(pbegin, pend);
  582. return pbegin[(pend - pbegin)/2];
  583. }
  584. /**
  585. * Returns true if there are nRequired or more blocks of minVersion or above
  586. * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
  587. * and going backwards.
  588. */
  589. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  590. unsigned int nRequired);
  591. std::string ToString() const
  592. {
  593. return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  594. pprev, nHeight,
  595. hashMerkleRoot.ToString(),
  596. GetBlockHash().ToString());
  597. }
  598. // Check whether this block index entry is valid up to the passed validity level.
  599. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
  600. {
  601. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  602. if (nStatus & BLOCK_FAILED_MASK)
  603. return false;
  604. return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
  605. }
  606. // Raise the validity level of this block index entry.
  607. // Returns true if the validity was changed.
  608. bool RaiseValidity(enum BlockStatus nUpTo)
  609. {
  610. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  611. if (nStatus & BLOCK_FAILED_MASK)
  612. return false;
  613. if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
  614. nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
  615. return true;
  616. }
  617. return false;
  618. }
  619. // Build the skiplist pointer for this entry.
  620. void BuildSkip();
  621. // Efficiently find an ancestor of this block.
  622. CBlockIndex* GetAncestor(int height);
  623. const CBlockIndex* GetAncestor(int height) const;
  624. };
  625. /** Used to marshal pointers into hashes for db storage. */
  626. class CDiskBlockIndex : public CBlockIndex
  627. {
  628. public:
  629. uint256 hashPrev;
  630. CDiskBlockIndex() {
  631. hashPrev = 0;
  632. }
  633. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
  634. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  635. }
  636. ADD_SERIALIZE_METHODS;
  637. template <typename Stream, typename Operation>
  638. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  639. if (!(nType & SER_GETHASH))
  640. READWRITE(VARINT(nVersion));
  641. READWRITE(VARINT(nHeight));
  642. READWRITE(VARINT(nStatus));
  643. READWRITE(VARINT(nTx));
  644. if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
  645. READWRITE(VARINT(nFile));
  646. if (nStatus & BLOCK_HAVE_DATA)
  647. READWRITE(VARINT(nDataPos));
  648. if (nStatus & BLOCK_HAVE_UNDO)
  649. READWRITE(VARINT(nUndoPos));
  650. // block header
  651. READWRITE(this->nVersion);
  652. READWRITE(hashPrev);
  653. READWRITE(hashMerkleRoot);
  654. READWRITE(nTime);
  655. READWRITE(nBits);
  656. READWRITE(nNonce);
  657. }
  658. uint256 GetBlockHash() const
  659. {
  660. CBlockHeader block;
  661. block.nVersion = nVersion;
  662. block.hashPrevBlock = hashPrev;
  663. block.hashMerkleRoot = hashMerkleRoot;
  664. block.nTime = nTime;
  665. block.nBits = nBits;
  666. block.nNonce = nNonce;
  667. return block.GetHash();
  668. }
  669. std::string ToString() const
  670. {
  671. std::string str = "CDiskBlockIndex(";
  672. str += CBlockIndex::ToString();
  673. str += strprintf("\n hashBlock=%s, hashPrev=%s)",
  674. GetBlockHash().ToString(),
  675. hashPrev.ToString());
  676. return str;
  677. }
  678. };
  679. /** Capture information about block/transaction validation */
  680. class CValidationState {
  681. private:
  682. enum mode_state {
  683. MODE_VALID, // everything ok
  684. MODE_INVALID, // network rule violation (DoS value may be set)
  685. MODE_ERROR, // run-time error
  686. } mode;
  687. int nDoS;
  688. std::string strRejectReason;
  689. unsigned char chRejectCode;
  690. bool corruptionPossible;
  691. public:
  692. CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
  693. bool DoS(int level, bool ret = false,
  694. unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
  695. bool corruptionIn=false) {
  696. chRejectCode = chRejectCodeIn;
  697. strRejectReason = strRejectReasonIn;
  698. corruptionPossible = corruptionIn;
  699. if (mode == MODE_ERROR)
  700. return ret;
  701. nDoS += level;
  702. mode = MODE_INVALID;
  703. return ret;
  704. }
  705. bool Invalid(bool ret = false,
  706. unsigned char _chRejectCode=0, std::string _strRejectReason="") {
  707. return DoS(0, ret, _chRejectCode, _strRejectReason);
  708. }
  709. bool Error(std::string strRejectReasonIn="") {
  710. if (mode == MODE_VALID)
  711. strRejectReason = strRejectReasonIn;
  712. mode = MODE_ERROR;
  713. return false;
  714. }
  715. bool Abort(const std::string &msg) {
  716. AbortNode(msg);
  717. return Error(msg);
  718. }
  719. bool IsValid() const {
  720. return mode == MODE_VALID;
  721. }
  722. bool IsInvalid() const {
  723. return mode == MODE_INVALID;
  724. }
  725. bool IsError() const {
  726. return mode == MODE_ERROR;
  727. }
  728. bool IsInvalid(int &nDoSOut) const {
  729. if (IsInvalid()) {
  730. nDoSOut = nDoS;
  731. return true;
  732. }
  733. return false;
  734. }
  735. bool CorruptionPossible() const {
  736. return corruptionPossible;
  737. }
  738. unsigned char GetRejectCode() const { return chRejectCode; }
  739. std::string GetRejectReason() const { return strRejectReason; }
  740. };
  741. /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
  742. class CVerifyDB {
  743. public:
  744. CVerifyDB();
  745. ~CVerifyDB();
  746. bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
  747. };
  748. /** An in-memory indexed chain of blocks. */
  749. class CChain {
  750. private:
  751. std::vector<CBlockIndex*> vChain;
  752. public:
  753. /** Returns the index entry for the genesis block of this chain, or NULL if none. */
  754. CBlockIndex *Genesis() const {
  755. return vChain.size() > 0 ? vChain[0] : NULL;
  756. }
  757. /** Returns the index entry for the tip of this chain, or NULL if none. */
  758. CBlockIndex *Tip() const {
  759. return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
  760. }
  761. /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
  762. CBlockIndex *operator[](int nHeight) const {
  763. if (nHeight < 0 || nHeight >= (int)vChain.size())
  764. return NULL;
  765. return vChain[nHeight];
  766. }
  767. /** Compare two chains efficiently. */
  768. friend bool operator==(const CChain &a, const CChain &b) {
  769. return a.vChain.size() == b.vChain.size() &&
  770. a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
  771. }
  772. /** Efficiently check whether a block is present in this chain. */
  773. bool Contains(const CBlockIndex *pindex) const {
  774. return (*this)[pindex->nHeight] == pindex;
  775. }
  776. /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
  777. CBlockIndex *Next(const CBlockIndex *pindex) const {
  778. if (Contains(pindex))
  779. return (*this)[pindex->nHeight + 1];
  780. else
  781. return NULL;
  782. }
  783. /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
  784. int Height() const {
  785. return vChain.size() - 1;
  786. }
  787. /** Set/initialize a chain with a given tip. Returns the forking point. */
  788. CBlockIndex *SetTip(CBlockIndex *pindex);
  789. /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
  790. CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
  791. /** Find the last common block between this chain and a locator. */
  792. CBlockIndex *FindFork(const CBlockLocator &locator) const;
  793. /** Find the last common block between this chain and a block index entry. */
  794. const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
  795. };
  796. /** The currently-connected chain of blocks. */
  797. extern CChain chainActive;
  798. /** Global variable that points to the active CCoinsView (protected by cs_main) */
  799. extern CCoinsViewCache *pcoinsTip;
  800. /** Global variable that points to the active block tree (protected by cs_main) */
  801. extern CBlockTreeDB *pblocktree;
  802. struct CBlockTemplate
  803. {
  804. CBlock block;
  805. std::vector<int64_t> vTxFees;
  806. std::vector<int64_t> vTxSigOps;
  807. };
  808. /** Used to relay blocks as header + vector<merkle branch>
  809. * to filtered nodes.
  810. */
  811. class CMerkleBlock
  812. {
  813. public:
  814. // Public only for unit testing
  815. CBlockHeader header;
  816. CPartialMerkleTree txn;
  817. public:
  818. // Public only for unit testing and relay testing
  819. // (not relayed)
  820. std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
  821. // Create from a CBlock, filtering transactions according to filter
  822. // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
  823. // thus the filter will likely be modified.
  824. CMerkleBlock(const CBlock& block, CBloomFilter& filter);
  825. ADD_SERIALIZE_METHODS;
  826. template <typename Stream, typename Operation>
  827. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  828. READWRITE(header);
  829. READWRITE(txn);
  830. }
  831. };
  832. class CWalletInterface {
  833. protected:
  834. virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) =0;
  835. virtual void EraseFromWallet(const uint256 &hash) =0;
  836. virtual void SetBestChain(const CBlockLocator &locator) =0;
  837. virtual void UpdatedTransaction(const uint256 &hash) =0;
  838. virtual void Inventory(const uint256 &hash) =0;
  839. virtual void ResendWalletTransactions() =0;
  840. friend void ::RegisterWallet(CWalletInterface*);
  841. friend void ::UnregisterWallet(CWalletInterface*);
  842. friend void ::UnregisterAllWallets();
  843. };
  844. #endif // BITCOIN_MAIN_H