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

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