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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels 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 STARWELS_CHAIN_H
  6. #define STARWELS_CHAIN_H
  7. #include "arith_uint256.h"
  8. #include "primitives/block.h"
  9. #include "pow.h"
  10. #include "tinyformat.h"
  11. #include "uint256.h"
  12. #include <vector>
  13. /**
  14. * Maximum amount of time that a block timestamp is allowed to exceed the
  15. * current network-adjusted time before the block will be accepted.
  16. */
  17. static const int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;
  18. /**
  19. * Timestamp window used as a grace period by code that compares external
  20. * timestamps (such as timestamps passed to RPCs, or wallet key creation times)
  21. * to block timestamps. This should be set at least as high as
  22. * MAX_FUTURE_BLOCK_TIME.
  23. */
  24. static const int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;
  25. class CBlockFileInfo
  26. {
  27. public:
  28. unsigned int nBlocks; //!< number of blocks stored in file
  29. unsigned int nSize; //!< number of used bytes of block file
  30. unsigned int nUndoSize; //!< number of used bytes in the undo file
  31. unsigned int nHeightFirst; //!< lowest height of block in file
  32. unsigned int nHeightLast; //!< highest height of block in file
  33. uint64_t nTimeFirst; //!< earliest time of block in file
  34. uint64_t nTimeLast; //!< latest time of block in file
  35. ADD_SERIALIZE_METHODS;
  36. template <typename Stream, typename Operation>
  37. inline void SerializationOp(Stream& s, Operation ser_action) {
  38. READWRITE(VARINT(nBlocks));
  39. READWRITE(VARINT(nSize));
  40. READWRITE(VARINT(nUndoSize));
  41. READWRITE(VARINT(nHeightFirst));
  42. READWRITE(VARINT(nHeightLast));
  43. READWRITE(VARINT(nTimeFirst));
  44. READWRITE(VARINT(nTimeLast));
  45. }
  46. void SetNull() {
  47. nBlocks = 0;
  48. nSize = 0;
  49. nUndoSize = 0;
  50. nHeightFirst = 0;
  51. nHeightLast = 0;
  52. nTimeFirst = 0;
  53. nTimeLast = 0;
  54. }
  55. CBlockFileInfo() {
  56. SetNull();
  57. }
  58. std::string ToString() const;
  59. /** update statistics (does not update nSize) */
  60. void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
  61. if (nBlocks==0 || nHeightFirst > nHeightIn)
  62. nHeightFirst = nHeightIn;
  63. if (nBlocks==0 || nTimeFirst > nTimeIn)
  64. nTimeFirst = nTimeIn;
  65. nBlocks++;
  66. if (nHeightIn > nHeightLast)
  67. nHeightLast = nHeightIn;
  68. if (nTimeIn > nTimeLast)
  69. nTimeLast = nTimeIn;
  70. }
  71. };
  72. struct CDiskBlockPos
  73. {
  74. int nFile;
  75. unsigned int nPos;
  76. ADD_SERIALIZE_METHODS;
  77. template <typename Stream, typename Operation>
  78. inline void SerializationOp(Stream& s, Operation ser_action) {
  79. READWRITE(VARINT(nFile));
  80. READWRITE(VARINT(nPos));
  81. }
  82. CDiskBlockPos() {
  83. SetNull();
  84. }
  85. CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
  86. nFile = nFileIn;
  87. nPos = nPosIn;
  88. }
  89. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  90. return (a.nFile == b.nFile && a.nPos == b.nPos);
  91. }
  92. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  93. return !(a == b);
  94. }
  95. void SetNull() { nFile = -1; nPos = 0; }
  96. bool IsNull() const { return (nFile == -1); }
  97. std::string ToString() const
  98. {
  99. return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
  100. }
  101. };
  102. enum BlockStatus: uint32_t {
  103. //! Unused.
  104. BLOCK_VALID_UNKNOWN = 0,
  105. //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
  106. BLOCK_VALID_HEADER = 1,
  107. //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
  108. //! are also at least TREE.
  109. BLOCK_VALID_TREE = 2,
  110. /**
  111. * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
  112. * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
  113. * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
  114. */
  115. BLOCK_VALID_TRANSACTIONS = 3,
  116. //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
  117. //! Implies all parents are also at least CHAIN.
  118. BLOCK_VALID_CHAIN = 4,
  119. //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
  120. BLOCK_VALID_SCRIPTS = 5,
  121. //! All validity bits.
  122. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
  123. BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
  124. BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat
  125. BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat
  126. BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
  127. BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed
  128. BLOCK_FAILED_CHILD = 64, //!< descends from failed block
  129. BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
  130. BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client
  131. };
  132. /** The block chain is a tree shaped structure starting with the
  133. * genesis block at the root, with each block potentially having multiple
  134. * candidates to be the next block. A blockindex may have multiple pprev pointing
  135. * to it, but at most one of them can be part of the currently active branch.
  136. */
  137. class CBlockIndex
  138. {
  139. public:
  140. //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
  141. const uint256* phashBlock;
  142. //! pointer to the index of the predecessor of this block
  143. CBlockIndex* pprev;
  144. //! pointer to the index of some further predecessor of this block
  145. CBlockIndex* pskip;
  146. //! height of the entry in the chain. The genesis block has height 0
  147. int nHeight;
  148. //! Which # file this block is stored in (blk?????.dat)
  149. int nFile;
  150. //! Byte offset within blk?????.dat where this block's data is stored
  151. unsigned int nDataPos;
  152. //! Byte offset within rev?????.dat where this block's undo data is stored
  153. unsigned int nUndoPos;
  154. //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
  155. arith_uint256 nChainWork;
  156. //! Number of transactions in this block.
  157. //! Note: in a potential headers-first mode, this number cannot be relied upon
  158. unsigned int nTx;
  159. //! (memory only) Number of transactions in the chain up to and including this block.
  160. //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
  161. //! Change to 64-bit type when necessary; won't happen before 2030
  162. unsigned int nChainTx;
  163. //! Verification status of this block. See enum BlockStatus
  164. unsigned int nStatus;
  165. //! block header
  166. int nVersion;
  167. uint256 hashMerkleRoot;
  168. unsigned int nTime;
  169. unsigned int nBits;
  170. unsigned int nNonce;
  171. //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
  172. int32_t nSequenceId;
  173. //! (memory only) Maximum nTime in the chain upto and including this block.
  174. unsigned int nTimeMax;
  175. void SetNull()
  176. {
  177. phashBlock = nullptr;
  178. pprev = nullptr;
  179. pskip = nullptr;
  180. nHeight = 0;
  181. nFile = 0;
  182. nDataPos = 0;
  183. nUndoPos = 0;
  184. nChainWork = arith_uint256();
  185. nTx = 0;
  186. nChainTx = 0;
  187. nStatus = 0;
  188. nSequenceId = 0;
  189. nTimeMax = 0;
  190. nVersion = 0;
  191. hashMerkleRoot = uint256();
  192. nTime = 0;
  193. nBits = 0;
  194. nNonce = 0;
  195. }
  196. CBlockIndex()
  197. {
  198. SetNull();
  199. }
  200. CBlockIndex(const CBlockHeader& block)
  201. {
  202. SetNull();
  203. nVersion = block.nVersion;
  204. hashMerkleRoot = block.hashMerkleRoot;
  205. nTime = block.nTime;
  206. nBits = block.nBits;
  207. nNonce = block.nNonce;
  208. }
  209. CDiskBlockPos GetBlockPos() const {
  210. CDiskBlockPos ret;
  211. if (nStatus & BLOCK_HAVE_DATA) {
  212. ret.nFile = nFile;
  213. ret.nPos = nDataPos;
  214. }
  215. return ret;
  216. }
  217. CDiskBlockPos GetUndoPos() const {
  218. CDiskBlockPos ret;
  219. if (nStatus & BLOCK_HAVE_UNDO) {
  220. ret.nFile = nFile;
  221. ret.nPos = nUndoPos;
  222. }
  223. return ret;
  224. }
  225. CBlockHeader GetBlockHeader() const
  226. {
  227. CBlockHeader block;
  228. block.nVersion = nVersion;
  229. if (pprev)
  230. block.hashPrevBlock = pprev->GetBlockHash();
  231. block.hashMerkleRoot = hashMerkleRoot;
  232. block.nTime = nTime;
  233. block.nBits = nBits;
  234. block.nNonce = nNonce;
  235. return block;
  236. }
  237. uint256 GetBlockHash() const
  238. {
  239. return *phashBlock;
  240. }
  241. int64_t GetBlockTime() const
  242. {
  243. return (int64_t)nTime;
  244. }
  245. int64_t GetBlockTimeMax() const
  246. {
  247. return (int64_t)nTimeMax;
  248. }
  249. enum { nMedianTimeSpan=11 };
  250. int64_t GetMedianTimePast() const
  251. {
  252. int64_t pmedian[nMedianTimeSpan];
  253. int64_t* pbegin = &pmedian[nMedianTimeSpan];
  254. int64_t* pend = &pmedian[nMedianTimeSpan];
  255. const CBlockIndex* pindex = this;
  256. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  257. *(--pbegin) = pindex->GetBlockTime();
  258. std::sort(pbegin, pend);
  259. return pbegin[(pend - pbegin)/2];
  260. }
  261. std::string ToString() const
  262. {
  263. return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  264. pprev, nHeight,
  265. hashMerkleRoot.ToString(),
  266. GetBlockHash().ToString());
  267. }
  268. //! Check whether this block index entry is valid up to the passed validity level.
  269. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
  270. {
  271. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  272. if (nStatus & BLOCK_FAILED_MASK)
  273. return false;
  274. return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
  275. }
  276. //! Raise the validity level of this block index entry.
  277. //! Returns true if the validity was changed.
  278. bool RaiseValidity(enum BlockStatus nUpTo)
  279. {
  280. assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
  281. if (nStatus & BLOCK_FAILED_MASK)
  282. return false;
  283. if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
  284. nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
  285. return true;
  286. }
  287. return false;
  288. }
  289. //! Build the skiplist pointer for this entry.
  290. void BuildSkip();
  291. //! Efficiently find an ancestor of this block.
  292. CBlockIndex* GetAncestor(int height);
  293. const CBlockIndex* GetAncestor(int height) const;
  294. };
  295. arith_uint256 GetBlockProof(const CBlockIndex& block);
  296. /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */
  297. int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&);
  298. /** Find the forking point between two chain tips. */
  299. const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
  300. /** Used to marshal pointers into hashes for db storage. */
  301. class CDiskBlockIndex : public CBlockIndex
  302. {
  303. public:
  304. uint256 hashPrev;
  305. CDiskBlockIndex() {
  306. hashPrev = uint256();
  307. }
  308. explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
  309. hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
  310. }
  311. ADD_SERIALIZE_METHODS;
  312. template <typename Stream, typename Operation>
  313. inline void SerializationOp(Stream& s, Operation ser_action) {
  314. int _nVersion = s.GetVersion();
  315. if (!(s.GetType() & SER_GETHASH))
  316. READWRITE(VARINT(_nVersion));
  317. READWRITE(VARINT(nHeight));
  318. READWRITE(VARINT(nStatus));
  319. READWRITE(VARINT(nTx));
  320. if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
  321. READWRITE(VARINT(nFile));
  322. if (nStatus & BLOCK_HAVE_DATA)
  323. READWRITE(VARINT(nDataPos));
  324. if (nStatus & BLOCK_HAVE_UNDO)
  325. READWRITE(VARINT(nUndoPos));
  326. // block header
  327. READWRITE(this->nVersion);
  328. READWRITE(hashPrev);
  329. READWRITE(hashMerkleRoot);
  330. READWRITE(nTime);
  331. READWRITE(nBits);
  332. READWRITE(nNonce);
  333. }
  334. uint256 GetBlockHash() const
  335. {
  336. CBlockHeader block;
  337. block.nVersion = nVersion;
  338. block.hashPrevBlock = hashPrev;
  339. block.hashMerkleRoot = hashMerkleRoot;
  340. block.nTime = nTime;
  341. block.nBits = nBits;
  342. block.nNonce = nNonce;
  343. return block.GetHash();
  344. }
  345. std::string ToString() const
  346. {
  347. std::string str = "CDiskBlockIndex(";
  348. str += CBlockIndex::ToString();
  349. str += strprintf("\n hashBlock=%s, hashPrev=%s)",
  350. GetBlockHash().ToString(),
  351. hashPrev.ToString());
  352. return str;
  353. }
  354. };
  355. /** An in-memory indexed chain of blocks. */
  356. class CChain {
  357. private:
  358. std::vector<CBlockIndex*> vChain;
  359. public:
  360. /** Returns the index entry for the genesis block of this chain, or nullptr if none. */
  361. CBlockIndex *Genesis() const {
  362. return vChain.size() > 0 ? vChain[0] : nullptr;
  363. }
  364. /** Returns the index entry for the tip of this chain, or nullptr if none. */
  365. CBlockIndex *Tip() const {
  366. return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr;
  367. }
  368. /** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */
  369. CBlockIndex *operator[](int nHeight) const {
  370. if (nHeight < 0 || nHeight >= (int)vChain.size())
  371. return nullptr;
  372. return vChain[nHeight];
  373. }
  374. /** Compare two chains efficiently. */
  375. friend bool operator==(const CChain &a, const CChain &b) {
  376. return a.vChain.size() == b.vChain.size() &&
  377. a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
  378. }
  379. /** Efficiently check whether a block is present in this chain. */
  380. bool Contains(const CBlockIndex *pindex) const {
  381. return (*this)[pindex->nHeight] == pindex;
  382. }
  383. /** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */
  384. CBlockIndex *Next(const CBlockIndex *pindex) const {
  385. if (Contains(pindex))
  386. return (*this)[pindex->nHeight + 1];
  387. else
  388. return nullptr;
  389. }
  390. /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
  391. int Height() const {
  392. return vChain.size() - 1;
  393. }
  394. /** Set/initialize a chain with a given tip. */
  395. void SetTip(CBlockIndex *pindex);
  396. /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
  397. CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const;
  398. /** Find the last common block between this chain and a block index entry. */
  399. const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
  400. /** Find the earliest block with timestamp equal or greater than the given. */
  401. CBlockIndex* FindEarliestAtLeast(int64_t nTime) const;
  402. };
  403. #endif // STARWELS_CHAIN_H