1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_CHAIN_H
7 #define BITCOIN_CHAIN_H
9 #include "arith_uint256.h"
10 #include "primitives/block.h"
12 #include "tinyformat.h"
17 #include <boost/foreach.hpp>
19 static const int SPROUT_VALUE_VERSION = 1001400;
26 ADD_SERIALIZE_METHODS;
28 template <typename Stream, typename Operation>
29 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
30 READWRITE(VARINT(nFile));
31 READWRITE(VARINT(nPos));
38 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
43 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
44 return (a.nFile == b.nFile && a.nPos == b.nPos);
47 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
51 void SetNull() { nFile = -1; nPos = 0; }
52 bool IsNull() const { return (nFile == -1); }
54 std::string ToString() const
56 return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
61 enum BlockStatus: uint32_t {
63 BLOCK_VALID_UNKNOWN = 0,
65 //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
66 BLOCK_VALID_HEADER = 1,
68 //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
69 //! are also at least TREE.
73 * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
74 * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
75 * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
77 BLOCK_VALID_TRANSACTIONS = 3,
79 //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
80 //! Implies all parents are also at least CHAIN.
81 BLOCK_VALID_CHAIN = 4,
83 //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
84 BLOCK_VALID_SCRIPTS = 5,
86 //! All validity bits.
87 BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
88 BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
90 BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
91 BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
92 BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
94 BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
95 BLOCK_FAILED_CHILD = 64, //! descends from failed block
96 BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
98 BLOCK_ACTIVATES_UPGRADE = 128, //! block activates a network upgrade
101 //! Short-hand for the highest consensus validity we implement.
102 //! Blocks with this validity are assumed to satisfy all consensus rules.
103 static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS;
105 /** The block chain is a tree shaped structure starting with the
106 * genesis block at the root, with each block potentially having multiple
107 * candidates to be the next block. A blockindex may have multiple pprev pointing
108 * to it, but at most one of them can be part of the currently active branch.
113 //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
114 const uint256* phashBlock;
116 //! pointer to the index of the predecessor of this block
119 //! pointer to the index of some further predecessor of this block
122 //! height of the entry in the chain. The genesis block has height 0
124 int64_t newcoins,zfunds;
125 //! Which # file this block is stored in (blk?????.dat)
128 //! Byte offset within blk?????.dat where this block's data is stored
129 unsigned int nDataPos;
131 //! Byte offset within rev?????.dat where this block's undo data is stored
132 unsigned int nUndoPos;
134 //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
135 arith_uint256 nChainWork;
137 //! Number of transactions in this block.
138 //! Note: in a potential headers-first mode, this number cannot be relied upon
141 //! (memory only) Number of transactions in the chain up to and including this block.
142 //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
143 //! Change to 64-bit type when necessary; won't happen before 2030
144 unsigned int nChainTx;
146 //! Verification status of this block. See enum BlockStatus
147 unsigned int nStatus;
149 //! Branch ID corresponding to the consensus rules used to validate this block.
150 //! Only cached if block validity is BLOCK_VALID_CONSENSUS.
151 //! Persisted at each activation height, memory-only for intervening blocks.
152 boost::optional<uint32_t> nCachedBranchId;
154 //! The anchor for the tree state up to the start of this block
157 //! (memory only) The anchor for the tree state up to the end of this block
158 uint256 hashAnchorEnd;
160 //! Change in value held by the Sprout circuit over this block.
161 //! Will be boost::none for older blocks on old nodes until a reindex has taken place.
162 boost::optional<CAmount> nSproutValue;
164 //! (memory only) Total value held by the Sprout circuit up to and including this block.
165 //! Will be boost::none for on old nodes until a reindex has taken place.
166 //! Will be boost::none if nChainTx is zero.
167 boost::optional<CAmount> nChainSproutValue;
171 uint256 hashMerkleRoot;
172 uint256 hashReserved;
176 std::vector<unsigned char> nSolution;
178 //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
179 uint32_t nSequenceId;
184 newcoins = zfunds = 0;
191 nChainWork = arith_uint256();
195 nCachedBranchId = boost::none;
196 hashAnchor = uint256();
197 hashAnchorEnd = uint256();
199 nSproutValue = boost::none;
200 nChainSproutValue = boost::none;
203 hashMerkleRoot = uint256();
204 hashReserved = uint256();
216 CBlockIndex(const CBlockHeader& block)
220 nVersion = block.nVersion;
221 hashMerkleRoot = block.hashMerkleRoot;
222 hashReserved = block.hashReserved;
225 nNonce = block.nNonce;
226 nSolution = block.nSolution;
229 CDiskBlockPos GetBlockPos() const {
231 if (nStatus & BLOCK_HAVE_DATA) {
238 CDiskBlockPos GetUndoPos() const {
240 if (nStatus & BLOCK_HAVE_UNDO) {
247 CBlockHeader GetBlockHeader() const
250 block.nVersion = nVersion;
252 block.hashPrevBlock = pprev->GetBlockHash();
253 block.hashMerkleRoot = hashMerkleRoot;
254 block.hashReserved = hashReserved;
257 block.nNonce = nNonce;
258 block.nSolution = nSolution;
262 uint256 GetBlockHash() const
267 int64_t GetBlockTime() const
269 return (int64_t)nTime;
272 enum { nMedianTimeSpan=11 };
274 int64_t GetMedianTimePast() const
276 int64_t pmedian[nMedianTimeSpan];
277 int64_t* pbegin = &pmedian[nMedianTimeSpan];
278 int64_t* pend = &pmedian[nMedianTimeSpan];
280 const CBlockIndex* pindex = this;
281 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
282 *(--pbegin) = pindex->GetBlockTime();
284 std::sort(pbegin, pend);
285 return pbegin[(pend - pbegin)/2];
288 std::string ToString() const
290 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
292 hashMerkleRoot.ToString(),
293 GetBlockHash().ToString());
296 //! Check whether this block index entry is valid up to the passed validity level.
297 bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
299 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
300 if (nStatus & BLOCK_FAILED_MASK)
302 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
305 //! Raise the validity level of this block index entry.
306 //! Returns true if the validity was changed.
307 bool RaiseValidity(enum BlockStatus nUpTo)
309 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
310 if (nStatus & BLOCK_FAILED_MASK)
312 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
313 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
319 //! Build the skiplist pointer for this entry.
322 //! Efficiently find an ancestor of this block.
323 CBlockIndex* GetAncestor(int height);
324 const CBlockIndex* GetAncestor(int height) const;
328 /** Used to marshal pointers into hashes for db storage. */
329 class CDiskBlockIndex : public CBlockIndex
335 hashPrev = uint256();
338 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
339 hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
342 ADD_SERIALIZE_METHODS;
344 template <typename Stream, typename Operation>
345 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
346 if (!(nType & SER_GETHASH))
347 READWRITE(VARINT(nVersion));
349 READWRITE(VARINT(nHeight));
350 READWRITE(VARINT(nStatus));
351 READWRITE(VARINT(nTx));
352 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
353 READWRITE(VARINT(nFile));
354 if (nStatus & BLOCK_HAVE_DATA)
355 READWRITE(VARINT(nDataPos));
356 if (nStatus & BLOCK_HAVE_UNDO)
357 READWRITE(VARINT(nUndoPos));
358 if (nStatus & BLOCK_ACTIVATES_UPGRADE) {
359 if (ser_action.ForRead()) {
362 nCachedBranchId = branchId;
364 // nCachedBranchId must always be set if BLOCK_ACTIVATES_UPGRADE is set.
365 assert(nCachedBranchId);
366 uint32_t branchId = *nCachedBranchId;
370 READWRITE(hashAnchor);
373 READWRITE(this->nVersion);
375 READWRITE(hashMerkleRoot);
376 READWRITE(hashReserved);
380 READWRITE(nSolution);
382 // Only read/write nSproutValue if the client version used to create
383 // this index was storing them.
384 if ((nType & SER_DISK) && (nVersion >= SPROUT_VALUE_VERSION)) {
385 READWRITE(nSproutValue);
389 uint256 GetBlockHash() const
392 block.nVersion = nVersion;
393 block.hashPrevBlock = hashPrev;
394 block.hashMerkleRoot = hashMerkleRoot;
395 block.hashReserved = hashReserved;
398 block.nNonce = nNonce;
399 block.nSolution = nSolution;
400 return block.GetHash();
404 std::string ToString() const
406 std::string str = "CDiskBlockIndex(";
407 str += CBlockIndex::ToString();
408 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
409 GetBlockHash().ToString(),
410 hashPrev.ToString());
415 /** An in-memory indexed chain of blocks. */
418 std::vector<CBlockIndex*> vChain;
419 CBlockIndex *lastTip;
422 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
423 CBlockIndex *Genesis() const {
424 return vChain.size() > 0 ? vChain[0] : NULL;
427 /** Returns the index entry for the tip of this chain, or NULL if none. */
428 CBlockIndex *Tip() const {
429 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
432 /** Returns the last tip of the chain, or NULL if none. */
433 CBlockIndex *LastTip() const {
434 return vChain.size() > 0 ? lastTip : NULL;
437 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
438 CBlockIndex *operator[](int nHeight) const {
439 if (nHeight < 0 || nHeight >= (int)vChain.size())
441 return vChain[nHeight];
444 /** Compare two chains efficiently. */
445 friend bool operator==(const CChain &a, const CChain &b) {
446 return a.vChain.size() == b.vChain.size() &&
447 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
450 /** Efficiently check whether a block is present in this chain. */
451 bool Contains(const CBlockIndex *pindex) const {
452 return (*this)[pindex->nHeight] == pindex;
455 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
456 CBlockIndex *Next(const CBlockIndex *pindex) const {
457 if (Contains(pindex))
458 return (*this)[pindex->nHeight + 1];
463 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
465 return vChain.size() - 1;
468 /** Set/initialize a chain with a given tip. */
469 void SetTip(CBlockIndex *pindex);
471 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
472 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
474 /** Find the last common block between this chain and a block index entry. */
475 const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
478 #endif // BITCOIN_CHAIN_H