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

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