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.

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