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;
20 static const int SAPLING_VALUE_VERSION = 1010100;
27 ADD_SERIALIZE_METHODS;
29 template <typename Stream, typename Operation>
30 inline void SerializationOp(Stream& s, Operation ser_action) {
31 READWRITE(VARINT(nFile));
32 READWRITE(VARINT(nPos));
39 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
44 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
45 return (a.nFile == b.nFile && a.nPos == b.nPos);
48 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
52 void SetNull() { nFile = -1; nPos = 0; }
53 bool IsNull() const { return (nFile == -1); }
55 std::string ToString() const
57 return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
62 enum BlockStatus: uint32_t {
64 BLOCK_VALID_UNKNOWN = 0,
66 //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
67 BLOCK_VALID_HEADER = 1,
69 //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
70 //! are also at least TREE.
74 * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
75 * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
76 * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
78 BLOCK_VALID_TRANSACTIONS = 3,
80 //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
81 //! Implies all parents are also at least CHAIN.
82 BLOCK_VALID_CHAIN = 4,
84 //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
85 BLOCK_VALID_SCRIPTS = 5,
87 //! All validity bits.
88 BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
89 BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
91 BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
92 BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
93 BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
95 BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
96 BLOCK_FAILED_CHILD = 64, //! descends from failed block
97 BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
99 BLOCK_ACTIVATES_UPGRADE = 128, //! block activates a network upgrade
102 //! Short-hand for the highest consensus validity we implement.
103 //! Blocks with this validity are assumed to satisfy all consensus rules.
104 static const BlockStatus BLOCK_VALID_CONSENSUS = BLOCK_VALID_SCRIPTS;
106 /** The block chain is a tree shaped structure starting with the
107 * genesis block at the root, with each block potentially having multiple
108 * candidates to be the next block. A blockindex may have multiple pprev pointing
109 * to it, but at most one of them can be part of the currently active branch.
114 //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
115 const uint256* phashBlock;
117 //! pointer to the index of the predecessor of this block
120 //! pointer to the index of some further predecessor of this block
123 //! height of the entry in the chain. The genesis block has height 0
126 //! Which # file this block is stored in (blk?????.dat)
129 //! Byte offset within blk?????.dat where this block's data is stored
130 unsigned int nDataPos;
132 //! Byte offset within rev?????.dat where this block's undo data is stored
133 unsigned int nUndoPos;
135 //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
136 arith_uint256 nChainWork;
138 //! Number of transactions in this block.
139 //! Note: in a potential headers-first mode, this number cannot be relied upon
142 //! (memory only) Number of transactions in the chain up to and including this block.
143 //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
144 //! Change to 64-bit type when necessary; won't happen before 2030
145 unsigned int nChainTx;
147 //! Verification status of this block. See enum BlockStatus
148 unsigned int nStatus;
150 //! Branch ID corresponding to the consensus rules used to validate this block.
151 //! Only cached if block validity is BLOCK_VALID_CONSENSUS.
152 //! Persisted at each activation height, memory-only for intervening blocks.
153 boost::optional<uint32_t> nCachedBranchId;
155 //! The anchor for the tree state up to the start of this block
156 uint256 hashSproutAnchor;
158 //! (memory only) The anchor for the tree state up to the end of this block
159 uint256 hashFinalSproutRoot;
161 //! Change in value held by the Sprout circuit over this block.
162 //! Will be boost::none for older blocks on old nodes until a reindex has taken place.
163 boost::optional<CAmount> nSproutValue;
165 //! (memory only) Total value held by the Sprout circuit up to and including this block.
166 //! Will be boost::none for on old nodes until a reindex has taken place.
167 //! Will be boost::none if nChainTx is zero.
168 boost::optional<CAmount> nChainSproutValue;
170 //! Change in value held by the Sapling circuit over this block.
171 //! Not a boost::optional because this was added before Sapling activated, so we can
172 //! rely on the invariant that every block before this was added had nSaplingValue = 0.
173 CAmount nSaplingValue;
175 //! (memory only) Total value held by the Sapling circuit up to and including this block.
176 //! Will be boost::none if nChainTx is zero.
177 boost::optional<CAmount> nChainSaplingValue;
181 uint256 hashMerkleRoot;
182 uint256 hashFinalSaplingRoot;
186 std::vector<unsigned char> nSolution;
188 //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
189 uint32_t nSequenceId;
200 nChainWork = arith_uint256();
204 nCachedBranchId = boost::none;
205 hashSproutAnchor = uint256();
206 hashFinalSproutRoot = uint256();
208 nSproutValue = boost::none;
209 nChainSproutValue = boost::none;
211 nChainSaplingValue = boost::none;
214 hashMerkleRoot = uint256();
215 hashFinalSaplingRoot = uint256();
227 CBlockIndex(const CBlockHeader& block)
231 nVersion = block.nVersion;
232 hashMerkleRoot = block.hashMerkleRoot;
233 hashFinalSaplingRoot = block.hashFinalSaplingRoot;
236 nNonce = block.nNonce;
237 nSolution = block.nSolution;
240 CDiskBlockPos GetBlockPos() const {
242 if (nStatus & BLOCK_HAVE_DATA) {
249 CDiskBlockPos GetUndoPos() const {
251 if (nStatus & BLOCK_HAVE_UNDO) {
258 CBlockHeader GetBlockHeader() const
261 block.nVersion = nVersion;
263 block.hashPrevBlock = pprev->GetBlockHash();
264 block.hashMerkleRoot = hashMerkleRoot;
265 block.hashFinalSaplingRoot = hashFinalSaplingRoot;
268 block.nNonce = nNonce;
269 block.nSolution = nSolution;
273 uint256 GetBlockHash() const
278 int64_t GetBlockTime() const
280 return (int64_t)nTime;
283 enum { nMedianTimeSpan=11 };
285 int64_t GetMedianTimePast() const
287 int64_t pmedian[nMedianTimeSpan];
288 int64_t* pbegin = &pmedian[nMedianTimeSpan];
289 int64_t* pend = &pmedian[nMedianTimeSpan];
291 const CBlockIndex* pindex = this;
292 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
293 *(--pbegin) = pindex->GetBlockTime();
295 std::sort(pbegin, pend);
296 return pbegin[(pend - pbegin)/2];
299 std::string ToString() const
301 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
303 hashMerkleRoot.ToString(),
304 GetBlockHash().ToString());
307 //! Check whether this block index entry is valid up to the passed validity level.
308 bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
310 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
311 if (nStatus & BLOCK_FAILED_MASK)
313 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
316 //! Raise the validity level of this block index entry.
317 //! Returns true if the validity was changed.
318 bool RaiseValidity(enum BlockStatus nUpTo)
320 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
321 if (nStatus & BLOCK_FAILED_MASK)
323 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
324 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
330 //! Build the skiplist pointer for this entry.
333 //! Efficiently find an ancestor of this block.
334 CBlockIndex* GetAncestor(int height);
335 const CBlockIndex* GetAncestor(int height) const;
338 /** Used to marshal pointers into hashes for db storage. */
339 class CDiskBlockIndex : public CBlockIndex
345 hashPrev = uint256();
348 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
349 hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
352 ADD_SERIALIZE_METHODS;
354 template <typename Stream, typename Operation>
355 inline void SerializationOp(Stream& s, Operation ser_action) {
356 int nVersion = s.GetVersion();
357 if (!(s.GetType() & SER_GETHASH))
358 READWRITE(VARINT(nVersion));
360 READWRITE(VARINT(nHeight));
361 READWRITE(VARINT(nStatus));
362 READWRITE(VARINT(nTx));
363 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
364 READWRITE(VARINT(nFile));
365 if (nStatus & BLOCK_HAVE_DATA)
366 READWRITE(VARINT(nDataPos));
367 if (nStatus & BLOCK_HAVE_UNDO)
368 READWRITE(VARINT(nUndoPos));
369 if (nStatus & BLOCK_ACTIVATES_UPGRADE) {
370 if (ser_action.ForRead()) {
373 nCachedBranchId = branchId;
375 // nCachedBranchId must always be set if BLOCK_ACTIVATES_UPGRADE is set.
376 assert(nCachedBranchId);
377 uint32_t branchId = *nCachedBranchId;
381 READWRITE(hashSproutAnchor);
384 READWRITE(this->nVersion);
386 READWRITE(hashMerkleRoot);
387 READWRITE(hashFinalSaplingRoot);
391 READWRITE(nSolution);
393 // Only read/write nSproutValue if the client version used to create
394 // this index was storing them.
395 if ((s.GetType() & SER_DISK) && (nVersion >= SPROUT_VALUE_VERSION)) {
396 READWRITE(nSproutValue);
399 // Only read/write nSaplingValue if the client version used to create
400 // this index was storing them.
401 if ((s.GetType() & SER_DISK) && (nVersion >= SAPLING_VALUE_VERSION)) {
402 READWRITE(nSaplingValue);
405 // If you have just added new serialized fields above, remember to add
406 // them to CBlockTreeDB::LoadBlockIndexGuts() in txdb.cpp :)
409 uint256 GetBlockHash() const
412 block.nVersion = nVersion;
413 block.hashPrevBlock = hashPrev;
414 block.hashMerkleRoot = hashMerkleRoot;
415 block.hashFinalSaplingRoot = hashFinalSaplingRoot;
418 block.nNonce = nNonce;
419 block.nSolution = nSolution;
420 return block.GetHash();
424 std::string ToString() const
426 std::string str = "CDiskBlockIndex(";
427 str += CBlockIndex::ToString();
428 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
429 GetBlockHash().ToString(),
430 hashPrev.ToString());
435 /** An in-memory indexed chain of blocks. */
438 std::vector<CBlockIndex*> vChain;
441 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
442 CBlockIndex *Genesis() const {
443 return vChain.size() > 0 ? vChain[0] : NULL;
446 /** Returns the index entry for the tip of this chain, or NULL if none. */
447 CBlockIndex *Tip() const {
448 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
451 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
452 CBlockIndex *operator[](int nHeight) const {
453 if (nHeight < 0 || nHeight >= (int)vChain.size())
455 return vChain[nHeight];
458 /** Compare two chains efficiently. */
459 friend bool operator==(const CChain &a, const CChain &b) {
460 return a.vChain.size() == b.vChain.size() &&
461 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
464 /** Efficiently check whether a block is present in this chain. */
465 bool Contains(const CBlockIndex *pindex) const {
466 return (*this)[pindex->nHeight] == pindex;
469 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
470 CBlockIndex *Next(const CBlockIndex *pindex) const {
471 if (Contains(pindex))
472 return (*this)[pindex->nHeight + 1];
477 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
479 return vChain.size() - 1;
482 /** Set/initialize a chain with a given tip. */
483 void SetTip(CBlockIndex *pindex);
485 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
486 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
488 /** Find the last common block between this chain and a block index entry. */
489 const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
492 #endif // BITCOIN_CHAIN_H