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

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