Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 "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. // Unused.
  40. BLOCK_VALID_UNKNOWN = 0,
  41. // Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
  42. BLOCK_VALID_HEADER = 1,
  43. // All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
  44. // are also at least TREE.
  45. BLOCK_VALID_TREE = 2,
  46. // Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
  47. // sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
  48. // parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
  49. BLOCK_VALID_TRANSACTIONS = 3,
  50. // Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30.
  51. // Implies all parents are also at least CHAIN.
  52. BLOCK_VALID_CHAIN = 4,
  53. // Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
  54. BLOCK_VALID_SCRIPTS = 5,
  55. // All validity bits.
  56. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
  57. BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
  58. BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
  59. BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
  60. BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
  61. BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
  62. BLOCK_FAILED_CHILD = 64, // descends from failed block
  63. BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
  64. };
  65. /** The block chain is a tree shaped structure starting with the
  66. * genesis block at the root, with each block potentially having multiple
  67. * candidates to be the next block. A blockindex may have multiple pprev pointing
  68. * to it, but at most one of them can be part of the currently active branch.
  69. */
  70. class CBlockIndex
  71. {
  72. public:
  73. // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
  74. const uint256* phashBlock;
  75. // pointer to the index of the predecessor of this block
  76. CBlockIndex* pprev;
  77. // pointer to the index of some further predecessor of this block
  78. CBlockIndex* pskip;
  79. // height of the entry in the chain. The genesis block has height 0
  80. int nHeight;
  81. // Which # file this block is stored in (blk?????.dat)
  82. int nFile;
  83. // Byte offset within blk?????.dat where this block's data is stored
  84. unsigned int nDataPos;
  85. // Byte offset within rev?????.dat where this block's undo data is stored
  86. unsigned int nUndoPos;
  87. // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  88. uint256 nChainWork;
  89. // Number of transactions in this block.
  90. // Note: in a potential headers-first mode, this number cannot be relied upon
  91. unsigned int nTx;
  92. // (memory only) Number of transactions in the chain up to and including this block.
  93. // This value will be non-zero only if and only if transactions for this block and all its parents are available.
  94. unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
  95. // Verification status of this block. See enum BlockStatus
  96. unsigned int nStatus;
  97. // block header
  98. int nVersion;
  99. uint256 hashMerkleRoot;
  100. unsigned int nTime;
  101. unsigned int nBits;
  102. unsigned int nNonce;
  103. // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
  104. uint32_t nSequenceId;
  105. void SetNull()
  106. {
  107. phashBlock = NULL;
  108. pprev = NULL;
  109. pskip = NULL;
  110. nHeight = 0;
  111. nFile = 0;
  112. nDataPos = 0;
  113. nUndoPos = 0;
  114. nChainWork = 0;
  115. nTx = 0;
  116. nChainTx = 0;
  117. nStatus = 0;
  118. nSequenceId = 0;
  119. nVersion = 0;
  120. hashMerkleRoot = 0;
  121. nTime = 0;
  122. nBits = 0;
  123. nNonce = 0;
  124. }
  125. CBlockIndex()
  126. {
  127. SetNull();
  128. }
  129. CBlockIndex(const CBlockHeader& block)
  130. {
  131. SetNull();
  132. nVersion = block.nVersion;
  133. hashMerkleRoot = block.hashMerkleRoot;
  134. nTime = block.nTime;
  135. nBits = block.nBits;
  136. nNonce = block.nNonce;
  137. }
  138. CDiskBlockPos GetBlockPos() const {
  139. CDiskBlockPos ret;
  140. if (nStatus & BLOCK_HAVE_DATA) {
  141. ret.nFile = nFile;
  142. ret.nPos = nDataPos;
  143. }
  144. return ret;
  145. }
  146. CDiskBlockPos GetUndoPos() const {
  147. CDiskBlockPos ret;
  148. if (nStatus & BLOCK_HAVE_UNDO) {
  149. ret.nFile = nFile;
  150. ret.nPos = nUndoPos;
  151. }
  152. return ret;
  153. }
  154. CBlockHeader GetBlockHeader() const
  155. {
  156. CBlockHeader block;
  157. block.nVersion = nVersion;
  158. if (pprev)
  159. block.hashPrevBlock = pprev->GetBlockHash();
  160. block.hashMerkleRoot = hashMerkleRoot;
  161. block.nTime = nTime;
  162. block.nBits = nBits;
  163. block.nNonce = nNonce;
  164. return block;
  165. }
  166. uint256 GetBlockHash() const
  167. {
  168. return *phashBlock;
  169. }
  170. int64_t GetBlockTime() const
  171. {
  172. return (int64_t)nTime;
  173. }
  174. uint256 GetBlockWork() const
  175. {
  176. return GetProofIncrement(nBits);
  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. /**
  191. * Returns true if there are nRequired or more blocks of minVersion or above
  192. * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
  193. * and going backwards.
  194. */
  195. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  196. unsigned int nRequired);
  197. std::string ToString() const
  198. {
  199. return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  200. pprev, nHeight,
  201. hashMerkleRoot.ToString(),
  202. GetBlockHash().ToString());
  203. }
  204. // Check whether this block index entry is valid up to the passed validity level.
  205. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
  206. {
  207. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  208. if (nStatus & BLOCK_FAILED_MASK)
  209. return false;
  210. return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
  211. }
  212. // Raise the validity level of this block index entry.
  213. // Returns true if the validity was changed.
  214. bool RaiseValidity(enum BlockStatus nUpTo)
  215. {
  216. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  217. if (nStatus & BLOCK_FAILED_MASK)
  218. return false;
  219. if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
  220. nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
  221. return true;
  222. }
  223. return false;
  224. }
  225. // Build the skiplist pointer for this entry.
  226. void BuildSkip();
  227. // Efficiently find an ancestor of this block.
  228. CBlockIndex* GetAncestor(int height);
  229. const CBlockIndex* GetAncestor(int height) const;
  230. };
  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 = 0;
  238. }
  239. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
  240. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  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. Returns the forking point. */
  325. CBlockIndex *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 // H_BITCOIN_CHAIN