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.

преди 5 години
преди 6 години
преди 6 години
преди 6 години
преди 6 години
преди 6 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2015 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_CHAIN_H
  6. #define BITCOIN_CHAIN_H
  7. #include "arith_uint256.h"
  8. #include "primitives/block.h"
  9. #include "pow.h"
  10. #include "tinyformat.h"
  11. #include "uint256.h"
  12. #include <vector>
  13. struct CDiskBlockPos
  14. {
  15. int nFile;
  16. unsigned int nPos;
  17. ADD_SERIALIZE_METHODS;
  18. template <typename Stream, typename Operation>
  19. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  20. READWRITE(VARINT(nFile));
  21. READWRITE(VARINT(nPos));
  22. }
  23. CDiskBlockPos() {
  24. SetNull();
  25. }
  26. CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
  27. nFile = nFileIn;
  28. nPos = nPosIn;
  29. }
  30. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  31. return (a.nFile == b.nFile && a.nPos == b.nPos);
  32. }
  33. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  34. return !(a == b);
  35. }
  36. void SetNull() { nFile = -1; nPos = 0; }
  37. bool IsNull() const { return (nFile == -1); }
  38. std::string ToString() const
  39. {
  40. return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
  41. }
  42. };
  43. enum BlockStatus {
  44. //! Unused.
  45. BLOCK_VALID_UNKNOWN = 0,
  46. //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
  47. BLOCK_VALID_HEADER = 1,
  48. //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
  49. //! are also at least TREE.
  50. BLOCK_VALID_TREE = 2,
  51. /**
  52. * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
  53. * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
  54. * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
  55. */
  56. BLOCK_VALID_TRANSACTIONS = 3,
  57. //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
  58. //! Implies all parents are also at least CHAIN.
  59. BLOCK_VALID_CHAIN = 4,
  60. //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
  61. BLOCK_VALID_SCRIPTS = 5,
  62. //! All validity bits.
  63. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
  64. BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
  65. BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
  66. BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
  67. BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
  68. BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
  69. BLOCK_FAILED_CHILD = 64, //! descends from failed block
  70. BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
  71. };
  72. /** The block chain is a tree shaped structure starting with the
  73. * genesis block at the root, with each block potentially having multiple
  74. * candidates to be the next block. A blockindex may have multiple pprev pointing
  75. * to it, but at most one of them can be part of the currently active branch.
  76. */
  77. class CBlockIndex
  78. {
  79. public:
  80. //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
  81. const uint256* phashBlock;
  82. //! pointer to the index of the predecessor of this block
  83. CBlockIndex* pprev;
  84. //! pointer to the index of some further predecessor of this block
  85. CBlockIndex* pskip;
  86. //! height of the entry in the chain. The genesis block has height 0
  87. int nHeight;
  88. //! Which # file this block is stored in (blk?????.dat)
  89. int nFile;
  90. //! Byte offset within blk?????.dat where this block's data is stored
  91. unsigned int nDataPos;
  92. //! Byte offset within rev?????.dat where this block's undo data is stored
  93. unsigned int nUndoPos;
  94. //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  95. arith_uint256 nChainWork;
  96. //! Number of transactions in this block.
  97. //! Note: in a potential headers-first mode, this number cannot be relied upon
  98. unsigned int nTx;
  99. //! (memory only) Number of transactions in the chain up to and including this block.
  100. //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
  101. //! Change to 64-bit type when necessary; won't happen before 2030
  102. unsigned int nChainTx;
  103. //! Verification status of this block. See enum BlockStatus
  104. unsigned int nStatus;
  105. //! block header
  106. int nVersion;
  107. uint256 hashMerkleRoot;
  108. unsigned int nTime;
  109. unsigned int nBits;
  110. unsigned int nNonce;
  111. //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
  112. uint32_t nSequenceId;
  113. void SetNull()
  114. {
  115. phashBlock = NULL;
  116. pprev = NULL;
  117. pskip = NULL;
  118. nHeight = 0;
  119. nFile = 0;
  120. nDataPos = 0;
  121. nUndoPos = 0;
  122. nChainWork = arith_uint256();
  123. nTx = 0;
  124. nChainTx = 0;
  125. nStatus = 0;
  126. nSequenceId = 0;
  127. nVersion = 0;
  128. hashMerkleRoot = uint256();
  129. nTime = 0;
  130. nBits = 0;
  131. nNonce = 0;
  132. }
  133. CBlockIndex()
  134. {
  135. SetNull();
  136. }
  137. CBlockIndex(const CBlockHeader& block)
  138. {
  139. SetNull();
  140. nVersion = block.nVersion;
  141. hashMerkleRoot = block.hashMerkleRoot;
  142. nTime = block.nTime;
  143. nBits = block.nBits;
  144. nNonce = block.nNonce;
  145. }
  146. CDiskBlockPos GetBlockPos() const {
  147. CDiskBlockPos ret;
  148. if (nStatus & BLOCK_HAVE_DATA) {
  149. ret.nFile = nFile;
  150. ret.nPos = nDataPos;
  151. }
  152. return ret;
  153. }
  154. CDiskBlockPos GetUndoPos() const {
  155. CDiskBlockPos ret;
  156. if (nStatus & BLOCK_HAVE_UNDO) {
  157. ret.nFile = nFile;
  158. ret.nPos = nUndoPos;
  159. }
  160. return ret;
  161. }
  162. CBlockHeader GetBlockHeader() const
  163. {
  164. CBlockHeader block;
  165. block.nVersion = nVersion;
  166. if (pprev)
  167. block.hashPrevBlock = pprev->GetBlockHash();
  168. block.hashMerkleRoot = hashMerkleRoot;
  169. block.nTime = nTime;
  170. block.nBits = nBits;
  171. block.nNonce = nNonce;
  172. return block;
  173. }
  174. uint256 GetBlockHash() const
  175. {
  176. return *phashBlock;
  177. }
  178. int64_t GetBlockTime() const
  179. {
  180. return (int64_t)nTime;
  181. }
  182. enum { nMedianTimeSpan=11 };
  183. int64_t GetMedianTimePast() const
  184. {
  185. int64_t pmedian[nMedianTimeSpan];
  186. int64_t* pbegin = &pmedian[nMedianTimeSpan];
  187. int64_t* pend = &pmedian[nMedianTimeSpan];
  188. const CBlockIndex* pindex = this;
  189. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  190. *(--pbegin) = pindex->GetBlockTime();
  191. std::sort(pbegin, pend);
  192. return pbegin[(pend - pbegin)/2];
  193. }
  194. std::string ToString() const
  195. {
  196. return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  197. pprev, nHeight,
  198. hashMerkleRoot.ToString(),
  199. GetBlockHash().ToString());
  200. }
  201. //! Check whether this block index entry is valid up to the passed validity level.
  202. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
  203. {
  204. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  205. if (nStatus & BLOCK_FAILED_MASK)
  206. return false;
  207. return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
  208. }
  209. //! Raise the validity level of this block index entry.
  210. //! Returns true if the validity was changed.
  211. bool RaiseValidity(enum BlockStatus nUpTo)
  212. {
  213. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  214. if (nStatus & BLOCK_FAILED_MASK)
  215. return false;
  216. if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
  217. nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
  218. return true;
  219. }
  220. return false;
  221. }
  222. //! Build the skiplist pointer for this entry.
  223. void BuildSkip();
  224. //! Efficiently find an ancestor of this block.
  225. CBlockIndex* GetAncestor(int height);
  226. const CBlockIndex* GetAncestor(int height) const;
  227. };
  228. arith_uint256 GetBlockProof(const CBlockIndex& block);
  229. /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */
  230. int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
  231. /** Used to marshal pointers into hashes for db storage. */
  232. class CDiskBlockIndex : public CBlockIndex
  233. {
  234. public:
  235. uint256 hashPrev;
  236. CDiskBlockIndex() {
  237. hashPrev = uint256();
  238. }
  239. explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
  240. hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
  241. }
  242. ADD_SERIALIZE_METHODS;
  243. template <typename Stream, typename Operation>
  244. inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
  245. if (!(nType & SER_GETHASH))
  246. READWRITE(VARINT(nVersion));
  247. READWRITE(VARINT(nHeight));
  248. READWRITE(VARINT(nStatus));
  249. READWRITE(VARINT(nTx));
  250. if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
  251. READWRITE(VARINT(nFile));
  252. if (nStatus & BLOCK_HAVE_DATA)
  253. READWRITE(VARINT(nDataPos));
  254. if (nStatus & BLOCK_HAVE_UNDO)
  255. READWRITE(VARINT(nUndoPos));
  256. // block header
  257. READWRITE(this->nVersion);
  258. READWRITE(hashPrev);
  259. READWRITE(hashMerkleRoot);
  260. READWRITE(nTime);
  261. READWRITE(nBits);
  262. READWRITE(nNonce);
  263. }
  264. uint256 GetBlockHash() const
  265. {
  266. CBlockHeader block;
  267. block.nVersion = nVersion;
  268. block.hashPrevBlock = hashPrev;
  269. block.hashMerkleRoot = hashMerkleRoot;
  270. block.nTime = nTime;
  271. block.nBits = nBits;
  272. block.nNonce = nNonce;
  273. return block.GetHash();
  274. }
  275. std::string ToString() const
  276. {
  277. std::string str = "CDiskBlockIndex(";
  278. str += CBlockIndex::ToString();
  279. str += strprintf("\n hashBlock=%s, hashPrev=%s)",
  280. GetBlockHash().ToString(),
  281. hashPrev.ToString());
  282. return str;
  283. }
  284. };
  285. /** An in-memory indexed chain of blocks. */
  286. class CChain {
  287. private:
  288. std::vector<CBlockIndex*> vChain;
  289. public:
  290. /** Returns the index entry for the genesis block of this chain, or NULL if none. */
  291. CBlockIndex *Genesis() const {
  292. return vChain.size() > 0 ? vChain[0] : NULL;
  293. }
  294. /** Returns the index entry for the tip of this chain, or NULL if none. */
  295. CBlockIndex *Tip() const {
  296. return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
  297. }
  298. /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
  299. CBlockIndex *operator[](int nHeight) const {
  300. if (nHeight < 0 || nHeight >= (int)vChain.size())
  301. return NULL;
  302. return vChain[nHeight];
  303. }
  304. /** Compare two chains efficiently. */
  305. friend bool operator==(const CChain &a, const CChain &b) {
  306. return a.vChain.size() == b.vChain.size() &&
  307. a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
  308. }
  309. /** Efficiently check whether a block is present in this chain. */
  310. bool Contains(const CBlockIndex *pindex) const {
  311. return (*this)[pindex->nHeight] == pindex;
  312. }
  313. /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
  314. CBlockIndex *Next(const CBlockIndex *pindex) const {
  315. if (Contains(pindex))
  316. return (*this)[pindex->nHeight + 1];
  317. else
  318. return NULL;
  319. }
  320. /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
  321. int Height() const {
  322. return vChain.size() - 1;
  323. }
  324. /** Set/initialize a chain with a given tip. */
  325. void SetTip(CBlockIndex *pindex);
  326. /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
  327. CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
  328. /** Find the last common block between this chain and a block index entry. */
  329. const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
  330. };
  331. #endif // BITCOIN_CHAIN_H