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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 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. #include "core.h"
  8. #include "bignum.h"
  9. #include "sync.h"
  10. #include "net.h"
  11. #include "script.h"
  12. #include <list>
  13. class CWallet;
  14. class CBlock;
  15. class CBlockIndex;
  16. class CKeyItem;
  17. class CReserveKey;
  18. class CAddress;
  19. class CInv;
  20. class CNode;
  21. struct CBlockIndexWorkComparator;
  22. /** The maximum allowed size for a serialized block, in bytes (network rule) */
  23. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  24. /** The maximum size for mined blocks */
  25. static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  26. /** The maximum size for transactions we're willing to relay/mine */
  27. static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
  28. /** The maximum allowed number of signature check operations in a block (network rule) */
  29. static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  30. /** The maximum number of orphan transactions kept in memory */
  31. static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
  32. /** The maximum size of a blk?????.dat file (since 0.8) */
  33. static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
  34. /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
  35. static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
  36. /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
  37. static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
  38. /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
  39. static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
  40. /** No amount larger than this (in satoshi) is valid */
  41. static const int64 MAX_MONEY = 21000000 * COIN;
  42. inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  43. /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
  44. static const int COINBASE_MATURITY = 100;
  45. /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
  46. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  47. /** Maximum number of script-checking threads allowed */
  48. static const int MAX_SCRIPTCHECK_THREADS = 16;
  49. #ifdef USE_UPNP
  50. static const int fHaveUPnP = true;
  51. #else
  52. static const int fHaveUPnP = false;
  53. #endif
  54. extern CScript COINBASE_FLAGS;
  55. extern CCriticalSection cs_main;
  56. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  57. extern std::vector<CBlockIndex*> vBlockIndexByHeight;
  58. extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
  59. extern CBlockIndex* pindexGenesisBlock;
  60. extern int nBestHeight;
  61. extern uint256 nBestChainWork;
  62. extern uint256 nBestInvalidWork;
  63. extern uint256 hashBestChain;
  64. extern CBlockIndex* pindexBest;
  65. extern unsigned int nTransactionsUpdated;
  66. extern uint64 nLastBlockTx;
  67. extern uint64 nLastBlockSize;
  68. extern const std::string strMessageMagic;
  69. extern double dHashesPerSec;
  70. extern int64 nHPSTimerStart;
  71. extern int64 nTimeBestReceived;
  72. extern CCriticalSection cs_setpwalletRegistered;
  73. extern std::set<CWallet*> setpwalletRegistered;
  74. extern bool fImporting;
  75. extern bool fReindex;
  76. extern bool fBenchmark;
  77. extern int nScriptCheckThreads;
  78. extern bool fTxIndex;
  79. extern unsigned int nCoinCacheSize;
  80. extern bool fHaveGUI;
  81. // Settings
  82. extern int64 nTransactionFee;
  83. // Minimum disk space required - used in CheckDiskSpace()
  84. static const uint64 nMinDiskSpace = 52428800;
  85. class CReserveKey;
  86. class CCoinsDB;
  87. class CBlockTreeDB;
  88. struct CDiskBlockPos;
  89. class CCoins;
  90. class CTxUndo;
  91. class CCoinsView;
  92. class CCoinsViewCache;
  93. class CScriptCheck;
  94. class CValidationState;
  95. struct CBlockTemplate;
  96. /** Register a wallet to receive updates from core */
  97. void RegisterWallet(CWallet* pwalletIn);
  98. /** Unregister a wallet from core */
  99. void UnregisterWallet(CWallet* pwalletIn);
  100. /** Push an updated transaction to all registered wallets */
  101. void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
  102. /** Register with a network node to receive its signals */
  103. void RegisterNodeSignals(CNodeSignals& nodeSignals);
  104. /** Unregister a network node */
  105. void UnregisterNodeSignals(CNodeSignals& nodeSignals);
  106. void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
  107. /** Process an incoming block */
  108. bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
  109. /** Check whether enough disk space is available for an incoming block */
  110. bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
  111. /** Open a block file (blk?????.dat) */
  112. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  113. /** Open an undo file (rev?????.dat) */
  114. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  115. /** Import blocks from an external file */
  116. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
  117. /** Initialize a new block tree database + block data on disk */
  118. bool InitBlockIndex();
  119. /** Load the block tree and coins database from disk */
  120. bool LoadBlockIndex();
  121. /** Unload database information */
  122. void UnloadBlockIndex();
  123. /** Verify consistency of the block and coin databases */
  124. bool VerifyDB();
  125. /** Print the loaded block tree */
  126. void PrintBlockTree();
  127. /** Find a block by height in the currently-connected chain */
  128. CBlockIndex* FindBlockByHeight(int nHeight);
  129. /** Process protocol messages received from a given node */
  130. bool ProcessMessages(CNode* pfrom);
  131. /** Send queued protocol messages to be sent to a give node */
  132. bool SendMessages(CNode* pto, bool fSendTrickle);
  133. /** Run an instance of the script checking thread */
  134. void ThreadScriptCheck();
  135. /** Run the miner threads */
  136. void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
  137. /** Generate a new block, without valid proof-of-work */
  138. CBlockTemplate* CreateNewBlock(CReserveKey& reservekey);
  139. /** Modify the extranonce in a block */
  140. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
  141. /** Do mining precalculation */
  142. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
  143. /** Check mined block */
  144. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
  145. /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
  146. bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  147. /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
  148. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
  149. /** Get the number of active peers */
  150. int GetNumBlocksOfPeers();
  151. /** Check whether we are doing an initial block download (synchronizing from disk or network) */
  152. bool IsInitialBlockDownload();
  153. /** Format a string that describes several potential problems detected by the core */
  154. std::string GetWarnings(std::string strFor);
  155. /** Retrieve a transaction (from memory pool, or from disk, if possible) */
  156. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
  157. /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
  158. bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
  159. /** Find the best known block, and make it the tip of the block chain */
  160. bool ConnectBestBlock(CValidationState &state);
  161. void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev);
  162. /** Create a new block index entry for a given block hash */
  163. CBlockIndex * InsertBlockIndex(uint256 hash);
  164. /** Verify a signature */
  165. bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
  166. /** Abort with a message */
  167. bool AbortNode(const std::string &msg);
  168. bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
  169. struct CDiskBlockPos
  170. {
  171. int nFile;
  172. unsigned int nPos;
  173. IMPLEMENT_SERIALIZE(
  174. READWRITE(VARINT(nFile));
  175. READWRITE(VARINT(nPos));
  176. )
  177. CDiskBlockPos() {
  178. SetNull();
  179. }
  180. CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
  181. nFile = nFileIn;
  182. nPos = nPosIn;
  183. }
  184. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  185. return (a.nFile == b.nFile && a.nPos == b.nPos);
  186. }
  187. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  188. return !(a == b);
  189. }
  190. void SetNull() { nFile = -1; nPos = 0; }
  191. bool IsNull() const { return (nFile == -1); }
  192. };
  193. struct CDiskTxPos : public CDiskBlockPos
  194. {
  195. unsigned int nTxOffset; // after header
  196. IMPLEMENT_SERIALIZE(
  197. READWRITE(*(CDiskBlockPos*)this);
  198. READWRITE(VARINT(nTxOffset));
  199. )
  200. CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
  201. }
  202. CDiskTxPos() {
  203. SetNull();
  204. }
  205. void SetNull() {
  206. CDiskBlockPos::SetNull();
  207. nTxOffset = 0;
  208. }
  209. };
  210. enum GetMinFee_mode
  211. {
  212. GMF_BLOCK,
  213. GMF_RELAY,
  214. GMF_SEND,
  215. };
  216. int64 GetMinFee(const CTransaction& tx, unsigned int nBlockSize = 1, bool fAllowFree = true, enum GetMinFee_mode mode = GMF_BLOCK);
  217. //
  218. // Check transaction inputs, and make sure any
  219. // pay-to-script-hash transactions are evaluating IsStandard scripts
  220. //
  221. // Why bother? To avoid denial-of-service attacks; an attacker
  222. // can submit a standard HASH... OP_EQUAL transaction,
  223. // which will get accepted into blocks. The redemption
  224. // script can be anything; an attacker could use a very
  225. // expensive-to-check-upon-redemption script like:
  226. // DUP CHECKSIG DROP ... repeated 100 times... OP_1
  227. //
  228. /** Check for standard transaction types
  229. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  230. @return True if all inputs (scriptSigs) use only standard transaction forms
  231. */
  232. bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs);
  233. /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
  234. @return number of sigops this transaction's outputs will produce when spent
  235. @see CTransaction::FetchInputs
  236. */
  237. unsigned int GetLegacySigOpCount(const CTransaction& tx);
  238. /** Count ECDSA signature operations in pay-to-script-hash inputs.
  239. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  240. @return maximum number of sigops required to validate this transaction's inputs
  241. @see CTransaction::FetchInputs
  242. */
  243. unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& mapInputs);
  244. inline bool AllowFree(double dPriority)
  245. {
  246. // Large (in bytes) low-priority (new, small-coin) transactions
  247. // need a fee.
  248. return dPriority > COIN * 144 / 250;
  249. }
  250. // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
  251. // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
  252. // instead of being performed inline.
  253. bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
  254. unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
  255. std::vector<CScriptCheck> *pvChecks = NULL);
  256. // Apply the effects of this transaction on the UTXO set represented by view
  257. bool UpdateCoins(const CTransaction& tx, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash);
  258. // Context-independent validity checks
  259. bool CheckTransaction(const CTransaction& tx, CValidationState& state);
  260. /** Check for standard transaction types
  261. @return True if all outputs (scriptPubKeys) use only standard transaction forms
  262. */
  263. bool IsStandardTx(const CTransaction& tx);
  264. bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64 nBlockTime = 0);
  265. /** Amount of bitcoins spent by the transaction.
  266. @return sum of all outputs (note: does not include fees)
  267. */
  268. int64 GetValueOut(const CTransaction& tx);
  269. /** Undo information for a CBlock */
  270. class CBlockUndo
  271. {
  272. public:
  273. std::vector<CTxUndo> vtxundo; // for all but the coinbase
  274. IMPLEMENT_SERIALIZE(
  275. READWRITE(vtxundo);
  276. )
  277. bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
  278. {
  279. // Open history file to append
  280. CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
  281. if (!fileout)
  282. return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
  283. // Write index header
  284. unsigned int nSize = fileout.GetSerializeSize(*this);
  285. fileout << FLATDATA(Params().MessageStart()) << nSize;
  286. // Write undo data
  287. long fileOutPos = ftell(fileout);
  288. if (fileOutPos < 0)
  289. return error("CBlockUndo::WriteToDisk() : ftell failed");
  290. pos.nPos = (unsigned int)fileOutPos;
  291. fileout << *this;
  292. // calculate & write checksum
  293. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  294. hasher << hashBlock;
  295. hasher << *this;
  296. fileout << hasher.GetHash();
  297. // Flush stdio buffers and commit to disk before returning
  298. fflush(fileout);
  299. if (!IsInitialBlockDownload())
  300. FileCommit(fileout);
  301. return true;
  302. }
  303. bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
  304. {
  305. // Open history file to read
  306. CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
  307. if (!filein)
  308. return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
  309. // Read block
  310. uint256 hashChecksum;
  311. try {
  312. filein >> *this;
  313. filein >> hashChecksum;
  314. }
  315. catch (std::exception &e) {
  316. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  317. }
  318. // Verify checksum
  319. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  320. hasher << hashBlock;
  321. hasher << *this;
  322. if (hashChecksum != hasher.GetHash())
  323. return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
  324. return true;
  325. }
  326. };
  327. /** Closure representing one script verification
  328. * Note that this stores references to the spending transaction */
  329. class CScriptCheck
  330. {
  331. private:
  332. CScript scriptPubKey;
  333. const CTransaction *ptxTo;
  334. unsigned int nIn;
  335. unsigned int nFlags;
  336. int nHashType;
  337. public:
  338. CScriptCheck() {}
  339. CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
  340. scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
  341. ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
  342. bool operator()() const;
  343. void swap(CScriptCheck &check) {
  344. scriptPubKey.swap(check.scriptPubKey);
  345. std::swap(ptxTo, check.ptxTo);
  346. std::swap(nIn, check.nIn);
  347. std::swap(nFlags, check.nFlags);
  348. std::swap(nHashType, check.nHashType);
  349. }
  350. };
  351. /** A transaction with a merkle branch linking it to the block chain. */
  352. class CMerkleTx : public CTransaction
  353. {
  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. int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
  384. int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  385. bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
  386. int GetBlocksToMaturity() const;
  387. bool AcceptToMemoryPool(bool fLimitFree=true);
  388. };
  389. /** Data structure that represents a partial merkle tree.
  390. *
  391. * It respresents a subset of the txid's of a known block, in a way that
  392. * allows recovery of the list of txid's and the merkle root, in an
  393. * authenticated way.
  394. *
  395. * The encoding works as follows: we traverse the tree in depth-first order,
  396. * storing a bit for each traversed node, signifying whether the node is the
  397. * parent of at least one matched leaf txid (or a matched txid itself). In
  398. * case we are at the leaf level, or this bit is 0, its merkle node hash is
  399. * stored, and its children are not explorer further. Otherwise, no hash is
  400. * stored, but we recurse into both (or the only) child branch. During
  401. * decoding, the same depth-first traversal is performed, consuming bits and
  402. * hashes as they written during encoding.
  403. *
  404. * The serialization is fixed and provides a hard guarantee about the
  405. * encoded size:
  406. *
  407. * SIZE <= 10 + ceil(32.25*N)
  408. *
  409. * Where N represents the number of leaf nodes of the partial tree. N itself
  410. * is bounded by:
  411. *
  412. * N <= total_transactions
  413. * N <= 1 + matched_transactions*tree_height
  414. *
  415. * The serialization format:
  416. * - uint32 total_transactions (4 bytes)
  417. * - varint number of hashes (1-3 bytes)
  418. * - uint256[] hashes in depth-first order (<= 32*N bytes)
  419. * - varint number of bytes of flag bits (1-3 bytes)
  420. * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
  421. * The size constraints follow from this.
  422. */
  423. class CPartialMerkleTree
  424. {
  425. protected:
  426. // the total number of transactions in the block
  427. unsigned int nTransactions;
  428. // node-is-parent-of-matched-txid bits
  429. std::vector<bool> vBits;
  430. // txids and internal hashes
  431. std::vector<uint256> vHash;
  432. // flag set when encountering invalid data
  433. bool fBad;
  434. // helper function to efficiently calculate the number of nodes at given height in the merkle tree
  435. unsigned int CalcTreeWidth(int height) {
  436. return (nTransactions+(1 << height)-1) >> height;
  437. }
  438. // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
  439. uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
  440. // recursive function that traverses tree nodes, storing the data as bits and hashes
  441. void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  442. // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
  443. // it returns the hash of the respective node.
  444. uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
  445. public:
  446. // serialization implementation
  447. IMPLEMENT_SERIALIZE(
  448. READWRITE(nTransactions);
  449. READWRITE(vHash);
  450. std::vector<unsigned char> vBytes;
  451. if (fRead) {
  452. READWRITE(vBytes);
  453. CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
  454. us.vBits.resize(vBytes.size() * 8);
  455. for (unsigned int p = 0; p < us.vBits.size(); p++)
  456. us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
  457. us.fBad = false;
  458. } else {
  459. vBytes.resize((vBits.size()+7)/8);
  460. for (unsigned int p = 0; p < vBits.size(); p++)
  461. vBytes[p / 8] |= vBits[p] << (p % 8);
  462. READWRITE(vBytes);
  463. }
  464. )
  465. // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
  466. CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
  467. CPartialMerkleTree();
  468. // extract the matching txid's represented by this partial merkle tree.
  469. // returns the merkle root, or 0 in case of failure
  470. uint256 ExtractMatches(std::vector<uint256> &vMatch);
  471. };
  472. class CBlock : public CBlockHeader
  473. {
  474. public:
  475. // network and disk
  476. std::vector<CTransaction> vtx;
  477. // memory only
  478. mutable std::vector<uint256> vMerkleTree;
  479. CBlock()
  480. {
  481. SetNull();
  482. }
  483. CBlock(const CBlockHeader &header)
  484. {
  485. SetNull();
  486. *((CBlockHeader*)this) = header;
  487. }
  488. IMPLEMENT_SERIALIZE
  489. (
  490. READWRITE(*(CBlockHeader*)this);
  491. READWRITE(vtx);
  492. )
  493. void SetNull()
  494. {
  495. CBlockHeader::SetNull();
  496. vtx.clear();
  497. vMerkleTree.clear();
  498. }
  499. CBlockHeader GetBlockHeader() const
  500. {
  501. CBlockHeader block;
  502. block.nVersion = nVersion;
  503. block.hashPrevBlock = hashPrevBlock;
  504. block.hashMerkleRoot = hashMerkleRoot;
  505. block.nTime = nTime;
  506. block.nBits = nBits;
  507. block.nNonce = nNonce;
  508. return block;
  509. }
  510. uint256 BuildMerkleTree() const
  511. {
  512. vMerkleTree.clear();
  513. BOOST_FOREACH(const CTransaction& tx, vtx)
  514. vMerkleTree.push_back(tx.GetHash());
  515. int j = 0;
  516. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  517. {
  518. for (int i = 0; i < nSize; i += 2)
  519. {
  520. int i2 = std::min(i+1, nSize-1);
  521. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  522. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  523. }
  524. j += nSize;
  525. }
  526. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  527. }
  528. const uint256 &GetTxHash(unsigned int nIndex) const {
  529. assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
  530. assert(nIndex < vtx.size());
  531. return vMerkleTree[nIndex];
  532. }
  533. std::vector<uint256> GetMerkleBranch(int nIndex) const
  534. {
  535. if (vMerkleTree.empty())
  536. BuildMerkleTree();
  537. std::vector<uint256> vMerkleBranch;
  538. int j = 0;
  539. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  540. {
  541. int i = std::min(nIndex^1, nSize-1);
  542. vMerkleBranch.push_back(vMerkleTree[j+i]);
  543. nIndex >>= 1;
  544. j += nSize;
  545. }
  546. return vMerkleBranch;
  547. }
  548. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  549. {
  550. if (nIndex == -1)
  551. return 0;
  552. BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
  553. {
  554. if (nIndex & 1)
  555. hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
  556. else
  557. hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
  558. nIndex >>= 1;
  559. }
  560. return hash;
  561. }
  562. bool WriteToDisk(CDiskBlockPos &pos)
  563. {
  564. // Open history file to append
  565. CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
  566. if (!fileout)
  567. return error("CBlock::WriteToDisk() : OpenBlockFile failed");
  568. // Write index header
  569. unsigned int nSize = fileout.GetSerializeSize(*this);
  570. fileout << FLATDATA(Params().MessageStart()) << nSize;
  571. // Write block
  572. long fileOutPos = ftell(fileout);
  573. if (fileOutPos < 0)
  574. return error("CBlock::WriteToDisk() : ftell failed");
  575. pos.nPos = (unsigned int)fileOutPos;
  576. fileout << *this;
  577. // Flush stdio buffers and commit to disk before returning
  578. fflush(fileout);
  579. if (!IsInitialBlockDownload())
  580. FileCommit(fileout);
  581. return true;
  582. }
  583. bool ReadFromDisk(const CDiskBlockPos &pos)
  584. {
  585. SetNull();
  586. // Open history file to read
  587. CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
  588. if (!filein)
  589. return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
  590. // Read block
  591. try {
  592. filein >> *this;
  593. }
  594. catch (std::exception &e) {
  595. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  596. }
  597. // Check the header
  598. if (!CheckProofOfWork(GetHash(), nBits))
  599. return error("CBlock::ReadFromDisk() : errors in block header");
  600. return true;
  601. }
  602. void print() const
  603. {
  604. printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
  605. GetHash().ToString().c_str(),
  606. nVersion,
  607. hashPrevBlock.ToString().c_str(),
  608. hashMerkleRoot.ToString().c_str(),
  609. nTime, nBits, nNonce,
  610. vtx.size());
  611. for (unsigned int i = 0; i < vtx.size(); i++)
  612. {
  613. printf(" ");
  614. vtx[i].print();
  615. }
  616. printf(" vMerkleTree: ");
  617. for (unsigned int i = 0; i < vMerkleTree.size(); i++)
  618. printf("%s ", vMerkleTree[i].ToString().c_str());
  619. printf("\n");
  620. }
  621. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
  622. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
  623. * will be true if no problems were found. Otherwise, the return value will be false in case
  624. * of problems. Note that in any case, coins may be modified. */
  625. bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
  626. // Apply the effects of this block (with given index) on the UTXO set represented by coins
  627. bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
  628. // Read a block from disk
  629. bool ReadFromDisk(const CBlockIndex* pindex);
  630. // Add this block to the block index, and if necessary, switch the active block chain to this
  631. bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
  632. // Context-independent validity checks
  633. bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
  634. // Store block on disk
  635. // if dbp is provided, the file is known to already reside on disk
  636. bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
  637. };
  638. class CBlockFileInfo
  639. {
  640. public:
  641. unsigned int nBlocks; // number of blocks stored in file
  642. unsigned int nSize; // number of used bytes of block file
  643. unsigned int nUndoSize; // number of used bytes in the undo file
  644. unsigned int nHeightFirst; // lowest height of block in file
  645. unsigned int nHeightLast; // highest height of block in file
  646. uint64 nTimeFirst; // earliest time of block in file
  647. uint64 nTimeLast; // latest time of block in file
  648. IMPLEMENT_SERIALIZE(
  649. READWRITE(VARINT(nBlocks));
  650. READWRITE(VARINT(nSize));
  651. READWRITE(VARINT(nUndoSize));
  652. READWRITE(VARINT(nHeightFirst));
  653. READWRITE(VARINT(nHeightLast));
  654. READWRITE(VARINT(nTimeFirst));
  655. READWRITE(VARINT(nTimeLast));
  656. )
  657. void SetNull() {
  658. nBlocks = 0;
  659. nSize = 0;
  660. nUndoSize = 0;
  661. nHeightFirst = 0;
  662. nHeightLast = 0;
  663. nTimeFirst = 0;
  664. nTimeLast = 0;
  665. }
  666. CBlockFileInfo() {
  667. SetNull();
  668. }
  669. std::string ToString() const {
  670. 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());
  671. }
  672. // update statistics (does not update nSize)
  673. void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
  674. if (nBlocks==0 || nHeightFirst > nHeightIn)
  675. nHeightFirst = nHeightIn;
  676. if (nBlocks==0 || nTimeFirst > nTimeIn)
  677. nTimeFirst = nTimeIn;
  678. nBlocks++;
  679. if (nHeightIn > nHeightFirst)
  680. nHeightLast = nHeightIn;
  681. if (nTimeIn > nTimeLast)
  682. nTimeLast = nTimeIn;
  683. }
  684. };
  685. extern CCriticalSection cs_LastBlockFile;
  686. extern CBlockFileInfo infoLastBlockFile;
  687. extern int nLastBlockFile;
  688. enum BlockStatus {
  689. BLOCK_VALID_UNKNOWN = 0,
  690. BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
  691. BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
  692. BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
  693. BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
  694. BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
  695. BLOCK_VALID_MASK = 7,
  696. BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
  697. BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
  698. BLOCK_HAVE_MASK = 24,
  699. BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
  700. BLOCK_FAILED_CHILD = 64, // descends from failed block
  701. BLOCK_FAILED_MASK = 96
  702. };
  703. /** The block chain is a tree shaped structure starting with the
  704. * genesis block at the root, with each block potentially having multiple
  705. * candidates to be the next block. A blockindex may have multiple pprev pointing
  706. * to it, but at most one of them can be part of the currently active branch.
  707. */
  708. class CBlockIndex
  709. {
  710. public:
  711. // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
  712. const uint256* phashBlock;
  713. // pointer to the index of the predecessor of this block
  714. CBlockIndex* pprev;
  715. // height of the entry in the chain. The genesis block has height 0
  716. int nHeight;
  717. // Which # file this block is stored in (blk?????.dat)
  718. int nFile;
  719. // Byte offset within blk?????.dat where this block's data is stored
  720. unsigned int nDataPos;
  721. // Byte offset within rev?????.dat where this block's undo data is stored
  722. unsigned int nUndoPos;
  723. // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  724. uint256 nChainWork;
  725. // Number of transactions in this block.
  726. // Note: in a potential headers-first mode, this number cannot be relied upon
  727. unsigned int nTx;
  728. // (memory only) Number of transactions in the chain up to and including this block
  729. unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
  730. // Verification status of this block. See enum BlockStatus
  731. unsigned int nStatus;
  732. // block header
  733. int nVersion;
  734. uint256 hashMerkleRoot;
  735. unsigned int nTime;
  736. unsigned int nBits;
  737. unsigned int nNonce;
  738. CBlockIndex()
  739. {
  740. phashBlock = NULL;
  741. pprev = NULL;
  742. nHeight = 0;
  743. nFile = 0;
  744. nDataPos = 0;
  745. nUndoPos = 0;
  746. nChainWork = 0;
  747. nTx = 0;
  748. nChainTx = 0;
  749. nStatus = 0;
  750. nVersion = 0;
  751. hashMerkleRoot = 0;
  752. nTime = 0;
  753. nBits = 0;
  754. nNonce = 0;
  755. }
  756. CBlockIndex(CBlockHeader& block)
  757. {
  758. phashBlock = NULL;
  759. pprev = NULL;
  760. nHeight = 0;
  761. nFile = 0;
  762. nDataPos = 0;
  763. nUndoPos = 0;
  764. nChainWork = 0;
  765. nTx = 0;
  766. nChainTx = 0;
  767. nStatus = 0;
  768. nVersion = block.nVersion;
  769. hashMerkleRoot = block.hashMerkleRoot;
  770. nTime = block.nTime;
  771. nBits = block.nBits;
  772. nNonce = block.nNonce;
  773. }
  774. CDiskBlockPos GetBlockPos() const {
  775. CDiskBlockPos ret;
  776. if (nStatus & BLOCK_HAVE_DATA) {
  777. ret.nFile = nFile;
  778. ret.nPos = nDataPos;
  779. }
  780. return ret;
  781. }
  782. CDiskBlockPos GetUndoPos() const {
  783. CDiskBlockPos ret;
  784. if (nStatus & BLOCK_HAVE_UNDO) {
  785. ret.nFile = nFile;
  786. ret.nPos = nUndoPos;
  787. }
  788. return ret;
  789. }
  790. CBlockHeader GetBlockHeader() const
  791. {
  792. CBlockHeader block;
  793. block.nVersion = nVersion;
  794. if (pprev)
  795. block.hashPrevBlock = pprev->GetBlockHash();
  796. block.hashMerkleRoot = hashMerkleRoot;
  797. block.nTime = nTime;
  798. block.nBits = nBits;
  799. block.nNonce = nNonce;
  800. return block;
  801. }
  802. uint256 GetBlockHash() const
  803. {
  804. return *phashBlock;
  805. }
  806. int64 GetBlockTime() const
  807. {
  808. return (int64)nTime;
  809. }
  810. CBigNum GetBlockWork() const
  811. {
  812. CBigNum bnTarget;
  813. bnTarget.SetCompact(nBits);
  814. if (bnTarget <= 0)
  815. return 0;
  816. return (CBigNum(1)<<256) / (bnTarget+1);
  817. }
  818. bool IsInMainChain() const
  819. {
  820. return nHeight < (int)vBlockIndexByHeight.size() && vBlockIndexByHeight[nHeight] == this;
  821. }
  822. CBlockIndex *GetNextInMainChain() const {
  823. return nHeight+1 >= (int)vBlockIndexByHeight.size() ? NULL : vBlockIndexByHeight[nHeight+1];
  824. }
  825. bool CheckIndex() const
  826. {
  827. return CheckProofOfWork(GetBlockHash(), nBits);
  828. }
  829. enum { nMedianTimeSpan=11 };
  830. int64 GetMedianTimePast() const
  831. {
  832. int64 pmedian[nMedianTimeSpan];
  833. int64* pbegin = &pmedian[nMedianTimeSpan];
  834. int64* pend = &pmedian[nMedianTimeSpan];
  835. const CBlockIndex* pindex = this;
  836. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  837. *(--pbegin) = pindex->GetBlockTime();
  838. std::sort(pbegin, pend);
  839. return pbegin[(pend - pbegin)/2];
  840. }
  841. int64 GetMedianTime() const
  842. {
  843. const CBlockIndex* pindex = this;
  844. for (int i = 0; i < nMedianTimeSpan/2; i++)
  845. {
  846. if (!pindex->GetNextInMainChain())
  847. return GetBlockTime();
  848. pindex = pindex->GetNextInMainChain();
  849. }
  850. return pindex->GetMedianTimePast();
  851. }
  852. /**
  853. * Returns true if there are nRequired or more blocks of minVersion or above
  854. * in the last nToCheck blocks, starting at pstart and going backwards.
  855. */
  856. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  857. unsigned int nRequired, unsigned int nToCheck);
  858. std::string ToString() const
  859. {
  860. return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  861. pprev, GetNextInMainChain(), nHeight,
  862. hashMerkleRoot.ToString().c_str(),
  863. GetBlockHash().ToString().c_str());
  864. }
  865. void print() const
  866. {
  867. printf("%s\n", ToString().c_str());
  868. }
  869. };
  870. struct CBlockIndexWorkComparator
  871. {
  872. bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
  873. if (pa->nChainWork > pb->nChainWork) return false;
  874. if (pa->nChainWork < pb->nChainWork) return true;
  875. if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
  876. if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
  877. return false; // identical blocks
  878. }
  879. };
  880. /** Used to marshal pointers into hashes for db storage. */
  881. class CDiskBlockIndex : public CBlockIndex
  882. {
  883. public:
  884. uint256 hashPrev;
  885. CDiskBlockIndex() {
  886. hashPrev = 0;
  887. }
  888. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
  889. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  890. }
  891. IMPLEMENT_SERIALIZE
  892. (
  893. if (!(nType & SER_GETHASH))
  894. READWRITE(VARINT(nVersion));
  895. READWRITE(VARINT(nHeight));
  896. READWRITE(VARINT(nStatus));
  897. READWRITE(VARINT(nTx));
  898. if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
  899. READWRITE(VARINT(nFile));
  900. if (nStatus & BLOCK_HAVE_DATA)
  901. READWRITE(VARINT(nDataPos));
  902. if (nStatus & BLOCK_HAVE_UNDO)
  903. READWRITE(VARINT(nUndoPos));
  904. // block header
  905. READWRITE(this->nVersion);
  906. READWRITE(hashPrev);
  907. READWRITE(hashMerkleRoot);
  908. READWRITE(nTime);
  909. READWRITE(nBits);
  910. READWRITE(nNonce);
  911. )
  912. uint256 GetBlockHash() const
  913. {
  914. CBlockHeader block;
  915. block.nVersion = nVersion;
  916. block.hashPrevBlock = hashPrev;
  917. block.hashMerkleRoot = hashMerkleRoot;
  918. block.nTime = nTime;
  919. block.nBits = nBits;
  920. block.nNonce = nNonce;
  921. return block.GetHash();
  922. }
  923. std::string ToString() const
  924. {
  925. std::string str = "CDiskBlockIndex(";
  926. str += CBlockIndex::ToString();
  927. str += strprintf("\n hashBlock=%s, hashPrev=%s)",
  928. GetBlockHash().ToString().c_str(),
  929. hashPrev.ToString().c_str());
  930. return str;
  931. }
  932. void print() const
  933. {
  934. printf("%s\n", ToString().c_str());
  935. }
  936. };
  937. /** Capture information about block/transaction validation */
  938. class CValidationState {
  939. private:
  940. enum mode_state {
  941. MODE_VALID, // everything ok
  942. MODE_INVALID, // network rule violation (DoS value may be set)
  943. MODE_ERROR, // run-time error
  944. } mode;
  945. int nDoS;
  946. public:
  947. CValidationState() : mode(MODE_VALID), nDoS(0) {}
  948. bool DoS(int level, bool ret = false) {
  949. if (mode == MODE_ERROR)
  950. return ret;
  951. nDoS += level;
  952. mode = MODE_INVALID;
  953. return ret;
  954. }
  955. bool Invalid(bool ret = false) {
  956. return DoS(0, ret);
  957. }
  958. bool Error() {
  959. mode = MODE_ERROR;
  960. return false;
  961. }
  962. bool Abort(const std::string &msg) {
  963. AbortNode(msg);
  964. return Error();
  965. }
  966. bool IsValid() {
  967. return mode == MODE_VALID;
  968. }
  969. bool IsInvalid() {
  970. return mode == MODE_INVALID;
  971. }
  972. bool IsError() {
  973. return mode == MODE_ERROR;
  974. }
  975. bool IsInvalid(int &nDoSOut) {
  976. if (IsInvalid()) {
  977. nDoSOut = nDoS;
  978. return true;
  979. }
  980. return false;
  981. }
  982. };
  983. /** Describes a place in the block chain to another node such that if the
  984. * other node doesn't have the same branch, it can find a recent common trunk.
  985. * The further back it is, the further before the fork it may be.
  986. */
  987. class CBlockLocator
  988. {
  989. protected:
  990. std::vector<uint256> vHave;
  991. public:
  992. CBlockLocator() {}
  993. explicit CBlockLocator(const CBlockIndex* pindex)
  994. {
  995. Set(pindex);
  996. }
  997. explicit CBlockLocator(uint256 hashBlock);
  998. CBlockLocator(const std::vector<uint256>& vHaveIn)
  999. {
  1000. vHave = vHaveIn;
  1001. }
  1002. IMPLEMENT_SERIALIZE
  1003. (
  1004. if (!(nType & SER_GETHASH))
  1005. READWRITE(nVersion);
  1006. READWRITE(vHave);
  1007. )
  1008. void SetNull()
  1009. {
  1010. vHave.clear();
  1011. }
  1012. bool IsNull()
  1013. {
  1014. return vHave.empty();
  1015. }
  1016. /** Given a block initialises the locator to that point in the chain. */
  1017. void Set(const CBlockIndex* pindex);
  1018. /** Returns the distance in blocks this locator is from our chain head. */
  1019. int GetDistanceBack();
  1020. /** Returns the first best-chain block the locator contains. */
  1021. CBlockIndex* GetBlockIndex();
  1022. /** Returns the hash of the first best chain block the locator contains. */
  1023. uint256 GetBlockHash();
  1024. /** Returns the height of the first best chain block the locator has. */
  1025. int GetHeight();
  1026. };
  1027. class CTxMemPool
  1028. {
  1029. public:
  1030. mutable CCriticalSection cs;
  1031. std::map<uint256, CTransaction> mapTx;
  1032. std::map<COutPoint, CInPoint> mapNextTx;
  1033. bool accept(CValidationState &state, CTransaction &tx, bool fLimitFree, bool* pfMissingInputs);
  1034. bool addUnchecked(const uint256& hash, CTransaction &tx);
  1035. bool remove(const CTransaction &tx, bool fRecursive = false);
  1036. bool removeConflicts(const CTransaction &tx);
  1037. void clear();
  1038. void queryHashes(std::vector<uint256>& vtxid);
  1039. void pruneSpent(const uint256& hash, CCoins &coins);
  1040. unsigned long size()
  1041. {
  1042. LOCK(cs);
  1043. return mapTx.size();
  1044. }
  1045. bool exists(uint256 hash)
  1046. {
  1047. return (mapTx.count(hash) != 0);
  1048. }
  1049. CTransaction& lookup(uint256 hash)
  1050. {
  1051. return mapTx[hash];
  1052. }
  1053. };
  1054. extern CTxMemPool mempool;
  1055. struct CCoinsStats
  1056. {
  1057. int nHeight;
  1058. uint256 hashBlock;
  1059. uint64 nTransactions;
  1060. uint64 nTransactionOutputs;
  1061. uint64 nSerializedSize;
  1062. uint256 hashSerialized;
  1063. int64 nTotalAmount;
  1064. CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
  1065. };
  1066. /** Abstract view on the open txout dataset. */
  1067. class CCoinsView
  1068. {
  1069. public:
  1070. // Retrieve the CCoins (unspent transaction outputs) for a given txid
  1071. virtual bool GetCoins(const uint256 &txid, CCoins &coins);
  1072. // Modify the CCoins for a given txid
  1073. virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
  1074. // Just check whether we have data for a given txid.
  1075. // This may (but cannot always) return true for fully spent transactions
  1076. virtual bool HaveCoins(const uint256 &txid);
  1077. // Retrieve the block index whose state this CCoinsView currently represents
  1078. virtual CBlockIndex *GetBestBlock();
  1079. // Modify the currently active block index
  1080. virtual bool SetBestBlock(CBlockIndex *pindex);
  1081. // Do a bulk modification (multiple SetCoins + one SetBestBlock)
  1082. virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
  1083. // Calculate statistics about the unspent transaction output set
  1084. virtual bool GetStats(CCoinsStats &stats);
  1085. // As we use CCoinsViews polymorphically, have a virtual destructor
  1086. virtual ~CCoinsView() {}
  1087. };
  1088. /** CCoinsView backed by another CCoinsView */
  1089. class CCoinsViewBacked : public CCoinsView
  1090. {
  1091. protected:
  1092. CCoinsView *base;
  1093. public:
  1094. CCoinsViewBacked(CCoinsView &viewIn);
  1095. bool GetCoins(const uint256 &txid, CCoins &coins);
  1096. bool SetCoins(const uint256 &txid, const CCoins &coins);
  1097. bool HaveCoins(const uint256 &txid);
  1098. CBlockIndex *GetBestBlock();
  1099. bool SetBestBlock(CBlockIndex *pindex);
  1100. void SetBackend(CCoinsView &viewIn);
  1101. bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
  1102. bool GetStats(CCoinsStats &stats);
  1103. };
  1104. /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
  1105. class CCoinsViewCache : public CCoinsViewBacked
  1106. {
  1107. protected:
  1108. CBlockIndex *pindexTip;
  1109. std::map<uint256,CCoins> cacheCoins;
  1110. public:
  1111. CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
  1112. // Standard CCoinsView methods
  1113. bool GetCoins(const uint256 &txid, CCoins &coins);
  1114. bool SetCoins(const uint256 &txid, const CCoins &coins);
  1115. bool HaveCoins(const uint256 &txid);
  1116. CBlockIndex *GetBestBlock();
  1117. bool SetBestBlock(CBlockIndex *pindex);
  1118. bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
  1119. // Return a modifiable reference to a CCoins. Check HaveCoins first.
  1120. // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
  1121. // copying.
  1122. CCoins &GetCoins(const uint256 &txid);
  1123. // Push the modifications applied to this cache to its base.
  1124. // Failure to call this method before destruction will cause the changes to be forgotten.
  1125. bool Flush();
  1126. // Calculate the size of the cache (in number of transactions)
  1127. unsigned int GetCacheSize();
  1128. /** Amount of bitcoins coming in to a transaction
  1129. Note that lightweight clients may not know anything besides the hash of previous transactions,
  1130. so may not be able to calculate this.
  1131. @param[in] tx transaction for which we are checking input total
  1132. @return Sum of value of all inputs (scriptSigs)
  1133. @see CTransaction::FetchInputs
  1134. */
  1135. int64 GetValueIn(const CTransaction& tx);
  1136. // Check whether all prevouts of the transaction are present in the UTXO set represented by this view
  1137. bool HaveInputs(const CTransaction& tx);
  1138. const CTxOut &GetOutputFor(const CTxIn& input);
  1139. private:
  1140. std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
  1141. };
  1142. /** CCoinsView that brings transactions from a memorypool into view.
  1143. It does not check for spendings by memory pool transactions. */
  1144. class CCoinsViewMemPool : public CCoinsViewBacked
  1145. {
  1146. protected:
  1147. CTxMemPool &mempool;
  1148. public:
  1149. CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
  1150. bool GetCoins(const uint256 &txid, CCoins &coins);
  1151. bool HaveCoins(const uint256 &txid);
  1152. };
  1153. /** Global variable that points to the active CCoinsView (protected by cs_main) */
  1154. extern CCoinsViewCache *pcoinsTip;
  1155. /** Global variable that points to the active block tree (protected by cs_main) */
  1156. extern CBlockTreeDB *pblocktree;
  1157. struct CBlockTemplate
  1158. {
  1159. CBlock block;
  1160. std::vector<int64_t> vTxFees;
  1161. std::vector<int64_t> vTxSigOps;
  1162. };
  1163. /** Used to relay blocks as header + vector<merkle branch>
  1164. * to filtered nodes.
  1165. */
  1166. class CMerkleBlock
  1167. {
  1168. public:
  1169. // Public only for unit testing
  1170. CBlockHeader header;
  1171. CPartialMerkleTree txn;
  1172. public:
  1173. // Public only for unit testing and relay testing
  1174. // (not relayed)
  1175. std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
  1176. // Create from a CBlock, filtering transactions according to filter
  1177. // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
  1178. // thus the filter will likely be modified.
  1179. CMerkleBlock(const CBlock& block, CBloomFilter& filter);
  1180. IMPLEMENT_SERIALIZE
  1181. (
  1182. READWRITE(header);
  1183. READWRITE(txn);
  1184. )
  1185. };
  1186. #endif