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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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 sigops we're willing to relay/mine in a single tx */
  43. static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
  44. /** The maximum number of orphan transactions kept in memory */
  45. static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
  46. /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */
  47. static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
  48. /** The maximum size of a blk?????.dat file (since 0.8) */
  49. static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
  50. /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
  51. static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
  52. /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
  53. static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
  54. /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
  55. static const int COINBASE_MATURITY = 100;
  56. /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
  57. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  58. /** Maximum number of script-checking threads allowed */
  59. static const int MAX_SCRIPTCHECK_THREADS = 16;
  60. /** -par default (number of script-checking threads, 0 = auto) */
  61. static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
  62. /** Number of blocks that can be requested at any given time from a single peer. */
  63. static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
  64. /** Timeout in seconds before considering a block download peer unresponsive. */
  65. static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
  66. /** "reject" message codes **/
  67. static const unsigned char REJECT_MALFORMED = 0x01;
  68. static const unsigned char REJECT_INVALID = 0x10;
  69. static const unsigned char REJECT_OBSOLETE = 0x11;
  70. static const unsigned char REJECT_DUPLICATE = 0x12;
  71. static const unsigned char REJECT_NONSTANDARD = 0x40;
  72. static const unsigned char REJECT_DUST = 0x41;
  73. static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
  74. static const unsigned char REJECT_CHECKPOINT = 0x43;
  75. extern CScript COINBASE_FLAGS;
  76. extern CCriticalSection cs_main;
  77. extern CTxMemPool mempool;
  78. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  79. extern uint64_t nLastBlockTx;
  80. extern uint64_t nLastBlockSize;
  81. extern const std::string strMessageMagic;
  82. extern int64_t nTimeBestReceived;
  83. extern CWaitableCriticalSection csBestBlock;
  84. extern CConditionVariable cvBlockChange;
  85. extern bool fImporting;
  86. extern bool fReindex;
  87. extern int nScriptCheckThreads;
  88. extern bool fTxIndex;
  89. extern bool fIsBareMultisigStd;
  90. extern unsigned int nCoinCacheSize;
  91. extern CFeeRate minRelayTxFee;
  92. // Minimum disk space required - used in CheckDiskSpace()
  93. static const uint64_t nMinDiskSpace = 52428800;
  94. class CBlockTreeDB;
  95. struct CDiskBlockPos;
  96. class CTxUndo;
  97. class CScriptCheck;
  98. class CValidationState;
  99. class CWalletInterface;
  100. struct CNodeStateStats;
  101. struct CBlockTemplate;
  102. /** Register a wallet to receive updates from core */
  103. void RegisterWallet(CWalletInterface* pwalletIn);
  104. /** Unregister a wallet from core */
  105. void UnregisterWallet(CWalletInterface* pwalletIn);
  106. /** Unregister all wallets from core */
  107. void UnregisterAllWallets();
  108. /** Push an updated transaction to all registered wallets */
  109. void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
  110. /** Register with a network node to receive its signals */
  111. void RegisterNodeSignals(CNodeSignals& nodeSignals);
  112. /** Unregister a network node */
  113. void UnregisterNodeSignals(CNodeSignals& nodeSignals);
  114. void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
  115. /** Process an incoming block */
  116. bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
  117. /** Check whether enough disk space is available for an incoming block */
  118. bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
  119. /** Open a block file (blk?????.dat) */
  120. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  121. /** Open an undo file (rev?????.dat) */
  122. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  123. /** Import blocks from an external file */
  124. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
  125. /** Initialize a new block tree database + block data on disk */
  126. bool InitBlockIndex();
  127. /** Load the block tree and coins database from disk */
  128. bool LoadBlockIndex();
  129. /** Unload database information */
  130. void UnloadBlockIndex();
  131. /** Print the loaded block tree */
  132. void PrintBlockTree();
  133. /** Process protocol messages received from a given node */
  134. bool ProcessMessages(CNode* pfrom);
  135. /** Send queued protocol messages to be sent to a give node */
  136. bool SendMessages(CNode* pto, bool fSendTrickle);
  137. /** Run an instance of the script checking thread */
  138. void ThreadScriptCheck();
  139. /** Check whether we are doing an initial block download (synchronizing from disk or network) */
  140. bool IsInitialBlockDownload();
  141. /** Format a string that describes several potential problems detected by the core */
  142. std::string GetWarnings(std::string strFor);
  143. /** Retrieve a transaction (from memory pool, or from disk, if possible) */
  144. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
  145. /** Find the best known block, and make it the tip of the block chain */
  146. bool ActivateBestChain(CValidationState &state);
  147. int64_t GetBlockValue(int nHeight, int64_t nFees);
  148. void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev);
  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. IMPLEMENT_SERIALIZE(
  171. READWRITE(VARINT(nFile));
  172. READWRITE(VARINT(nPos));
  173. )
  174. CDiskBlockPos() {
  175. SetNull();
  176. }
  177. CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
  178. nFile = nFileIn;
  179. nPos = nPosIn;
  180. }
  181. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  182. return (a.nFile == b.nFile && a.nPos == b.nPos);
  183. }
  184. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  185. return !(a == b);
  186. }
  187. void SetNull() { nFile = -1; nPos = 0; }
  188. bool IsNull() const { return (nFile == -1); }
  189. };
  190. struct CDiskTxPos : public CDiskBlockPos
  191. {
  192. unsigned int nTxOffset; // after header
  193. IMPLEMENT_SERIALIZE(
  194. READWRITE(*(CDiskBlockPos*)this);
  195. READWRITE(VARINT(nTxOffset));
  196. )
  197. CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
  198. }
  199. CDiskTxPos() {
  200. SetNull();
  201. }
  202. void SetNull() {
  203. CDiskBlockPos::SetNull();
  204. nTxOffset = 0;
  205. }
  206. };
  207. int64_t GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
  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, const 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, const 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, const 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, bool fRejectInsaneFee=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. // pointer to the index of some further predecessor of this block
  555. CBlockIndex* pskip;
  556. // height of the entry in the chain. The genesis block has height 0
  557. int nHeight;
  558. // Which # file this block is stored in (blk?????.dat)
  559. int nFile;
  560. // Byte offset within blk?????.dat where this block's data is stored
  561. unsigned int nDataPos;
  562. // Byte offset within rev?????.dat where this block's undo data is stored
  563. unsigned int nUndoPos;
  564. // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  565. uint256 nChainWork;
  566. // Number of transactions in this block.
  567. // Note: in a potential headers-first mode, this number cannot be relied upon
  568. unsigned int nTx;
  569. // (memory only) Number of transactions in the chain up to and including this block
  570. unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
  571. // Verification status of this block. See enum BlockStatus
  572. unsigned int nStatus;
  573. // block header
  574. int nVersion;
  575. uint256 hashMerkleRoot;
  576. unsigned int nTime;
  577. unsigned int nBits;
  578. unsigned int nNonce;
  579. // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
  580. uint32_t nSequenceId;
  581. void SetNull()
  582. {
  583. phashBlock = NULL;
  584. pprev = NULL;
  585. pskip = NULL;
  586. nHeight = 0;
  587. nFile = 0;
  588. nDataPos = 0;
  589. nUndoPos = 0;
  590. nChainWork = 0;
  591. nTx = 0;
  592. nChainTx = 0;
  593. nStatus = 0;
  594. nSequenceId = 0;
  595. nVersion = 0;
  596. hashMerkleRoot = 0;
  597. nTime = 0;
  598. nBits = 0;
  599. nNonce = 0;
  600. }
  601. CBlockIndex()
  602. {
  603. SetNull();
  604. }
  605. CBlockIndex(CBlockHeader& block)
  606. {
  607. SetNull();
  608. nVersion = block.nVersion;
  609. hashMerkleRoot = block.hashMerkleRoot;
  610. nTime = block.nTime;
  611. nBits = block.nBits;
  612. nNonce = block.nNonce;
  613. }
  614. CDiskBlockPos GetBlockPos() const {
  615. CDiskBlockPos ret;
  616. if (nStatus & BLOCK_HAVE_DATA) {
  617. ret.nFile = nFile;
  618. ret.nPos = nDataPos;
  619. }
  620. return ret;
  621. }
  622. CDiskBlockPos GetUndoPos() const {
  623. CDiskBlockPos ret;
  624. if (nStatus & BLOCK_HAVE_UNDO) {
  625. ret.nFile = nFile;
  626. ret.nPos = nUndoPos;
  627. }
  628. return ret;
  629. }
  630. CBlockHeader GetBlockHeader() const
  631. {
  632. CBlockHeader block;
  633. block.nVersion = nVersion;
  634. if (pprev)
  635. block.hashPrevBlock = pprev->GetBlockHash();
  636. block.hashMerkleRoot = hashMerkleRoot;
  637. block.nTime = nTime;
  638. block.nBits = nBits;
  639. block.nNonce = nNonce;
  640. return block;
  641. }
  642. uint256 GetBlockHash() const
  643. {
  644. return *phashBlock;
  645. }
  646. int64_t GetBlockTime() const
  647. {
  648. return (int64_t)nTime;
  649. }
  650. uint256 GetBlockWork() const
  651. {
  652. uint256 bnTarget;
  653. bool fNegative;
  654. bool fOverflow;
  655. bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
  656. if (fNegative || fOverflow || bnTarget == 0)
  657. return 0;
  658. // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
  659. // as it's too large for a uint256. However, as 2**256 is at least as large
  660. // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
  661. // or ~bnTarget / (nTarget+1) + 1.
  662. return (~bnTarget / (bnTarget + 1)) + 1;
  663. }
  664. enum { nMedianTimeSpan=11 };
  665. int64_t GetMedianTimePast() const
  666. {
  667. int64_t pmedian[nMedianTimeSpan];
  668. int64_t* pbegin = &pmedian[nMedianTimeSpan];
  669. int64_t* pend = &pmedian[nMedianTimeSpan];
  670. const CBlockIndex* pindex = this;
  671. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  672. *(--pbegin) = pindex->GetBlockTime();
  673. std::sort(pbegin, pend);
  674. return pbegin[(pend - pbegin)/2];
  675. }
  676. /**
  677. * Returns true if there are nRequired or more blocks of minVersion or above
  678. * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
  679. * and going backwards.
  680. */
  681. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  682. unsigned int nRequired);
  683. std::string ToString() const
  684. {
  685. return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  686. pprev, nHeight,
  687. hashMerkleRoot.ToString(),
  688. GetBlockHash().ToString());
  689. }
  690. // Check whether this block index entry is valid up to the passed validity level.
  691. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
  692. {
  693. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  694. if (nStatus & BLOCK_FAILED_MASK)
  695. return false;
  696. return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
  697. }
  698. // Raise the validity level of this block index entry.
  699. // Returns true if the validity was changed.
  700. bool RaiseValidity(enum BlockStatus nUpTo)
  701. {
  702. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  703. if (nStatus & BLOCK_FAILED_MASK)
  704. return false;
  705. if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
  706. nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
  707. return true;
  708. }
  709. return false;
  710. }
  711. // Build the skiplist pointer for this entry.
  712. void BuildSkip();
  713. // Efficiently find an ancestor of this block.
  714. CBlockIndex* GetAncestor(int height);
  715. const CBlockIndex* GetAncestor(int height) const;
  716. };
  717. /** Used to marshal pointers into hashes for db storage. */
  718. class CDiskBlockIndex : public CBlockIndex
  719. {
  720. public:
  721. uint256 hashPrev;
  722. CDiskBlockIndex() {
  723. hashPrev = 0;
  724. }
  725. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
  726. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  727. }
  728. IMPLEMENT_SERIALIZE
  729. (
  730. if (!(nType & SER_GETHASH))
  731. READWRITE(VARINT(nVersion));
  732. READWRITE(VARINT(nHeight));
  733. READWRITE(VARINT(nStatus));
  734. READWRITE(VARINT(nTx));
  735. if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
  736. READWRITE(VARINT(nFile));
  737. if (nStatus & BLOCK_HAVE_DATA)
  738. READWRITE(VARINT(nDataPos));
  739. if (nStatus & BLOCK_HAVE_UNDO)
  740. READWRITE(VARINT(nUndoPos));
  741. // block header
  742. READWRITE(this->nVersion);
  743. READWRITE(hashPrev);
  744. READWRITE(hashMerkleRoot);
  745. READWRITE(nTime);
  746. READWRITE(nBits);
  747. READWRITE(nNonce);
  748. )
  749. uint256 GetBlockHash() const
  750. {
  751. CBlockHeader block;
  752. block.nVersion = nVersion;
  753. block.hashPrevBlock = hashPrev;
  754. block.hashMerkleRoot = hashMerkleRoot;
  755. block.nTime = nTime;
  756. block.nBits = nBits;
  757. block.nNonce = nNonce;
  758. return block.GetHash();
  759. }
  760. std::string ToString() const
  761. {
  762. std::string str = "CDiskBlockIndex(";
  763. str += CBlockIndex::ToString();
  764. str += strprintf("\n hashBlock=%s, hashPrev=%s)",
  765. GetBlockHash().ToString(),
  766. hashPrev.ToString());
  767. return str;
  768. }
  769. };
  770. /** Capture information about block/transaction validation */
  771. class CValidationState {
  772. private:
  773. enum mode_state {
  774. MODE_VALID, // everything ok
  775. MODE_INVALID, // network rule violation (DoS value may be set)
  776. MODE_ERROR, // run-time error
  777. } mode;
  778. int nDoS;
  779. std::string strRejectReason;
  780. unsigned char chRejectCode;
  781. bool corruptionPossible;
  782. public:
  783. CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
  784. bool DoS(int level, bool ret = false,
  785. unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
  786. bool corruptionIn=false) {
  787. chRejectCode = chRejectCodeIn;
  788. strRejectReason = strRejectReasonIn;
  789. corruptionPossible = corruptionIn;
  790. if (mode == MODE_ERROR)
  791. return ret;
  792. nDoS += level;
  793. mode = MODE_INVALID;
  794. return ret;
  795. }
  796. bool Invalid(bool ret = false,
  797. unsigned char _chRejectCode=0, std::string _strRejectReason="") {
  798. return DoS(0, ret, _chRejectCode, _strRejectReason);
  799. }
  800. bool Error(std::string strRejectReasonIn="") {
  801. if (mode == MODE_VALID)
  802. strRejectReason = strRejectReasonIn;
  803. mode = MODE_ERROR;
  804. return false;
  805. }
  806. bool Abort(const std::string &msg) {
  807. AbortNode(msg);
  808. return Error(msg);
  809. }
  810. bool IsValid() const {
  811. return mode == MODE_VALID;
  812. }
  813. bool IsInvalid() const {
  814. return mode == MODE_INVALID;
  815. }
  816. bool IsError() const {
  817. return mode == MODE_ERROR;
  818. }
  819. bool IsInvalid(int &nDoSOut) const {
  820. if (IsInvalid()) {
  821. nDoSOut = nDoS;
  822. return true;
  823. }
  824. return false;
  825. }
  826. bool CorruptionPossible() const {
  827. return corruptionPossible;
  828. }
  829. unsigned char GetRejectCode() const { return chRejectCode; }
  830. std::string GetRejectReason() const { return strRejectReason; }
  831. };
  832. /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
  833. class CVerifyDB {
  834. public:
  835. CVerifyDB();
  836. ~CVerifyDB();
  837. bool VerifyDB(int nCheckLevel, int nCheckDepth);
  838. };
  839. /** An in-memory indexed chain of blocks. */
  840. class CChain {
  841. private:
  842. std::vector<CBlockIndex*> vChain;
  843. public:
  844. /** Returns the index entry for the genesis block of this chain, or NULL if none. */
  845. CBlockIndex *Genesis() const {
  846. return vChain.size() > 0 ? vChain[0] : NULL;
  847. }
  848. /** Returns the index entry for the tip of this chain, or NULL if none. */
  849. CBlockIndex *Tip() const {
  850. return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
  851. }
  852. /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
  853. CBlockIndex *operator[](int nHeight) const {
  854. if (nHeight < 0 || nHeight >= (int)vChain.size())
  855. return NULL;
  856. return vChain[nHeight];
  857. }
  858. /** Compare two chains efficiently. */
  859. friend bool operator==(const CChain &a, const CChain &b) {
  860. return a.vChain.size() == b.vChain.size() &&
  861. a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
  862. }
  863. /** Efficiently check whether a block is present in this chain. */
  864. bool Contains(const CBlockIndex *pindex) const {
  865. return (*this)[pindex->nHeight] == pindex;
  866. }
  867. /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
  868. CBlockIndex *Next(const CBlockIndex *pindex) const {
  869. if (Contains(pindex))
  870. return (*this)[pindex->nHeight + 1];
  871. else
  872. return NULL;
  873. }
  874. /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
  875. int Height() const {
  876. return vChain.size() - 1;
  877. }
  878. /** Set/initialize a chain with a given tip. Returns the forking point. */
  879. CBlockIndex *SetTip(CBlockIndex *pindex);
  880. /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
  881. CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
  882. /** Find the last common block between this chain and a locator. */
  883. CBlockIndex *FindFork(const CBlockLocator &locator) const;
  884. /** Find the last common block between this chain and a block index entry. */
  885. const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
  886. };
  887. /** The currently-connected chain of blocks. */
  888. extern CChain chainActive;
  889. /** Global variable that points to the active CCoinsView (protected by cs_main) */
  890. extern CCoinsViewCache *pcoinsTip;
  891. /** Global variable that points to the active block tree (protected by cs_main) */
  892. extern CBlockTreeDB *pblocktree;
  893. struct CBlockTemplate
  894. {
  895. CBlock block;
  896. std::vector<int64_t> vTxFees;
  897. std::vector<int64_t> vTxSigOps;
  898. };
  899. /** Used to relay blocks as header + vector<merkle branch>
  900. * to filtered nodes.
  901. */
  902. class CMerkleBlock
  903. {
  904. public:
  905. // Public only for unit testing
  906. CBlockHeader header;
  907. CPartialMerkleTree txn;
  908. public:
  909. // Public only for unit testing and relay testing
  910. // (not relayed)
  911. std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
  912. // Create from a CBlock, filtering transactions according to filter
  913. // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
  914. // thus the filter will likely be modified.
  915. CMerkleBlock(const CBlock& block, CBloomFilter& filter);
  916. IMPLEMENT_SERIALIZE
  917. (
  918. READWRITE(header);
  919. READWRITE(txn);
  920. )
  921. };
  922. class CWalletInterface {
  923. protected:
  924. virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) =0;
  925. virtual void EraseFromWallet(const uint256 &hash) =0;
  926. virtual void SetBestChain(const CBlockLocator &locator) =0;
  927. virtual void UpdatedTransaction(const uint256 &hash) =0;
  928. virtual void Inventory(const uint256 &hash) =0;
  929. virtual void ResendWalletTransactions() =0;
  930. friend void ::RegisterWallet(CWalletInterface*);
  931. friend void ::UnregisterWallet(CWalletInterface*);
  932. friend void ::UnregisterAllWallets();
  933. };
  934. #endif