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.

chain.h 12KB

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