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>
24 ADD_SERIALIZE_METHODS;
26 template <typename Stream, typename Operation>
27 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
28 READWRITE(VARINT(nFile));
29 READWRITE(VARINT(nPos));
36 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
41 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
42 return (a.nFile == b.nFile && a.nPos == b.nPos);
45 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
49 void SetNull() { nFile = -1; nPos = 0; }
50 bool IsNull() const { return (nFile == -1); }
52 std::string ToString() const
54 return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
61 BLOCK_VALID_UNKNOWN = 0,
63 //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
64 BLOCK_VALID_HEADER = 1,
66 //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
67 //! are also at least TREE.
71 * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
72 * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
73 * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
75 BLOCK_VALID_TRANSACTIONS = 3,
77 //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
78 //! Implies all parents are also at least CHAIN.
79 BLOCK_VALID_CHAIN = 4,
81 //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
82 BLOCK_VALID_SCRIPTS = 5,
84 //! All validity bits.
85 BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
86 BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
88 BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
89 BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
90 BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
92 BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
93 BLOCK_FAILED_CHILD = 64, //! descends from failed block
94 BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
97 /** The block chain is a tree shaped structure starting with the
98 * genesis block at the root, with each block potentially having multiple
99 * candidates to be the next block. A blockindex may have multiple pprev pointing
100 * to it, but at most one of them can be part of the currently active branch.
105 //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
106 const uint256* phashBlock;
108 //! pointer to the index of the predecessor of this block
111 //! pointer to the index of some further predecessor of this block
114 //! height of the entry in the chain. The genesis block has height 0
117 //! Which # file this block is stored in (blk?????.dat)
120 //! Byte offset within blk?????.dat where this block's data is stored
121 unsigned int nDataPos;
123 //! Byte offset within rev?????.dat where this block's undo data is stored
124 unsigned int nUndoPos;
126 //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
127 arith_uint256 nChainWork;
129 //! Number of transactions in this block.
130 //! Note: in a potential headers-first mode, this number cannot be relied upon
133 //! (memory only) Number of transactions in the chain up to and including this block.
134 //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
135 //! Change to 64-bit type when necessary; won't happen before 2030
136 unsigned int nChainTx;
138 //! Verification status of this block. See enum BlockStatus
139 unsigned int nStatus;
143 uint256 hashMerkleRoot;
144 uint256 hashReserved;
148 std::vector<uint32_t> nSolution;
150 //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
151 uint32_t nSequenceId;
162 nChainWork = arith_uint256();
169 hashMerkleRoot = uint256();
170 hashReserved = uint256();
182 CBlockIndex(const CBlockHeader& block)
186 nVersion = block.nVersion;
187 hashMerkleRoot = block.hashMerkleRoot;
188 hashReserved = block.hashReserved;
191 nNonce = block.nNonce;
192 nSolution = block.nSolution;
195 CDiskBlockPos GetBlockPos() const {
197 if (nStatus & BLOCK_HAVE_DATA) {
204 CDiskBlockPos GetUndoPos() const {
206 if (nStatus & BLOCK_HAVE_UNDO) {
213 CBlockHeader GetBlockHeader() const
216 block.nVersion = nVersion;
218 block.hashPrevBlock = pprev->GetBlockHash();
219 block.hashMerkleRoot = hashMerkleRoot;
220 block.hashReserved = hashReserved;
223 block.nNonce = nNonce;
224 block.nSolution = nSolution;
228 uint256 GetBlockHash() const
233 int64_t GetBlockTime() const
235 return (int64_t)nTime;
238 enum { nMedianTimeSpan=11 };
240 int64_t GetMedianTimePast() const
242 int64_t pmedian[nMedianTimeSpan];
243 int64_t* pbegin = &pmedian[nMedianTimeSpan];
244 int64_t* pend = &pmedian[nMedianTimeSpan];
246 const CBlockIndex* pindex = this;
247 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
248 *(--pbegin) = pindex->GetBlockTime();
250 std::sort(pbegin, pend);
251 return pbegin[(pend - pbegin)/2];
254 std::string ToString() const
256 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
258 hashMerkleRoot.ToString(),
259 GetBlockHash().ToString());
262 //! Check whether this block index entry is valid up to the passed validity level.
263 bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
265 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
266 if (nStatus & BLOCK_FAILED_MASK)
268 return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
271 //! Raise the validity level of this block index entry.
272 //! Returns true if the validity was changed.
273 bool RaiseValidity(enum BlockStatus nUpTo)
275 assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
276 if (nStatus & BLOCK_FAILED_MASK)
278 if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
279 nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
285 //! Build the skiplist pointer for this entry.
288 //! Efficiently find an ancestor of this block.
289 CBlockIndex* GetAncestor(int height);
290 const CBlockIndex* GetAncestor(int height) const;
293 /** Used to marshal pointers into hashes for db storage. */
294 class CDiskBlockIndex : public CBlockIndex
300 hashPrev = uint256();
303 explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
304 hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
307 ADD_SERIALIZE_METHODS;
309 template <typename Stream, typename Operation>
310 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
311 if (!(nType & SER_GETHASH))
312 READWRITE(VARINT(nVersion));
314 READWRITE(VARINT(nHeight));
315 READWRITE(VARINT(nStatus));
316 READWRITE(VARINT(nTx));
317 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
318 READWRITE(VARINT(nFile));
319 if (nStatus & BLOCK_HAVE_DATA)
320 READWRITE(VARINT(nDataPos));
321 if (nStatus & BLOCK_HAVE_UNDO)
322 READWRITE(VARINT(nUndoPos));
325 READWRITE(this->nVersion);
327 READWRITE(hashMerkleRoot);
328 READWRITE(hashReserved);
332 READWRITE(nSolution);
335 uint256 GetBlockHash() const
338 block.nVersion = nVersion;
339 block.hashPrevBlock = hashPrev;
340 block.hashMerkleRoot = hashMerkleRoot;
341 block.hashReserved = hashReserved;
344 block.nNonce = nNonce;
345 block.nSolution = nSolution;
346 return block.GetHash();
350 std::string ToString() const
352 std::string str = "CDiskBlockIndex(";
353 str += CBlockIndex::ToString();
354 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
355 GetBlockHash().ToString(),
356 hashPrev.ToString());
361 /** An in-memory indexed chain of blocks. */
364 std::vector<CBlockIndex*> vChain;
367 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
368 CBlockIndex *Genesis() const {
369 return vChain.size() > 0 ? vChain[0] : NULL;
372 /** Returns the index entry for the tip of this chain, or NULL if none. */
373 CBlockIndex *Tip() const {
374 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
377 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
378 CBlockIndex *operator[](int nHeight) const {
379 if (nHeight < 0 || nHeight >= (int)vChain.size())
381 return vChain[nHeight];
384 /** Compare two chains efficiently. */
385 friend bool operator==(const CChain &a, const CChain &b) {
386 return a.vChain.size() == b.vChain.size() &&
387 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
390 /** Efficiently check whether a block is present in this chain. */
391 bool Contains(const CBlockIndex *pindex) const {
392 return (*this)[pindex->nHeight] == pindex;
395 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
396 CBlockIndex *Next(const CBlockIndex *pindex) const {
397 if (Contains(pindex))
398 return (*this)[pindex->nHeight + 1];
403 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
405 return vChain.size() - 1;
408 /** Set/initialize a chain with a given tip. */
409 void SetTip(CBlockIndex *pindex);
411 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
412 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
414 /** Find the last common block between this chain and a block index entry. */
415 const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
418 #endif // BITCOIN_CHAIN_H