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

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