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

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