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

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